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