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