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