]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
Maildir synchronization
[notmuch] / notmuch-new.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22
23 #include <unistd.h>
24
25 typedef struct _filename_node {
26     char *filename;
27     struct _filename_node *next;
28 } _filename_node_t;
29
30 typedef struct _filename_list {
31     _filename_node_t *head;
32     _filename_node_t **tail;
33 } _filename_list_t;
34
35 typedef struct {
36     int output_is_a_tty;
37     int verbose;
38     const char **new_tags;
39     size_t new_tags_length;
40
41     int total_files;
42     int processed_files;
43     int added_messages;
44     struct timeval tv_start;
45
46     _filename_list_t *removed_files;
47     _filename_list_t *removed_directories;
48 } add_files_state_t;
49
50 static volatile sig_atomic_t do_add_files_print_progress = 0;
51
52 static void
53 handle_sigalrm (unused (int signal))
54 {
55     do_add_files_print_progress = 1;
56 }
57
58 static volatile sig_atomic_t interrupted;
59
60 static void
61 handle_sigint (unused (int sig))
62 {
63     ssize_t ignored;
64     static char msg[] = "Stopping...         \n";
65
66     ignored = write(2, msg, sizeof(msg)-1);
67     interrupted = 1;
68 }
69
70 static _filename_list_t *
71 _filename_list_create (const void *ctx)
72 {
73     _filename_list_t *list;
74
75     list = talloc (ctx, _filename_list_t);
76     if (list == NULL)
77         return NULL;
78
79     list->head = NULL;
80     list->tail = &list->head;
81
82     return list;
83 }
84
85 static void
86 _filename_list_add (_filename_list_t *list,
87                     const char *filename)
88 {
89     _filename_node_t *node = talloc (list, _filename_node_t);
90
91     node->filename = talloc_strdup (list, filename);
92     node->next = NULL;
93
94     *(list->tail) = node;
95     list->tail = &node->next;
96 }
97
98 static void
99 add_files_print_progress (add_files_state_t *state)
100 {
101     struct timeval tv_now;
102     double elapsed_overall, rate_overall;
103
104     gettimeofday (&tv_now, NULL);
105
106     elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
107     rate_overall = (state->processed_files) / elapsed_overall;
108
109     printf ("Processed %d", state->processed_files);
110
111     if (state->total_files) {
112         double time_remaining;
113
114         time_remaining = ((state->total_files - state->processed_files) /
115                           rate_overall);
116         printf (" of %d files (", state->total_files);
117         notmuch_time_print_formatted_seconds (time_remaining);
118         printf (" remaining).      \r");
119     } else {
120         printf (" files (%d files/sec.)    \r", (int) rate_overall);
121     }
122
123     fflush (stdout);
124 }
125
126 static int
127 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
128 {
129     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
130 }
131
132 static int
133 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
134 {
135     return strcmp ((*a)->d_name, (*b)->d_name);
136 }
137
138 /* Test if the directory looks like a Maildir directory.
139  *
140  * Search through the array of directory entries to see if we can find all
141  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
142  *
143  * Return 1 if the directory looks like a Maildir and 0 otherwise.
144  */
145 static int
146 _entries_resemble_maildir (struct dirent **entries, int count)
147 {
148     int i, found = 0;
149
150     for (i = 0; i < count; i++) {
151         if (entries[i]->d_type != DT_DIR && entries[i]->d_type != DT_UNKNOWN)
152             continue;
153
154         if (strcmp(entries[i]->d_name, "new") == 0 ||
155             strcmp(entries[i]->d_name, "cur") == 0 ||
156             strcmp(entries[i]->d_name, "tmp") == 0)
157         {
158             found++;
159             if (found == 3)
160                 return 1;
161         }
162     }
163
164     return 0;
165 }
166
167 /* Examine 'path' recursively as follows:
168  *
169  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
170  *   o Ask the database for its timestamp of 'path' (db_mtime)
171  *
172  *   o Ask the filesystem for files and directories within 'path'
173  *     (via scandir and stored in fs_entries)
174  *   o Ask the database for files and directories within 'path'
175  *     (db_files and db_subdirs)
176  *
177  *   o Pass 1: For each directory in fs_entries, recursively call into
178  *     this same function.
179  *
180  *   o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
181  *     simultaneously with db_files and db_subdirs. Look for one of
182  *     three interesting cases:
183  *
184  *         1. Regular file in fs_entries and not in db_files
185  *            This is a new file to add_message into the database.
186  *
187  *         2. Filename in db_files not in fs_entries.
188  *            This is a file that has been removed from the mail store.
189  *
190  *         3. Directory in db_subdirs not in fs_entries
191  *            This is a directory that has been removed from the mail store.
192  *
193  *     Note that the addition of a directory is not interesting here,
194  *     since that will have been taken care of in pass 1. Also, we
195  *     don't immediately act on file/directory removal since we must
196  *     ensure that in the case of a rename that the new filename is
197  *     added before the old filename is removed, (so that no
198  *     information is lost from the database).
199  *
200  *   o Tell the database to update its time of 'path' to 'fs_mtime'
201  */
202 static notmuch_status_t
203 add_files_recursive (notmuch_database_t *notmuch,
204                      const char *path,
205                      add_files_state_t *state)
206 {
207     DIR *dir = NULL;
208     struct dirent *entry = NULL;
209     char *next = NULL;
210     time_t fs_mtime, db_mtime;
211     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
212     notmuch_message_t *message = NULL;
213     struct dirent **fs_entries = NULL;
214     int i, num_fs_entries;
215     notmuch_directory_t *directory;
216     notmuch_filenames_t *db_files = NULL;
217     notmuch_filenames_t *db_subdirs = NULL;
218     struct stat st;
219     notmuch_bool_t is_maildir, new_directory;
220     const char **tag;
221
222     if (stat (path, &st)) {
223         fprintf (stderr, "Error reading directory %s: %s\n",
224                  path, strerror (errno));
225         return NOTMUCH_STATUS_FILE_ERROR;
226     }
227
228     /* This is not an error since we may have recursed based on a
229      * symlink to a regular file, not a directory, and we don't know
230      * that until this stat. */
231     if (! S_ISDIR (st.st_mode))
232         return NOTMUCH_STATUS_SUCCESS;
233
234     fs_mtime = st.st_mtime;
235
236     directory = notmuch_database_get_directory (notmuch, path);
237     db_mtime = notmuch_directory_get_mtime (directory);
238
239     if (db_mtime == 0) {
240         new_directory = TRUE;
241         db_files = NULL;
242         db_subdirs = NULL;
243     } else {
244         new_directory = FALSE;
245         db_files = notmuch_directory_get_child_files (directory);
246         db_subdirs = notmuch_directory_get_child_directories (directory);
247     }
248
249     /* If the database knows about this directory, then we sort based
250      * on strcmp to match the database sorting. Otherwise, we can do
251      * inode-based sorting for faster filesystem operation. */
252     num_fs_entries = scandir (path, &fs_entries, 0,
253                               new_directory ?
254                               dirent_sort_inode : dirent_sort_strcmp_name);
255
256     if (num_fs_entries == -1) {
257         fprintf (stderr, "Error opening directory %s: %s\n",
258                  path, strerror (errno));
259         ret = NOTMUCH_STATUS_FILE_ERROR;
260         goto DONE;
261     }
262
263     /* Pass 1: Recurse into all sub-directories. */
264     is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
265
266     for (i = 0; i < num_fs_entries; i++) {
267         if (interrupted)
268             break;
269
270         entry = fs_entries[i];
271
272         /* We only want to descend into directories.
273          * But symlinks can be to directories too, of course.
274          *
275          * And if the filesystem doesn't tell us the file type in the
276          * scandir results, then it might be a directory (and if not,
277          * then we'll stat and return immediately in the next level of
278          * recursion). */
279         if (entry->d_type != DT_DIR &&
280             entry->d_type != DT_LNK &&
281             entry->d_type != DT_UNKNOWN)
282         {
283             continue;
284         }
285
286         /* Ignore special directories to avoid infinite recursion.
287          * Also ignore the .notmuch directory and any "tmp" directory
288          * that appears within a maildir.
289          */
290         /* XXX: Eventually we'll want more sophistication to let the
291          * user specify files to be ignored. */
292         if (strcmp (entry->d_name, ".") == 0 ||
293             strcmp (entry->d_name, "..") == 0 ||
294             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
295             strcmp (entry->d_name, ".notmuch") ==0)
296         {
297             continue;
298         }
299
300         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
301         status = add_files_recursive (notmuch, next, state);
302         if (status && ret == NOTMUCH_STATUS_SUCCESS)
303             ret = status;
304         talloc_free (next);
305         next = NULL;
306     }
307
308     /* If this directory hasn't been modified since the last
309      * "notmuch new", then we can skip the second pass entirely. */
310     if (fs_mtime <= db_mtime)
311         goto DONE;
312
313     /* Pass 2: Scan for new files, removed files, and removed directories. */
314     for (i = 0; i < num_fs_entries; i++)
315     {
316         if (interrupted)
317             break;
318
319         entry = fs_entries[i];
320
321         /* Check if we've walked past any names in db_files or
322          * db_subdirs. If so, these have been deleted. */
323         while (notmuch_filenames_valid (db_files) &&
324                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
325         {
326             char *absolute = talloc_asprintf (state->removed_files,
327                                               "%s/%s", path,
328                                               notmuch_filenames_get (db_files));
329
330             _filename_list_add (state->removed_files, absolute);
331
332             notmuch_filenames_move_to_next (db_files);
333         }
334
335         while (notmuch_filenames_valid (db_subdirs) &&
336                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
337         {
338             const char *filename = notmuch_filenames_get (db_subdirs);
339
340             if (strcmp (filename, entry->d_name) < 0)
341             {
342                 char *absolute = talloc_asprintf (state->removed_directories,
343                                                   "%s/%s", path, filename);
344
345                 _filename_list_add (state->removed_directories, absolute);
346             }
347
348             notmuch_filenames_move_to_next (db_subdirs);
349         }
350
351         /* If we're looking at a symlink, we only want to add it if it
352          * links to a regular file, (and not to a directory, say).
353          *
354          * Similarly, if the file is of unknown type (due to filesytem
355          * limitations), then we also need to look closer.
356          *
357          * In either case, a stat does the trick.
358          */
359         if (entry->d_type == DT_LNK || entry->d_type == DT_UNKNOWN) {
360             int err;
361
362             next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
363             err = stat (next, &st);
364             talloc_free (next);
365             next = NULL;
366
367             /* Don't emit an error for a link pointing nowhere, since
368              * the directory-traversal pass will have already done
369              * that. */
370             if (err)
371                 continue;
372
373             if (! S_ISREG (st.st_mode))
374                 continue;
375         } else if (entry->d_type != DT_REG) {
376             continue;
377         }
378
379         /* Don't add a file that we've added before. */
380         if (notmuch_filenames_valid (db_files) &&
381             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
382         {
383             notmuch_filenames_move_to_next (db_files);
384             continue;
385         }
386
387         /* We're now looking at a regular file that doesn't yet exist
388          * in the database, so add it. */
389         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
390
391         state->processed_files++;
392
393         if (state->verbose) {
394             if (state->output_is_a_tty)
395                 printf("\r\033[K");
396
397             printf ("%i/%i: %s",
398                     state->processed_files,
399                     state->total_files,
400                     next);
401
402             putchar((state->output_is_a_tty) ? '\r' : '\n');
403             fflush (stdout);
404         }
405
406         status = notmuch_database_add_message (notmuch, next, &message);
407         switch (status) {
408         /* success */
409         case NOTMUCH_STATUS_SUCCESS:
410             state->added_messages++;
411             for (tag=state->new_tags; *tag != NULL; tag++)
412                 notmuch_message_add_tag (message, *tag);
413             notmuch_message_maildir_to_tags (message, next);
414             break;
415         /* Non-fatal issues (go on to next file) */
416         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
417             notmuch_message_maildir_to_tags (message, next);
418             break;
419         case NOTMUCH_STATUS_FILE_NOT_EMAIL:
420             fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
421                      next);
422             break;
423         /* Fatal issues. Don't process anymore. */
424         case NOTMUCH_STATUS_READ_ONLY_DATABASE:
425         case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
426         case NOTMUCH_STATUS_OUT_OF_MEMORY:
427             fprintf (stderr, "Error: %s. Halting processing.\n",
428                      notmuch_status_to_string (status));
429             ret = status;
430             goto DONE;
431         default:
432         case NOTMUCH_STATUS_FILE_ERROR:
433         case NOTMUCH_STATUS_NULL_POINTER:
434         case NOTMUCH_STATUS_TAG_TOO_LONG:
435         case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
436         case NOTMUCH_STATUS_LAST_STATUS:
437             INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
438             goto DONE;
439         }
440
441         if (message) {
442             notmuch_message_destroy (message);
443             message = NULL;
444         }
445
446         if (do_add_files_print_progress) {
447             do_add_files_print_progress = 0;
448             add_files_print_progress (state);
449         }
450
451         talloc_free (next);
452         next = NULL;
453     }
454
455     if (interrupted)
456         goto DONE;
457
458     /* Now that we've walked the whole filesystem list, anything left
459      * over in the database lists has been deleted. */
460     while (notmuch_filenames_valid (db_files))
461     {
462         char *absolute = talloc_asprintf (state->removed_files,
463                                           "%s/%s", path,
464                                           notmuch_filenames_get (db_files));
465
466         _filename_list_add (state->removed_files, absolute);
467
468         notmuch_filenames_move_to_next (db_files);
469     }
470
471     while (notmuch_filenames_valid (db_subdirs))
472     {
473         char *absolute = talloc_asprintf (state->removed_directories,
474                                           "%s/%s", path,
475                                           notmuch_filenames_get (db_subdirs));
476
477         _filename_list_add (state->removed_directories, absolute);
478
479         notmuch_filenames_move_to_next (db_subdirs);
480     }
481
482     if (! interrupted) {
483         status = notmuch_directory_set_mtime (directory, fs_mtime);
484         if (status && ret == NOTMUCH_STATUS_SUCCESS)
485             ret = status;
486     }
487
488   DONE:
489     if (next)
490         talloc_free (next);
491     if (entry)
492         free (entry);
493     if (dir)
494         closedir (dir);
495     if (fs_entries)
496         free (fs_entries);
497     if (db_subdirs)
498         notmuch_filenames_destroy (db_subdirs);
499     if (db_files)
500         notmuch_filenames_destroy (db_files);
501     if (directory)
502         notmuch_directory_destroy (directory);
503
504     return ret;
505 }
506
507 /* This is the top-level entry point for add_files. It does a couple
508  * of error checks, sets up the progress-printing timer and then calls
509  * into the recursive function. */
510 static notmuch_status_t
511 add_files (notmuch_database_t *notmuch,
512            const char *path,
513            add_files_state_t *state)
514 {
515     notmuch_status_t status;
516     struct sigaction action;
517     struct itimerval timerval;
518     notmuch_bool_t timer_is_active = FALSE;
519     struct stat st;
520
521     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
522         /* Setup our handler for SIGALRM */
523         memset (&action, 0, sizeof (struct sigaction));
524         action.sa_handler = handle_sigalrm;
525         sigemptyset (&action.sa_mask);
526         action.sa_flags = SA_RESTART;
527         sigaction (SIGALRM, &action, NULL);
528
529         /* Then start a timer to send SIGALRM once per second. */
530         timerval.it_interval.tv_sec = 1;
531         timerval.it_interval.tv_usec = 0;
532         timerval.it_value.tv_sec = 1;
533         timerval.it_value.tv_usec = 0;
534         setitimer (ITIMER_REAL, &timerval, NULL);
535
536         timer_is_active = TRUE;
537     }
538
539     if (stat (path, &st)) {
540         fprintf (stderr, "Error reading directory %s: %s\n",
541                  path, strerror (errno));
542         return NOTMUCH_STATUS_FILE_ERROR;
543     }
544
545     if (! S_ISDIR (st.st_mode)) {
546         fprintf (stderr, "Error: %s is not a directory.\n", path);
547         return NOTMUCH_STATUS_FILE_ERROR;
548     }
549
550     status = add_files_recursive (notmuch, path, state);
551
552     if (timer_is_active) {
553         /* Now stop the timer. */
554         timerval.it_interval.tv_sec = 0;
555         timerval.it_interval.tv_usec = 0;
556         timerval.it_value.tv_sec = 0;
557         timerval.it_value.tv_usec = 0;
558         setitimer (ITIMER_REAL, &timerval, NULL);
559
560         /* And disable the signal handler. */
561         action.sa_handler = SIG_IGN;
562         sigaction (SIGALRM, &action, NULL);
563     }
564
565     return status;
566 }
567
568 /* XXX: This should be merged with the add_files function since it
569  * shares a lot of logic with it. */
570 /* Recursively count all regular files in path and all sub-directories
571  * of path.  The result is added to *count (which should be
572  * initialized to zero by the top-level caller before calling
573  * count_files). */
574 static void
575 count_files (const char *path, int *count)
576 {
577     struct dirent *entry = NULL;
578     char *next;
579     struct stat st;
580     struct dirent **fs_entries = NULL;
581     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
582     int i = 0;
583
584     if (num_fs_entries == -1) {
585         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
586                  path, strerror (errno));
587         goto DONE;
588     }
589
590     while (!interrupted) {
591         if (i == num_fs_entries)
592             break;
593
594         entry = fs_entries[i++];
595
596         /* Ignore special directories to avoid infinite recursion.
597          * Also ignore the .notmuch directory.
598          */
599         /* XXX: Eventually we'll want more sophistication to let the
600          * user specify files to be ignored. */
601         if (strcmp (entry->d_name, ".") == 0 ||
602             strcmp (entry->d_name, "..") == 0 ||
603             strcmp (entry->d_name, ".notmuch") == 0)
604         {
605             continue;
606         }
607
608         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
609             next = NULL;
610             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
611                      path, entry->d_name);
612             continue;
613         }
614
615         stat (next, &st);
616
617         if (S_ISREG (st.st_mode)) {
618             *count = *count + 1;
619             if (*count % 1000 == 0) {
620                 printf ("Found %d files so far.\r", *count);
621                 fflush (stdout);
622             }
623         } else if (S_ISDIR (st.st_mode)) {
624             count_files (next, count);
625         }
626
627         free (next);
628     }
629
630   DONE:
631     if (entry)
632         free (entry);
633     if (fs_entries)
634         free (fs_entries);
635 }
636
637 static void
638 upgrade_print_progress (void *closure,
639                         double progress)
640 {
641     add_files_state_t *state = closure;
642
643     printf ("Upgrading database: %.2f%% complete", progress * 100.0);
644
645     if (progress > 0) {
646         struct timeval tv_now;
647         double elapsed, time_remaining;
648
649         gettimeofday (&tv_now, NULL);
650
651         elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
652         time_remaining = (elapsed / progress) * (1.0 - progress);
653         printf (" (");
654         notmuch_time_print_formatted_seconds (time_remaining);
655         printf (" remaining)");
656     }
657
658     printf (".      \r");
659
660     fflush (stdout);
661 }
662
663 /* Recursively remove all filenames from the database referring to
664  * 'path' (or to any of its children). */
665 static void
666 _remove_directory (void *ctx,
667                    notmuch_database_t *notmuch,
668                    const char *path,
669                    int *renamed_files,
670                    int *removed_files)
671 {
672     notmuch_directory_t *directory;
673     notmuch_filenames_t *files, *subdirs;
674     notmuch_status_t status;
675     char *absolute;
676
677     directory = notmuch_database_get_directory (notmuch, path);
678
679     for (files = notmuch_directory_get_child_files (directory);
680          notmuch_filenames_valid (files);
681          notmuch_filenames_move_to_next (files))
682     {
683         absolute = talloc_asprintf (ctx, "%s/%s", path,
684                                     notmuch_filenames_get (files));
685         status = notmuch_database_remove_message (notmuch, absolute);
686         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
687             *renamed_files = *renamed_files + 1;
688         else
689             *removed_files = *removed_files + 1;
690         talloc_free (absolute);
691     }
692
693     for (subdirs = notmuch_directory_get_child_directories (directory);
694          notmuch_filenames_valid (subdirs);
695          notmuch_filenames_move_to_next (subdirs))
696     {
697         absolute = talloc_asprintf (ctx, "%s/%s", path,
698                                     notmuch_filenames_get (subdirs));
699         _remove_directory (ctx, notmuch, absolute, renamed_files, removed_files);
700         talloc_free (absolute);
701     }
702
703     notmuch_directory_destroy (directory);
704 }
705
706 int
707 notmuch_new_command (void *ctx, int argc, char *argv[])
708 {
709     notmuch_config_t *config;
710     notmuch_database_t *notmuch;
711     add_files_state_t add_files_state;
712     double elapsed;
713     struct timeval tv_now;
714     int ret = 0;
715     struct stat st;
716     const char *db_path;
717     char *dot_notmuch_path;
718     struct sigaction action;
719     _filename_node_t *f;
720     int renamed_files, removed_files;
721     notmuch_status_t status;
722     int i;
723
724     add_files_state.verbose = 0;
725     add_files_state.output_is_a_tty = isatty (fileno (stdout));
726
727     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
728         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
729             add_files_state.verbose = 1;
730         } else {
731             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
732             return 1;
733         }
734     }
735
736     config = notmuch_config_open (ctx, NULL, NULL);
737     if (config == NULL)
738         return 1;
739
740     add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
741     db_path = notmuch_config_get_database_path (config);
742
743     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
744
745     if (stat (dot_notmuch_path, &st)) {
746         int count;
747
748         count = 0;
749         count_files (db_path, &count);
750         if (interrupted)
751             return 1;
752
753         printf ("Found %d total files (that's not much mail).\n", count);
754         notmuch = notmuch_database_create (db_path);
755         add_files_state.total_files = count;
756     } else {
757         notmuch = notmuch_database_open (db_path,
758                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
759         if (notmuch == NULL)
760             return 1;
761
762         if (notmuch_database_needs_upgrade (notmuch)) {
763             printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
764             gettimeofday (&add_files_state.tv_start, NULL);
765             notmuch_database_upgrade (notmuch, upgrade_print_progress,
766                                       &add_files_state);
767             printf ("Your notmuch database has now been upgraded to database format version %u.\n",
768                     notmuch_database_get_version (notmuch));
769         }
770
771         add_files_state.total_files = 0;
772     }
773
774     if (notmuch == NULL)
775         return 1;
776
777     /* Setup our handler for SIGINT. We do this after having
778      * potentially done a database upgrade we this interrupt handler
779      * won't support. */
780     memset (&action, 0, sizeof (struct sigaction));
781     action.sa_handler = handle_sigint;
782     sigemptyset (&action.sa_mask);
783     action.sa_flags = SA_RESTART;
784     sigaction (SIGINT, &action, NULL);
785
786     talloc_free (dot_notmuch_path);
787     dot_notmuch_path = NULL;
788
789     add_files_state.processed_files = 0;
790     add_files_state.added_messages = 0;
791     gettimeofday (&add_files_state.tv_start, NULL);
792
793     add_files_state.removed_files = _filename_list_create (ctx);
794     add_files_state.removed_directories = _filename_list_create (ctx);
795
796     ret = add_files (notmuch, db_path, &add_files_state);
797
798     removed_files = 0;
799     renamed_files = 0;
800     for (f = add_files_state.removed_files->head; f; f = f->next) {
801         status = notmuch_database_remove_message (notmuch, f->filename);
802         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
803             renamed_files++;
804         else
805             removed_files++;
806     }
807
808     for (f = add_files_state.removed_directories->head; f; f = f->next) {
809         _remove_directory (ctx, notmuch, f->filename,
810                            &renamed_files, &removed_files);
811     }
812
813     talloc_free (add_files_state.removed_files);
814     talloc_free (add_files_state.removed_directories);
815
816     gettimeofday (&tv_now, NULL);
817     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
818                                     tv_now);
819
820     if (add_files_state.processed_files) {
821         printf ("Processed %d %s in ", add_files_state.processed_files,
822                 add_files_state.processed_files == 1 ?
823                 "file" : "total files");
824         notmuch_time_print_formatted_seconds (elapsed);
825         if (elapsed > 1) {
826             printf (" (%d files/sec.).                 \n",
827                     (int) (add_files_state.processed_files / elapsed));
828         } else {
829             printf (".                    \n");
830         }
831     }
832
833     if (add_files_state.added_messages) {
834         printf ("Added %d new %s to the database.",
835                 add_files_state.added_messages,
836                 add_files_state.added_messages == 1 ?
837                 "message" : "messages");
838     } else {
839         printf ("No new mail.");
840     }
841
842     if (removed_files) {
843         printf (" Removed %d %s.",
844                 removed_files,
845                 removed_files == 1 ? "message" : "messages");
846     }
847
848     if (renamed_files) {
849         printf (" Detected %d file %s.",
850                 renamed_files,
851                 renamed_files == 1 ? "rename" : "renames");
852     }
853
854     printf ("\n");
855
856     if (ret) {
857         printf ("\nNote: At least one error was encountered: %s\n",
858                 notmuch_status_to_string (ret));
859     }
860
861     notmuch_database_close (notmuch);
862
863     return ret || interrupted;
864 }