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