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