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