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