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