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