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