]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
cli/new: use the same style for fs entry loops
[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 && ! interrupted; i++) {
447         entry = fs_entries[i];
448
449         /* Ignore any files/directories the user has configured to
450          * ignore.  We do this before dirent_type both for performance
451          * and because we don't care if dirent_type fails on entries
452          * that are explicitly ignored.
453          */
454         if (_entry_in_ignore_list (entry->d_name, state)) {
455             if (state->debug)
456                 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
457                         path, entry->d_name);
458             continue;
459         }
460
461         /* We only want to descend into directories (and symlinks to
462          * directories). */
463         entry_type = dirent_type (path, entry);
464         if (entry_type == -1) {
465             /* Be pessimistic, e.g. so we don't lose lots of mail just
466              * because a user broke a symlink. */
467             fprintf (stderr, "Error reading file %s/%s: %s\n",
468                      path, entry->d_name, strerror (errno));
469             return NOTMUCH_STATUS_FILE_ERROR;
470         } else if (entry_type != S_IFDIR) {
471             continue;
472         }
473
474         /* Ignore special directories to avoid infinite recursion.
475          * Also ignore the .notmuch directory and any "tmp" directory
476          * that appears within a maildir.
477          */
478         if (strcmp (entry->d_name, ".") == 0 ||
479             strcmp (entry->d_name, "..") == 0 ||
480             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
481             strcmp (entry->d_name, ".notmuch") == 0)
482             continue;
483
484         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
485         status = add_files (notmuch, next, state);
486         if (status) {
487             ret = status;
488             goto DONE;
489         }
490         talloc_free (next);
491         next = NULL;
492     }
493
494     /* If the directory's modification time in the filesystem is the
495      * same as what we recorded in the database the last time we
496      * scanned it, then we can skip the second pass entirely.
497      *
498      * We test for strict equality here to avoid a bug that can happen
499      * if the system clock jumps backward, (preventing new mail from
500      * being discovered until the clock catches up and the directory
501      * is modified again).
502      */
503     if (directory && fs_mtime == db_mtime)
504         goto DONE;
505
506     /* If the database has never seen this directory before, we can
507      * simply leave db_files and db_subdirs NULL. */
508     if (directory) {
509         db_files = notmuch_directory_get_child_files (directory);
510         db_subdirs = notmuch_directory_get_child_directories (directory);
511     }
512
513     /* Pass 2: Scan for new files, removed files, and removed directories. */
514     for (i = 0; i < num_fs_entries && ! interrupted; i++) {
515         entry = fs_entries[i];
516
517         /* Ignore files & directories user has configured to be ignored */
518         if (_entry_in_ignore_list (entry->d_name, state)) {
519             if (state->debug)
520                 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
521                         path, entry->d_name);
522             continue;
523         }
524
525         /* Check if we've walked past any names in db_files or
526          * db_subdirs. If so, these have been deleted. */
527         while (notmuch_filenames_valid (db_files) &&
528                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
529         {
530             char *absolute = talloc_asprintf (state->removed_files,
531                                               "%s/%s", path,
532                                               notmuch_filenames_get (db_files));
533
534             if (state->debug)
535                 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
536                         absolute);
537
538             _filename_list_add (state->removed_files, absolute);
539
540             notmuch_filenames_move_to_next (db_files);
541         }
542
543         while (notmuch_filenames_valid (db_subdirs) &&
544                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
545         {
546             const char *filename = notmuch_filenames_get (db_subdirs);
547
548             if (strcmp (filename, entry->d_name) < 0)
549             {
550                 char *absolute = talloc_asprintf (state->removed_directories,
551                                                   "%s/%s", path, filename);
552                 if (state->debug)
553                     printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
554                         absolute);
555
556                 _filename_list_add (state->removed_directories, absolute);
557             }
558
559             notmuch_filenames_move_to_next (db_subdirs);
560         }
561
562         /* Only add regular files (and symlinks to regular files). */
563         entry_type = dirent_type (path, entry);
564         if (entry_type == -1) {
565             fprintf (stderr, "Error reading file %s/%s: %s\n",
566                      path, entry->d_name, strerror (errno));
567             return NOTMUCH_STATUS_FILE_ERROR;
568         } else if (entry_type != S_IFREG) {
569             continue;
570         }
571
572         /* Don't add a file that we've added before. */
573         if (notmuch_filenames_valid (db_files) &&
574             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
575         {
576             notmuch_filenames_move_to_next (db_files);
577             continue;
578         }
579
580         /* We're now looking at a regular file that doesn't yet exist
581          * in the database, so add it. */
582         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
583
584         state->processed_files++;
585
586         if (state->verbosity >= VERBOSITY_VERBOSE) {
587             if (state->output_is_a_tty)
588                 printf("\r\033[K");
589
590             printf ("%i/%i: %s", state->processed_files, state->total_files,
591                     next);
592
593             putchar((state->output_is_a_tty) ? '\r' : '\n');
594             fflush (stdout);
595         }
596
597         status = add_file (notmuch, next, state);
598         if (status) {
599             ret = status;
600             goto DONE;
601         }
602
603         if (do_print_progress) {
604             do_print_progress = 0;
605             generic_print_progress ("Processed", "files", state->tv_start,
606                                     state->processed_files, state->total_files);
607         }
608
609         talloc_free (next);
610         next = NULL;
611     }
612
613     if (interrupted)
614         goto DONE;
615
616     /* Now that we've walked the whole filesystem list, anything left
617      * over in the database lists has been deleted. */
618     while (notmuch_filenames_valid (db_files))
619     {
620         char *absolute = talloc_asprintf (state->removed_files,
621                                           "%s/%s", path,
622                                           notmuch_filenames_get (db_files));
623         if (state->debug)
624             printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
625                     absolute);
626
627         _filename_list_add (state->removed_files, absolute);
628
629         notmuch_filenames_move_to_next (db_files);
630     }
631
632     while (notmuch_filenames_valid (db_subdirs))
633     {
634         char *absolute = talloc_asprintf (state->removed_directories,
635                                           "%s/%s", path,
636                                           notmuch_filenames_get (db_subdirs));
637
638         if (state->debug)
639             printf ("(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
640                     absolute);
641
642         _filename_list_add (state->removed_directories, absolute);
643
644         notmuch_filenames_move_to_next (db_subdirs);
645     }
646
647     /* If the directory's mtime is the same as the wall-clock time
648      * when we stat'ed the directory, we skip updating the mtime in
649      * the database because a message could be delivered later in this
650      * same second.  This may lead to unnecessary re-scans, but it
651      * avoids overlooking messages. */
652     if (fs_mtime != stat_time)
653         _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
654
655   DONE:
656     if (next)
657         talloc_free (next);
658     if (fs_entries) {
659         for (i = 0; i < num_fs_entries; i++)
660             free (fs_entries[i]);
661
662         free (fs_entries);
663     }
664     if (db_subdirs)
665         notmuch_filenames_destroy (db_subdirs);
666     if (db_files)
667         notmuch_filenames_destroy (db_files);
668     if (directory)
669         notmuch_directory_destroy (directory);
670
671     return ret;
672 }
673
674 static void
675 setup_progress_printing_timer (void)
676 {
677     struct sigaction action;
678     struct itimerval timerval;
679
680     /* Set up our handler for SIGALRM */
681     memset (&action, 0, sizeof (struct sigaction));
682     action.sa_handler = handle_sigalrm;
683     sigemptyset (&action.sa_mask);
684     action.sa_flags = SA_RESTART;
685     sigaction (SIGALRM, &action, NULL);
686
687     /* Then start a timer to send SIGALRM once per second. */
688     timerval.it_interval.tv_sec = 1;
689     timerval.it_interval.tv_usec = 0;
690     timerval.it_value.tv_sec = 1;
691     timerval.it_value.tv_usec = 0;
692     setitimer (ITIMER_REAL, &timerval, NULL);
693 }
694
695 static void
696 stop_progress_printing_timer (void)
697 {
698     struct sigaction action;
699     struct itimerval timerval;
700
701     /* Now stop the timer. */
702     timerval.it_interval.tv_sec = 0;
703     timerval.it_interval.tv_usec = 0;
704     timerval.it_value.tv_sec = 0;
705     timerval.it_value.tv_usec = 0;
706     setitimer (ITIMER_REAL, &timerval, NULL);
707
708     /* And disable the signal handler. */
709     action.sa_handler = SIG_IGN;
710     sigaction (SIGALRM, &action, NULL);
711 }
712
713
714 /* XXX: This should be merged with the add_files function since it
715  * shares a lot of logic with it. */
716 /* Recursively count all regular files in path and all sub-directories
717  * of path.  The result is added to *count (which should be
718  * initialized to zero by the top-level caller before calling
719  * count_files). */
720 static void
721 count_files (const char *path, int *count, add_files_state_t *state)
722 {
723     struct dirent *entry = NULL;
724     char *next;
725     struct dirent **fs_entries = NULL;
726     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
727     int entry_type, i;
728
729     if (num_fs_entries == -1) {
730         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
731                  path, strerror (errno));
732         goto DONE;
733     }
734
735     for (i = 0; i < num_fs_entries && ! interrupted; i++) {
736         entry = fs_entries[i];
737
738         /* Ignore special directories to avoid infinite recursion.
739          * Also ignore the .notmuch directory.
740          */
741         if (strcmp (entry->d_name, ".") == 0 ||
742             strcmp (entry->d_name, "..") == 0 ||
743             strcmp (entry->d_name, ".notmuch") == 0)
744             continue;
745
746         /* Ignore any files/directories the user has configured to be
747          * ignored
748          */
749         if (_entry_in_ignore_list (entry->d_name, state)) {
750             if (state->debug)
751                 printf ("(D) count_files: explicitly ignoring %s/%s\n",
752                         path, entry->d_name);
753             continue;
754         }
755
756         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
757             next = NULL;
758             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
759                      path, entry->d_name);
760             continue;
761         }
762
763         entry_type = dirent_type (path, entry);
764         if (entry_type == S_IFREG) {
765             *count = *count + 1;
766             if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
767                 printf ("Found %d files so far.\r", *count);
768                 fflush (stdout);
769             }
770         } else if (entry_type == S_IFDIR) {
771             count_files (next, count, state);
772         }
773
774         free (next);
775     }
776
777   DONE:
778     if (fs_entries) {
779         for (i = 0; i < num_fs_entries; i++)
780             free (fs_entries[i]);
781
782         free (fs_entries);
783     }
784 }
785
786 static void
787 upgrade_print_progress (void *closure,
788                         double progress)
789 {
790     add_files_state_t *state = closure;
791
792     printf ("Upgrading database: %.2f%% complete", progress * 100.0);
793
794     if (progress > 0) {
795         struct timeval tv_now;
796         double elapsed, time_remaining;
797
798         gettimeofday (&tv_now, NULL);
799
800         elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
801         time_remaining = (elapsed / progress) * (1.0 - progress);
802         printf (" (");
803         notmuch_time_print_formatted_seconds (time_remaining);
804         printf (" remaining)");
805     }
806
807     printf (".      \r");
808
809     fflush (stdout);
810 }
811
812 /* Remove one message filename from the database. */
813 static notmuch_status_t
814 remove_filename (notmuch_database_t *notmuch,
815                  const char *path,
816                  add_files_state_t *add_files_state)
817 {
818     notmuch_status_t status;
819     notmuch_message_t *message;
820     status = notmuch_database_begin_atomic (notmuch);
821     if (status)
822         return status;
823     status = notmuch_database_find_message_by_filename (notmuch, path, &message);
824     if (status || message == NULL)
825         goto DONE;
826
827     status = notmuch_database_remove_message (notmuch, path);
828     if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
829         add_files_state->renamed_messages++;
830         if (add_files_state->synchronize_flags == TRUE)
831             notmuch_message_maildir_flags_to_tags (message);
832         status = NOTMUCH_STATUS_SUCCESS;
833     } else if (status == NOTMUCH_STATUS_SUCCESS) {
834         add_files_state->removed_messages++;
835     }
836     notmuch_message_destroy (message);
837
838   DONE:
839     notmuch_database_end_atomic (notmuch);
840     return status;
841 }
842
843 /* Recursively remove all filenames from the database referring to
844  * 'path' (or to any of its children). */
845 static notmuch_status_t
846 _remove_directory (void *ctx,
847                    notmuch_database_t *notmuch,
848                    const char *path,
849                    add_files_state_t *add_files_state)
850 {
851     notmuch_status_t status;
852     notmuch_directory_t *directory;
853     notmuch_filenames_t *files, *subdirs;
854     char *absolute;
855
856     status = notmuch_database_get_directory (notmuch, path, &directory);
857     if (status || !directory)
858         return status;
859
860     for (files = notmuch_directory_get_child_files (directory);
861          notmuch_filenames_valid (files);
862          notmuch_filenames_move_to_next (files))
863     {
864         absolute = talloc_asprintf (ctx, "%s/%s", path,
865                                     notmuch_filenames_get (files));
866         status = remove_filename (notmuch, absolute, add_files_state);
867         talloc_free (absolute);
868         if (status)
869             goto DONE;
870     }
871
872     for (subdirs = notmuch_directory_get_child_directories (directory);
873          notmuch_filenames_valid (subdirs);
874          notmuch_filenames_move_to_next (subdirs))
875     {
876         absolute = talloc_asprintf (ctx, "%s/%s", path,
877                                     notmuch_filenames_get (subdirs));
878         status = _remove_directory (ctx, notmuch, absolute, add_files_state);
879         talloc_free (absolute);
880         if (status)
881             goto DONE;
882     }
883
884     status = notmuch_directory_delete (directory);
885
886   DONE:
887     if (status)
888         notmuch_directory_destroy (directory);
889     return status;
890 }
891
892 static void
893 print_results (const add_files_state_t *state)
894 {
895     double elapsed;
896     struct timeval tv_now;
897
898     gettimeofday (&tv_now, NULL);
899     elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
900
901     if (state->processed_files) {
902         printf ("Processed %d %s in ", state->processed_files,
903                 state->processed_files == 1 ? "file" : "total files");
904         notmuch_time_print_formatted_seconds (elapsed);
905         if (elapsed > 1)
906             printf (" (%d files/sec.)",
907                     (int) (state->processed_files / elapsed));
908         printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
909     }
910
911     if (state->added_messages)
912         printf ("Added %d new %s to the database.", state->added_messages,
913                 state->added_messages == 1 ? "message" : "messages");
914     else
915         printf ("No new mail.");
916
917     if (state->removed_messages)
918         printf (" Removed %d %s.", state->removed_messages,
919                 state->removed_messages == 1 ? "message" : "messages");
920
921     if (state->renamed_messages)
922         printf (" Detected %d file %s.", state->renamed_messages,
923                 state->renamed_messages == 1 ? "rename" : "renames");
924
925     printf ("\n");
926 }
927
928 int
929 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
930 {
931     notmuch_database_t *notmuch;
932     add_files_state_t add_files_state = {
933         .verbosity = VERBOSITY_NORMAL,
934         .debug = FALSE,
935         .output_is_a_tty = isatty (fileno (stdout)),
936     };
937     struct timeval tv_start;
938     int ret = 0;
939     struct stat st;
940     const char *db_path;
941     char *dot_notmuch_path;
942     struct sigaction action;
943     _filename_node_t *f;
944     int opt_index;
945     unsigned int i;
946     notmuch_bool_t timer_is_active = FALSE;
947     notmuch_bool_t no_hooks = FALSE;
948     notmuch_bool_t quiet = FALSE, verbose = FALSE;
949     notmuch_status_t status;
950
951     notmuch_opt_desc_t options[] = {
952         { NOTMUCH_OPT_BOOLEAN,  &quiet, "quiet", 'q', 0 },
953         { NOTMUCH_OPT_BOOLEAN,  &verbose, "verbose", 'v', 0 },
954         { NOTMUCH_OPT_BOOLEAN,  &add_files_state.debug, "debug", 'd', 0 },
955         { NOTMUCH_OPT_BOOLEAN,  &no_hooks, "no-hooks", 'n', 0 },
956         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
957         { 0, 0, 0, 0, 0 }
958     };
959
960     opt_index = parse_arguments (argc, argv, options, 1);
961     if (opt_index < 0)
962         return EXIT_FAILURE;
963
964     notmuch_process_shared_options (argv[0]);
965
966     /* quiet trumps verbose */
967     if (quiet)
968         add_files_state.verbosity = VERBOSITY_QUIET;
969     else if (verbose)
970         add_files_state.verbosity = VERBOSITY_VERBOSE;
971
972     add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
973     add_files_state.new_ignore = notmuch_config_get_new_ignore (config, &add_files_state.new_ignore_length);
974     add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
975     db_path = notmuch_config_get_database_path (config);
976
977     for (i = 0; i < add_files_state.new_tags_length; i++) {
978         const char *error_msg;
979
980         error_msg = illegal_tag (add_files_state.new_tags[i], FALSE);
981         if (error_msg) {
982             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
983                      add_files_state.new_tags[i], error_msg);
984             return EXIT_FAILURE;
985         }
986     }
987
988     if (!no_hooks) {
989         ret = notmuch_run_hook (db_path, "pre-new");
990         if (ret)
991             return EXIT_FAILURE;
992     }
993
994     dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
995
996     if (stat (dot_notmuch_path, &st)) {
997         int count;
998
999         count = 0;
1000         count_files (db_path, &count, &add_files_state);
1001         if (interrupted)
1002             return EXIT_FAILURE;
1003
1004         if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1005             printf ("Found %d total files (that's not much mail).\n", count);
1006         if (notmuch_database_create (db_path, &notmuch))
1007             return EXIT_FAILURE;
1008         add_files_state.total_files = count;
1009     } else {
1010         char *status_string = NULL;
1011         if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1012                                            &notmuch, &status_string)) {
1013             if (status_string) {
1014                 fputs (status_string, stderr);
1015                 free (status_string);
1016             }
1017             return EXIT_FAILURE;
1018         }
1019
1020         notmuch_exit_if_unmatched_db_uuid (notmuch);
1021
1022         if (notmuch_database_needs_upgrade (notmuch)) {
1023             time_t now = time (NULL);
1024             struct tm *gm_time = gmtime (&now);
1025
1026             /* since dump files are written atomically, the amount of
1027              * harm from overwriting one within a second seems
1028              * relatively small. */
1029
1030             const char *backup_name =
1031                 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1032                                  dot_notmuch_path,
1033                                  gm_time->tm_year + 1900,
1034                                  gm_time->tm_mon + 1,
1035                                  gm_time->tm_mday,
1036                                  gm_time->tm_hour,
1037                                  gm_time->tm_min,
1038                                  gm_time->tm_sec);
1039
1040             if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1041                 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1042                 printf ("This process is safe to interrupt.\n");
1043                 printf ("Backing up tags to %s...\n", backup_name);
1044             }
1045
1046             if (notmuch_database_dump (notmuch, backup_name, "",
1047                                        DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, TRUE)) {
1048                 fprintf (stderr, "Backup failed. Aborting upgrade.");
1049                 return EXIT_FAILURE;
1050             }
1051
1052             gettimeofday (&add_files_state.tv_start, NULL);
1053             status = notmuch_database_upgrade (
1054                 notmuch,
1055                 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1056                 &add_files_state);
1057             if (status) {
1058                 printf ("Upgrade failed: %s\n",
1059                         notmuch_status_to_string (status));
1060                 notmuch_database_destroy (notmuch);
1061                 return EXIT_FAILURE;
1062             }
1063             if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1064                 printf ("Your notmuch database has now been upgraded.\n");
1065         }
1066
1067         add_files_state.total_files = 0;
1068     }
1069
1070     if (notmuch == NULL)
1071         return EXIT_FAILURE;
1072
1073     /* Set up our handler for SIGINT. We do this after having
1074      * potentially done a database upgrade we this interrupt handler
1075      * won't support. */
1076     memset (&action, 0, sizeof (struct sigaction));
1077     action.sa_handler = handle_sigint;
1078     sigemptyset (&action.sa_mask);
1079     action.sa_flags = SA_RESTART;
1080     sigaction (SIGINT, &action, NULL);
1081
1082     talloc_free (dot_notmuch_path);
1083     dot_notmuch_path = NULL;
1084
1085     gettimeofday (&add_files_state.tv_start, NULL);
1086
1087     add_files_state.removed_files = _filename_list_create (config);
1088     add_files_state.removed_directories = _filename_list_create (config);
1089     add_files_state.directory_mtimes = _filename_list_create (config);
1090
1091     if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1092         add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1093         setup_progress_printing_timer ();
1094         timer_is_active = TRUE;
1095     }
1096
1097     ret = add_files (notmuch, db_path, &add_files_state);
1098     if (ret)
1099         goto DONE;
1100
1101     gettimeofday (&tv_start, NULL);
1102     for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1103         ret = remove_filename (notmuch, f->filename, &add_files_state);
1104         if (ret)
1105             goto DONE;
1106         if (do_print_progress) {
1107             do_print_progress = 0;
1108             generic_print_progress ("Cleaned up", "messages",
1109                 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1110                 add_files_state.removed_files->count);
1111         }
1112     }
1113
1114     gettimeofday (&tv_start, NULL);
1115     for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1116         ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1117         if (ret)
1118             goto DONE;
1119         if (do_print_progress) {
1120             do_print_progress = 0;
1121             generic_print_progress ("Cleaned up", "directories",
1122                 tv_start, i,
1123                 add_files_state.removed_directories->count);
1124         }
1125     }
1126
1127     for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1128         notmuch_directory_t *directory;
1129         status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1130         if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1131             notmuch_directory_set_mtime (directory, f->mtime);
1132             notmuch_directory_destroy (directory);
1133         }
1134     }
1135
1136   DONE:
1137     talloc_free (add_files_state.removed_files);
1138     talloc_free (add_files_state.removed_directories);
1139     talloc_free (add_files_state.directory_mtimes);
1140
1141     if (timer_is_active)
1142         stop_progress_printing_timer ();
1143
1144     if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1145         print_results (&add_files_state);
1146
1147     if (ret)
1148         fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1149                  notmuch_status_to_string (ret));
1150
1151     notmuch_database_destroy (notmuch);
1152
1153     if (!no_hooks && !ret && !interrupted)
1154         ret = notmuch_run_hook (db_path, "post-new");
1155
1156     if (ret || interrupted)
1157         return EXIT_FAILURE;
1158
1159     if (add_files_state.vanished_files)
1160         return NOTMUCH_EXIT_TEMPFAIL;
1161
1162     return EXIT_SUCCESS;
1163 }