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