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