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