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