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