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