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