]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
new: Defer updating directory mtimes until the end.
[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_LAST_STATUS:
492             INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
493             goto DONE;
494         }
495
496         if (message) {
497             notmuch_message_destroy (message);
498             message = NULL;
499         }
500
501         if (do_print_progress) {
502             do_print_progress = 0;
503             generic_print_progress ("Processed", "files", state->tv_start,
504                                     state->processed_files, state->total_files);
505         }
506
507         talloc_free (next);
508         next = NULL;
509     }
510
511     if (interrupted)
512         goto DONE;
513
514     /* Now that we've walked the whole filesystem list, anything left
515      * over in the database lists has been deleted. */
516     while (notmuch_filenames_valid (db_files))
517     {
518         char *absolute = talloc_asprintf (state->removed_files,
519                                           "%s/%s", path,
520                                           notmuch_filenames_get (db_files));
521
522         _filename_list_add (state->removed_files, absolute);
523
524         notmuch_filenames_move_to_next (db_files);
525     }
526
527     while (notmuch_filenames_valid (db_subdirs))
528     {
529         char *absolute = talloc_asprintf (state->removed_directories,
530                                           "%s/%s", path,
531                                           notmuch_filenames_get (db_subdirs));
532
533         _filename_list_add (state->removed_directories, absolute);
534
535         notmuch_filenames_move_to_next (db_subdirs);
536     }
537
538     /* If the directory's mtime is the same as the wall-clock time
539      * when we stat'ed the directory, we skip updating the mtime in
540      * the database because a message could be delivered later in this
541      * same second.  This may lead to unnecessary re-scans, but it
542      * avoids overlooking messages. */
543     if (fs_mtime != stat_time)
544         _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
545
546   DONE:
547     if (next)
548         talloc_free (next);
549     if (entry)
550         free (entry);
551     if (dir)
552         closedir (dir);
553     if (fs_entries)
554         free (fs_entries);
555     if (db_subdirs)
556         notmuch_filenames_destroy (db_subdirs);
557     if (db_files)
558         notmuch_filenames_destroy (db_files);
559     if (directory)
560         notmuch_directory_destroy (directory);
561
562     return ret;
563 }
564
565 static void
566 setup_progress_printing_timer (void)
567 {
568     struct sigaction action;
569     struct itimerval timerval;
570
571     /* Setup our handler for SIGALRM */
572     memset (&action, 0, sizeof (struct sigaction));
573     action.sa_handler = handle_sigalrm;
574     sigemptyset (&action.sa_mask);
575     action.sa_flags = SA_RESTART;
576     sigaction (SIGALRM, &action, NULL);
577
578     /* Then start a timer to send SIGALRM once per second. */
579     timerval.it_interval.tv_sec = 1;
580     timerval.it_interval.tv_usec = 0;
581     timerval.it_value.tv_sec = 1;
582     timerval.it_value.tv_usec = 0;
583     setitimer (ITIMER_REAL, &timerval, NULL);
584 }
585
586 static void
587 stop_progress_printing_timer (void)
588 {
589     struct sigaction action;
590     struct itimerval timerval;
591
592     /* Now stop the timer. */
593     timerval.it_interval.tv_sec = 0;
594     timerval.it_interval.tv_usec = 0;
595     timerval.it_value.tv_sec = 0;
596     timerval.it_value.tv_usec = 0;
597     setitimer (ITIMER_REAL, &timerval, NULL);
598
599     /* And disable the signal handler. */
600     action.sa_handler = SIG_IGN;
601     sigaction (SIGALRM, &action, NULL);
602 }
603
604
605 /* This is the top-level entry point for add_files. It does a couple
606  * of error checks and then calls into the recursive function. */
607 static notmuch_status_t
608 add_files (notmuch_database_t *notmuch,
609            const char *path,
610            add_files_state_t *state)
611 {
612     notmuch_status_t status;
613     struct stat st;
614
615     if (stat (path, &st)) {
616         fprintf (stderr, "Error reading directory %s: %s\n",
617                  path, strerror (errno));
618         return NOTMUCH_STATUS_FILE_ERROR;
619     }
620
621     if (! S_ISDIR (st.st_mode)) {
622         fprintf (stderr, "Error: %s is not a directory.\n", path);
623         return NOTMUCH_STATUS_FILE_ERROR;
624     }
625
626     status = add_files_recursive (notmuch, path, state);
627
628     return status;
629 }
630
631 /* XXX: This should be merged with the add_files function since it
632  * shares a lot of logic with it. */
633 /* Recursively count all regular files in path and all sub-directories
634  * of path.  The result is added to *count (which should be
635  * initialized to zero by the top-level caller before calling
636  * count_files). */
637 static void
638 count_files (const char *path, int *count)
639 {
640     struct dirent *entry = NULL;
641     char *next;
642     struct stat st;
643     struct dirent **fs_entries = NULL;
644     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
645     int i = 0;
646
647     if (num_fs_entries == -1) {
648         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
649                  path, strerror (errno));
650         goto DONE;
651     }
652
653     while (!interrupted) {
654         if (i == num_fs_entries)
655             break;
656
657         entry = fs_entries[i++];
658
659         /* Ignore special directories to avoid infinite recursion.
660          * Also ignore the .notmuch directory.
661          */
662         /* XXX: Eventually we'll want more sophistication to let the
663          * user specify files to be ignored. */
664         if (strcmp (entry->d_name, ".") == 0 ||
665             strcmp (entry->d_name, "..") == 0 ||
666             strcmp (entry->d_name, ".notmuch") == 0)
667         {
668             continue;
669         }
670
671         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
672             next = NULL;
673             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
674                      path, entry->d_name);
675             continue;
676         }
677
678         stat (next, &st);
679
680         if (S_ISREG (st.st_mode)) {
681             *count = *count + 1;
682             if (*count % 1000 == 0) {
683                 printf ("Found %d files so far.\r", *count);
684                 fflush (stdout);
685             }
686         } else if (S_ISDIR (st.st_mode)) {
687             count_files (next, count);
688         }
689
690         free (next);
691     }
692
693   DONE:
694     if (entry)
695         free (entry);
696     if (fs_entries)
697         free (fs_entries);
698 }
699
700 static void
701 upgrade_print_progress (void *closure,
702                         double progress)
703 {
704     add_files_state_t *state = closure;
705
706     printf ("Upgrading database: %.2f%% complete", progress * 100.0);
707
708     if (progress > 0) {
709         struct timeval tv_now;
710         double elapsed, time_remaining;
711
712         gettimeofday (&tv_now, NULL);
713
714         elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
715         time_remaining = (elapsed / progress) * (1.0 - progress);
716         printf (" (");
717         notmuch_time_print_formatted_seconds (time_remaining);
718         printf (" remaining)");
719     }
720
721     printf (".      \r");
722
723     fflush (stdout);
724 }
725
726 /* Recursively remove all filenames from the database referring to
727  * 'path' (or to any of its children). */
728 static void
729 _remove_directory (void *ctx,
730                    notmuch_database_t *notmuch,
731                    const char *path,
732                    int *renamed_files,
733                    int *removed_files)
734 {
735     notmuch_directory_t *directory;
736     notmuch_filenames_t *files, *subdirs;
737     notmuch_status_t status;
738     char *absolute;
739
740     directory = notmuch_database_get_directory (notmuch, path);
741
742     for (files = notmuch_directory_get_child_files (directory);
743          notmuch_filenames_valid (files);
744          notmuch_filenames_move_to_next (files))
745     {
746         absolute = talloc_asprintf (ctx, "%s/%s", path,
747                                     notmuch_filenames_get (files));
748         status = notmuch_database_remove_message (notmuch, absolute);
749         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
750             *renamed_files = *renamed_files + 1;
751         else
752             *removed_files = *removed_files + 1;
753         talloc_free (absolute);
754     }
755
756     for (subdirs = notmuch_directory_get_child_directories (directory);
757          notmuch_filenames_valid (subdirs);
758          notmuch_filenames_move_to_next (subdirs))
759     {
760         absolute = talloc_asprintf (ctx, "%s/%s", path,
761                                     notmuch_filenames_get (subdirs));
762         _remove_directory (ctx, notmuch, absolute, renamed_files, removed_files);
763         talloc_free (absolute);
764     }
765
766     notmuch_directory_destroy (directory);
767 }
768
769 int
770 notmuch_new_command (void *ctx, int argc, char *argv[])
771 {
772     notmuch_config_t *config;
773     notmuch_database_t *notmuch;
774     add_files_state_t add_files_state;
775     double elapsed;
776     struct timeval tv_now, tv_start;
777     int ret = 0;
778     struct stat st;
779     const char *db_path;
780     char *dot_notmuch_path;
781     struct sigaction action;
782     _filename_node_t *f;
783     int renamed_files, removed_files;
784     notmuch_status_t status;
785     int i;
786     notmuch_bool_t timer_is_active = FALSE;
787
788     add_files_state.verbose = 0;
789     add_files_state.output_is_a_tty = isatty (fileno (stdout));
790
791     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
792         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
793             add_files_state.verbose = 1;
794         } else {
795             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
796             return 1;
797         }
798     }
799     config = notmuch_config_open (ctx, NULL, NULL);
800     if (config == NULL)
801         return 1;
802
803     add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
804     add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
805     add_files_state.message_ids_to_sync = _filename_list_create (ctx);
806     db_path = notmuch_config_get_database_path (config);
807
808     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
809
810     if (stat (dot_notmuch_path, &st)) {
811         int count;
812
813         count = 0;
814         count_files (db_path, &count);
815         if (interrupted)
816             return 1;
817
818         printf ("Found %d total files (that's not much mail).\n", count);
819         notmuch = notmuch_database_create (db_path);
820         add_files_state.total_files = count;
821     } else {
822         notmuch = notmuch_database_open (db_path,
823                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
824         if (notmuch == NULL)
825             return 1;
826
827         if (notmuch_database_needs_upgrade (notmuch)) {
828             printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
829             gettimeofday (&add_files_state.tv_start, NULL);
830             notmuch_database_upgrade (notmuch, upgrade_print_progress,
831                                       &add_files_state);
832             printf ("Your notmuch database has now been upgraded to database format version %u.\n",
833                     notmuch_database_get_version (notmuch));
834         }
835
836         add_files_state.total_files = 0;
837     }
838
839     if (notmuch == NULL)
840         return 1;
841
842     /* Setup our handler for SIGINT. We do this after having
843      * potentially done a database upgrade we this interrupt handler
844      * won't support. */
845     memset (&action, 0, sizeof (struct sigaction));
846     action.sa_handler = handle_sigint;
847     sigemptyset (&action.sa_mask);
848     action.sa_flags = SA_RESTART;
849     sigaction (SIGINT, &action, NULL);
850
851     talloc_free (dot_notmuch_path);
852     dot_notmuch_path = NULL;
853
854     add_files_state.processed_files = 0;
855     add_files_state.added_messages = 0;
856     gettimeofday (&add_files_state.tv_start, NULL);
857
858     add_files_state.removed_files = _filename_list_create (ctx);
859     add_files_state.removed_directories = _filename_list_create (ctx);
860     add_files_state.directory_mtimes = _filename_list_create (ctx);
861
862     if (! debugger_is_active () && add_files_state.output_is_a_tty
863         && ! add_files_state.verbose) {
864         setup_progress_printing_timer ();
865         timer_is_active = TRUE;
866     }
867
868     ret = add_files (notmuch, db_path, &add_files_state);
869
870     removed_files = 0;
871     renamed_files = 0;
872     gettimeofday (&tv_start, NULL);
873     for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
874         status = notmuch_database_remove_message (notmuch, f->filename);
875         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
876             renamed_files++;
877         else
878             removed_files++;
879         if (do_print_progress) {
880             do_print_progress = 0;
881             generic_print_progress ("Cleaned up", "messages",
882                 tv_start, removed_files + renamed_files,
883                 add_files_state.removed_files->count);
884         }
885     }
886
887     gettimeofday (&tv_start, NULL);
888     for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
889         _remove_directory (ctx, notmuch, f->filename,
890                            &renamed_files, &removed_files);
891         if (do_print_progress) {
892             do_print_progress = 0;
893             generic_print_progress ("Cleaned up", "directories",
894                 tv_start, i,
895                 add_files_state.removed_directories->count);
896         }
897     }
898
899     for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
900         notmuch_directory_t *directory;
901         directory = notmuch_database_get_directory (notmuch, f->filename);
902         if (directory) {
903             notmuch_directory_set_mtime (directory, f->mtime);
904             notmuch_directory_destroy (directory);
905         }
906     }
907
908     talloc_free (add_files_state.removed_files);
909     talloc_free (add_files_state.removed_directories);
910     talloc_free (add_files_state.directory_mtimes);
911
912     /* Now that removals are done (hence the database is aware of all
913      * renames), we can synchronize maildir_flags to tags for all
914      * messages that had new filenames appear on this run. */
915     gettimeofday (&tv_start, NULL);
916     if (add_files_state.synchronize_flags) {
917         _filename_node_t *node;
918         notmuch_message_t *message;
919         for (node = add_files_state.message_ids_to_sync->head, i = 0;
920              node;
921              node = node->next, i++)
922         {
923             message = notmuch_database_find_message (notmuch, node->filename);
924             notmuch_message_maildir_flags_to_tags (message);
925             notmuch_message_destroy (message);
926             if (do_print_progress) {
927                 do_print_progress = 0;
928                 generic_print_progress (
929                     "Synchronized tags for", "messages",
930                     tv_start, i, add_files_state.message_ids_to_sync->count);
931             }
932         }
933     }
934
935     talloc_free (add_files_state.message_ids_to_sync);
936     add_files_state.message_ids_to_sync = NULL;
937
938     if (timer_is_active)
939         stop_progress_printing_timer ();
940
941     gettimeofday (&tv_now, NULL);
942     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
943                                     tv_now);
944
945     if (add_files_state.processed_files) {
946         printf ("Processed %d %s in ", add_files_state.processed_files,
947                 add_files_state.processed_files == 1 ?
948                 "file" : "total files");
949         notmuch_time_print_formatted_seconds (elapsed);
950         if (elapsed > 1) {
951             printf (" (%d files/sec.).\033[K\n",
952                     (int) (add_files_state.processed_files / elapsed));
953         } else {
954             printf (".\033[K\n");
955         }
956     }
957
958     if (add_files_state.added_messages) {
959         printf ("Added %d new %s to the database.",
960                 add_files_state.added_messages,
961                 add_files_state.added_messages == 1 ?
962                 "message" : "messages");
963     } else {
964         printf ("No new mail.");
965     }
966
967     if (removed_files) {
968         printf (" Removed %d %s.",
969                 removed_files,
970                 removed_files == 1 ? "message" : "messages");
971     }
972
973     if (renamed_files) {
974         printf (" Detected %d file %s.",
975                 renamed_files,
976                 renamed_files == 1 ? "rename" : "renames");
977     }
978
979     printf ("\n");
980
981     if (ret) {
982         printf ("\nNote: At least one error was encountered: %s\n",
983                 notmuch_status_to_string (ret));
984     }
985
986     notmuch_database_close (notmuch);
987
988     return ret || interrupted;
989 }