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