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