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