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