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