1 /* notmuch - Not much of an email program, (just index and search)
3 * Copyright © 2009 Carl Worth
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.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "notmuch-client.h"
26 typedef struct _filename_node {
29 struct _filename_node *next;
32 typedef struct _filename_list {
34 _filename_node_t *head;
35 _filename_node_t **tail;
46 const char *mail_root;
48 notmuch_indexopts_t *indexopts;
50 enum verbosity verbosity;
53 notmuch_config_values_t *new_tags;
54 const char **ignore_verbatim;
55 size_t ignore_verbatim_length;
56 regex_t *ignore_regex;
57 size_t ignore_regex_length;
61 int added_messages, removed_messages, renamed_messages;
63 struct timeval tv_start;
65 _filename_list_t *removed_files;
66 _filename_list_t *removed_directories;
67 _filename_list_t *directory_mtimes;
69 notmuch_bool_t synchronize_flags;
72 static volatile sig_atomic_t do_print_progress = 0;
75 handle_sigalrm (unused (int signal))
77 do_print_progress = 1;
80 static volatile sig_atomic_t interrupted;
83 handle_sigint (unused (int sig))
85 static const char msg[] = "Stopping... \n";
87 /* This write is "opportunistic", so it's okay to ignore the
88 * result. It is not required for correctness, and if it does
89 * fail or produce a short write, we want to get out of the signal
90 * handler as quickly as possible, not retry it. */
91 IGNORE_RESULT (write (2, msg, sizeof (msg) - 1));
95 static _filename_list_t *
96 _filename_list_create (const void *ctx)
98 _filename_list_t *list;
100 list = talloc (ctx, _filename_list_t);
105 list->tail = &list->head;
111 static _filename_node_t *
112 _filename_list_add (_filename_list_t *list,
113 const char *filename)
115 _filename_node_t *node = talloc (list, _filename_node_t);
119 node->filename = talloc_strdup (list, filename);
122 *(list->tail) = node;
123 list->tail = &node->next;
129 generic_print_progress (const char *action, const char *object,
130 struct timeval tv_start, unsigned processed, unsigned total)
132 struct timeval tv_now;
133 double elapsed_overall, rate_overall;
135 gettimeofday (&tv_now, NULL);
137 elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
138 rate_overall = processed / elapsed_overall;
140 printf ("%s %u ", action, processed);
143 printf ("of %u %s", total, object);
144 if (processed > 0 && elapsed_overall > 0.5) {
145 double time_remaining = ((total - processed) / rate_overall);
147 notmuch_time_print_formatted_seconds (time_remaining);
148 printf (" remaining)");
151 printf ("%s", object);
152 if (elapsed_overall > 0.5)
153 printf (" (%d %s/sec.)", (int) rate_overall, object);
155 printf (".\033[K\r");
161 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
163 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
167 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
169 return strcmp ((*a)->d_name, (*b)->d_name);
172 /* Return the type of a directory entry relative to path as a stat(2)
173 * mode. Like stat, this follows symlinks. Returns -1 and sets errno
174 * if the file's type cannot be determined (which includes dangling
178 dirent_type (const char *path, const struct dirent *entry)
182 int err, saved_errno;
185 /* Mapping from d_type to stat mode_t. We omit DT_LNK so that
186 * we'll fall through to stat and get the real file type. */
187 static const mode_t modes[] = {
195 if (entry->d_type < ARRAY_SIZE (modes) && modes[entry->d_type])
196 return modes[entry->d_type];
199 abspath = talloc_asprintf (NULL, "%s/%s", path, entry->d_name);
204 err = stat (abspath, &statbuf);
206 talloc_free (abspath);
211 return statbuf.st_mode & S_IFMT;
214 /* Test if the directory looks like a Maildir directory.
216 * Search through the array of directory entries to see if we can find all
217 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
219 * Return 1 if the directory looks like a Maildir and 0 otherwise.
222 _entries_resemble_maildir (const char *path, struct dirent **entries, int count)
226 for (i = 0; i < count; i++) {
227 if (dirent_type (path, entries[i]) != S_IFDIR)
230 if (strcmp (entries[i]->d_name, "new") == 0 ||
231 strcmp (entries[i]->d_name, "cur") == 0 ||
232 strcmp (entries[i]->d_name, "tmp") == 0) {
243 _special_directory (const char *entry)
245 return strcmp (entry, ".") == 0 || strcmp (entry, "..") == 0;
249 _setup_ignore (notmuch_database_t *notmuch, add_files_state_t *state)
251 notmuch_config_values_t *ignore_list;
252 int nregex = 0, nverbatim = 0;
253 const char **verbatim = NULL;
254 regex_t *regex = NULL;
256 for (ignore_list = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_IGNORE);
257 notmuch_config_values_valid (ignore_list);
258 notmuch_config_values_move_to_next (ignore_list)) {
259 const char *s = notmuch_config_values_get (ignore_list);
260 size_t len = strlen (s);
263 fprintf (stderr, "Error: Empty string in new.ignore list\n");
272 if (len < 3 || s[len - 1] != '/') {
273 fprintf (stderr, "Error: Malformed pattern '%s' in new.ignore\n",
278 r = talloc_strndup (notmuch, s + 1, len - 2);
279 regex = talloc_realloc (notmuch, regex, regex_t, nregex + 1);
280 preg = ®ex[nregex];
282 rerr = regcomp (preg, r, REG_EXTENDED | REG_NOSUB);
284 size_t error_size = regerror (rerr, preg, NULL, 0);
285 char *error = talloc_size (r, error_size);
287 regerror (rerr, preg, error, error_size);
289 fprintf (stderr, "Error: Invalid regex '%s' in new.ignore: %s\n",
297 verbatim = talloc_realloc (notmuch, verbatim, const char *,
299 verbatim[nverbatim++] = s;
303 state->ignore_regex = regex;
304 state->ignore_regex_length = nregex;
305 state->ignore_verbatim = verbatim;
306 state->ignore_verbatim_length = nverbatim;
312 _get_relative_path (const char *mail_root, const char *dirpath, const char *entry)
314 size_t mail_root_len = strlen (mail_root);
317 if (strncmp (dirpath, mail_root, mail_root_len) != 0) {
318 fprintf (stderr, "Warning: '%s' is not a subdirectory of '%s'\n",
323 dirpath += mail_root_len;
324 while (*dirpath == '/')
328 return talloc_asprintf (NULL, "%s/%s", dirpath, entry);
330 return talloc_strdup (NULL, entry);
333 /* Test if the file/directory is to be ignored.
336 _entry_in_ignore_list (add_files_state_t *state, const char *dirpath,
343 for (i = 0; i < state->ignore_verbatim_length; i++) {
344 if (strcmp (entry, state->ignore_verbatim[i]) == 0)
348 if (state->ignore_regex_length == 0)
351 path = _get_relative_path (state->mail_root, dirpath, entry);
355 for (i = 0; i < state->ignore_regex_length; i++) {
356 if (regexec (&state->ignore_regex[i], path, 0, NULL, 0) == 0) {
367 /* Add a single file to the database. */
368 static notmuch_status_t
369 add_file (notmuch_database_t *notmuch, const char *filename,
370 add_files_state_t *state)
372 notmuch_message_t *message = NULL;
374 notmuch_status_t status;
376 status = notmuch_database_begin_atomic (notmuch);
380 status = notmuch_database_index_file (notmuch, filename, state->indexopts, &message);
383 case NOTMUCH_STATUS_SUCCESS:
384 state->added_messages++;
385 notmuch_message_freeze (message);
386 if (state->synchronize_flags)
387 notmuch_message_maildir_flags_to_tags (message);
389 for (notmuch_config_values_start (state->new_tags);
390 notmuch_config_values_valid (state->new_tags);
391 notmuch_config_values_move_to_next (state->new_tags)) {
392 notmuch_bool_t is_set;
394 tag = notmuch_config_values_get (state->new_tags);
395 /* Currently all errors from has_maildir_flag are fatal */
396 if ((status = notmuch_message_has_maildir_flag_st (message, 'S', &is_set)))
398 if (strcmp ("unread", tag) != 0 || ! is_set) {
399 notmuch_message_add_tag (message, tag);
403 notmuch_message_thaw (message);
405 /* Non-fatal issues (go on to next file). */
406 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
407 if (state->synchronize_flags) {
408 status = notmuch_message_maildir_flags_to_tags (message);
409 if (print_status_message ("add_file", message, status))
413 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
414 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
416 case NOTMUCH_STATUS_FILE_ERROR:
417 /* Someone renamed/removed the file between scandir and now. */
418 state->vanished_files++;
419 fprintf (stderr, "Unexpected error with file %s\n", filename);
420 (void) print_status_database ("add_file", notmuch, status);
422 /* Fatal issues. Don't process anymore. */
423 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
424 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
425 case NOTMUCH_STATUS_OUT_OF_MEMORY:
426 (void) print_status_database ("add_file", notmuch, status);
429 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
433 status = notmuch_database_end_atomic (notmuch);
437 notmuch_message_destroy (message);
442 /* Examine 'path' recursively as follows:
444 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
445 * o Ask the database for its timestamp of 'path' (db_mtime)
447 * o Ask the filesystem for files and directories within 'path'
448 * (via scandir and stored in fs_entries)
450 * o Pass 1: For each directory in fs_entries, recursively call into
451 * this same function.
453 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
454 * the algorithm at this point, (this directory has not been
455 * updated in the filesystem since the last database scan of PASS
458 * o Ask the database for files and directories within 'path'
459 * (db_files and db_subdirs)
461 * o Pass 2: Walk fs_entries simultaneously with db_files and
462 * db_subdirs. Look for one of three interesting cases:
464 * 1. Regular file in fs_entries and not in db_files
465 * This is a new file to add_message into the database.
467 * 2. Filename in db_files not in fs_entries.
468 * This is a file that has been removed from the mail store.
470 * 3. Directory in db_subdirs not in fs_entries
471 * This is a directory that has been removed from the mail store.
473 * Note that the addition of a directory is not interesting here,
474 * since that will have been taken care of in pass 1. Also, we
475 * don't immediately act on file/directory removal since we must
476 * ensure that in the case of a rename that the new filename is
477 * added before the old filename is removed, (so that no
478 * information is lost from the database).
480 * o Tell the database to update its time of 'path' to 'fs_mtime'
481 * if fs_mtime isn't the current wall-clock time.
483 static notmuch_status_t
484 add_files (notmuch_database_t *notmuch,
486 add_files_state_t *state)
488 struct dirent *entry = NULL;
490 time_t fs_mtime, db_mtime;
491 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
492 struct dirent **fs_entries = NULL;
493 int i, num_fs_entries = 0, entry_type;
494 notmuch_directory_t *directory;
495 notmuch_filenames_t *db_files = NULL;
496 notmuch_filenames_t *db_subdirs = NULL;
501 if (stat (path, &st)) {
502 fprintf (stderr, "Error reading directory %s: %s\n",
503 path, strerror (errno));
504 return NOTMUCH_STATUS_FILE_ERROR;
506 stat_time = time (NULL);
508 if (! S_ISDIR (st.st_mode)) {
509 fprintf (stderr, "Error: %s is not a directory.\n", path);
510 return NOTMUCH_STATUS_FILE_ERROR;
513 fs_mtime = st.st_mtime;
515 status = notmuch_database_get_directory (notmuch, path, &directory);
520 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
522 /* If the directory is unchanged from our last scan and has no
523 * sub-directories, then return without scanning it at all. In
524 * some situations, skipping the scan can substantially reduce the
525 * cost of notmuch new, especially since the huge numbers of files
526 * in Maildirs make scans expensive, but all files live in leaf
529 * To check for sub-directories, we borrow a trick from find,
530 * kpathsea, and many other UNIX tools: since a directory's link
531 * count is the number of sub-directories (specifically, their
532 * '..' entries) plus 2 (the link from the parent and the link for
533 * '.'). This check is safe even on weird file systems, since
534 * file systems that can't compute this will return 0 or 1. This
535 * is safe even on *really* weird file systems like HFS+ that
536 * mistakenly return the total number of directory entries, since
537 * that only inflates the count beyond 2.
539 if (directory && (! state->full_scan) && fs_mtime == db_mtime && st.st_nlink == 2) {
540 /* There's one catch: pass 1 below considers symlinks to
541 * directories to be directories, but these don't increase the
542 * file system link count. So, only bail early if the
543 * database agrees that there are no sub-directories. */
544 db_subdirs = notmuch_directory_get_child_directories (directory);
545 if (! notmuch_filenames_valid (db_subdirs))
547 notmuch_filenames_destroy (db_subdirs);
551 /* If the database knows about this directory, then we sort based
552 * on strcmp to match the database sorting. Otherwise, we can do
553 * inode-based sorting for faster filesystem operation. */
554 num_fs_entries = scandir (path, &fs_entries, 0,
556 dirent_sort_strcmp_name : dirent_sort_inode);
558 if (num_fs_entries == -1) {
559 fprintf (stderr, "Error opening directory %s: %s\n",
560 path, strerror (errno));
561 /* We consider this a fatal error because, if a user moved a
562 * message from another directory that we were able to scan
563 * into this directory, skipping this directory will cause
564 * that message to be lost. */
565 ret = NOTMUCH_STATUS_FILE_ERROR;
569 /* Pass 1: Recurse into all sub-directories. */
570 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
572 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
573 entry = fs_entries[i];
575 /* Ignore special directories to avoid infinite recursion. */
576 if (_special_directory (entry->d_name))
579 /* Ignore any files/directories the user has configured to
580 * ignore. We do this before dirent_type both for performance
581 * and because we don't care if dirent_type fails on entries
582 * that are explicitly ignored.
584 if (_entry_in_ignore_list (state, path, entry->d_name)) {
586 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
587 path, entry->d_name);
591 /* We only want to descend into directories (and symlinks to
593 entry_type = dirent_type (path, entry);
594 if (entry_type == -1) {
595 /* Be pessimistic, e.g. so we don't lose lots of mail just
596 * because a user broke a symlink. */
597 fprintf (stderr, "Error reading file %s/%s: %s\n",
598 path, entry->d_name, strerror (errno));
599 return NOTMUCH_STATUS_FILE_ERROR;
600 } else if (entry_type != S_IFDIR) {
604 /* Ignore any top level .notmuch directory and any "tmp" directory
605 * that appears within a maildir.
607 if ((is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
608 (strcmp (entry->d_name, ".notmuch") == 0
609 && (strcmp (path, state->mail_root)) == 0))
612 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
613 status = add_files (notmuch, next, state);
622 /* If the directory's modification time in the filesystem is the
623 * same as what we recorded in the database the last time we
624 * scanned it, then we can skip the second pass entirely.
626 * We test for strict equality here to avoid a bug that can happen
627 * if the system clock jumps backward, (preventing new mail from
628 * being discovered until the clock catches up and the directory
629 * is modified again).
631 if (directory && (! state->full_scan) && fs_mtime == db_mtime)
634 /* If the database has never seen this directory before, we can
635 * simply leave db_files and db_subdirs NULL. */
637 db_files = notmuch_directory_get_child_files (directory);
638 db_subdirs = notmuch_directory_get_child_directories (directory);
641 /* Pass 2: Scan for new files, removed files, and removed directories. */
642 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
643 entry = fs_entries[i];
645 /* Ignore special directories early. */
646 if (_special_directory (entry->d_name))
649 /* Ignore files & directories user has configured to be ignored */
650 if (_entry_in_ignore_list (state, path, entry->d_name)) {
652 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
653 path, entry->d_name);
657 /* Check if we've walked past any names in db_files or
658 * db_subdirs. If so, these have been deleted. */
659 while (notmuch_filenames_valid (db_files) &&
660 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0) {
661 char *absolute = talloc_asprintf (state->removed_files,
663 notmuch_filenames_get (db_files));
666 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
669 _filename_list_add (state->removed_files, absolute);
671 notmuch_filenames_move_to_next (db_files);
674 while (notmuch_filenames_valid (db_subdirs) &&
675 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0) {
676 const char *filename = notmuch_filenames_get (db_subdirs);
678 if (strcmp (filename, entry->d_name) < 0) {
679 char *absolute = talloc_asprintf (state->removed_directories,
680 "%s/%s", path, filename);
683 "(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
686 _filename_list_add (state->removed_directories, absolute);
689 notmuch_filenames_move_to_next (db_subdirs);
692 /* Only add regular files (and symlinks to regular files). */
693 entry_type = dirent_type (path, entry);
694 if (entry_type == -1) {
695 fprintf (stderr, "Error reading file %s/%s: %s\n",
696 path, entry->d_name, strerror (errno));
697 return NOTMUCH_STATUS_FILE_ERROR;
698 } else if (entry_type != S_IFREG) {
702 /* Don't add a file that we've added before. */
703 if (notmuch_filenames_valid (db_files) &&
704 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0) {
705 notmuch_filenames_move_to_next (db_files);
709 /* We're now looking at a regular file that doesn't yet exist
710 * in the database, so add it. */
711 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
713 state->processed_files++;
715 if (state->verbosity >= VERBOSITY_VERBOSE) {
716 if (state->output_is_a_tty)
719 printf ("%i/%i: %s", state->processed_files, state->total_files,
722 putchar ((state->output_is_a_tty) ? '\r' : '\n');
726 status = add_file (notmuch, next, state);
732 if (do_print_progress) {
733 do_print_progress = 0;
734 generic_print_progress ("Processed", "files", state->tv_start,
735 state->processed_files, state->total_files);
745 /* Now that we've walked the whole filesystem list, anything left
746 * over in the database lists has been deleted. */
747 while (notmuch_filenames_valid (db_files)) {
748 char *absolute = talloc_asprintf (state->removed_files,
750 notmuch_filenames_get (db_files));
752 printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
755 _filename_list_add (state->removed_files, absolute);
757 notmuch_filenames_move_to_next (db_files);
760 while (notmuch_filenames_valid (db_subdirs)) {
761 char *absolute = talloc_asprintf (state->removed_directories,
763 notmuch_filenames_get (db_subdirs));
767 "(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
770 _filename_list_add (state->removed_directories, absolute);
772 notmuch_filenames_move_to_next (db_subdirs);
775 /* If the directory's mtime is the same as the wall-clock time
776 * when we stat'ed the directory, we skip updating the mtime in
777 * the database because a message could be delivered later in this
778 * same second. This may lead to unnecessary re-scans, but it
779 * avoids overlooking messages. */
780 if (fs_mtime != stat_time)
781 _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
787 for (i = 0; i < num_fs_entries; i++)
788 free (fs_entries[i]);
793 notmuch_filenames_destroy (db_subdirs);
795 notmuch_filenames_destroy (db_files);
797 notmuch_directory_destroy (directory);
803 setup_progress_printing_timer (void)
805 struct sigaction action;
806 struct itimerval timerval;
808 /* Set up our handler for SIGALRM */
809 memset (&action, 0, sizeof (struct sigaction));
810 action.sa_handler = handle_sigalrm;
811 sigemptyset (&action.sa_mask);
812 action.sa_flags = SA_RESTART;
813 sigaction (SIGALRM, &action, NULL);
815 /* Then start a timer to send SIGALRM once per second. */
816 timerval.it_interval.tv_sec = 1;
817 timerval.it_interval.tv_usec = 0;
818 timerval.it_value.tv_sec = 1;
819 timerval.it_value.tv_usec = 0;
820 setitimer (ITIMER_REAL, &timerval, NULL);
824 stop_progress_printing_timer (void)
826 struct sigaction action;
827 struct itimerval timerval;
829 /* Now stop the timer. */
830 timerval.it_interval.tv_sec = 0;
831 timerval.it_interval.tv_usec = 0;
832 timerval.it_value.tv_sec = 0;
833 timerval.it_value.tv_usec = 0;
834 setitimer (ITIMER_REAL, &timerval, NULL);
836 /* And disable the signal handler. */
837 action.sa_handler = SIG_IGN;
838 sigaction (SIGALRM, &action, NULL);
842 /* XXX: This should be merged with the add_files function since it
843 * shares a lot of logic with it. */
844 /* Recursively count all regular files in path and all sub-directories
845 * of path. The result is added to *count (which should be
846 * initialized to zero by the top-level caller before calling
849 count_files (const char *path, int *count, add_files_state_t *state)
851 struct dirent *entry = NULL;
853 struct dirent **fs_entries = NULL;
854 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
857 if (num_fs_entries == -1) {
858 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
859 path, strerror (errno));
863 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
864 entry = fs_entries[i];
866 /* Ignore special directories to avoid infinite recursion.
867 * Also ignore the .notmuch directory.
869 if (_special_directory (entry->d_name) ||
870 strcmp (entry->d_name, ".notmuch") == 0)
873 /* Ignore any files/directories the user has configured to be
876 if (_entry_in_ignore_list (state, path, entry->d_name)) {
878 printf ("(D) count_files: explicitly ignoring %s/%s\n",
879 path, entry->d_name);
883 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
885 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
886 path, entry->d_name);
890 entry_type = dirent_type (path, entry);
891 if (entry_type == S_IFREG) {
893 if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
894 printf ("Found %d files so far.\r", *count);
897 } else if (entry_type == S_IFDIR) {
898 count_files (next, count, state);
906 for (i = 0; i < num_fs_entries; i++)
907 free (fs_entries[i]);
914 upgrade_print_progress (void *closure,
917 add_files_state_t *state = closure;
919 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
922 struct timeval tv_now;
923 double elapsed, time_remaining;
925 gettimeofday (&tv_now, NULL);
927 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
928 time_remaining = (elapsed / progress) * (1.0 - progress);
930 notmuch_time_print_formatted_seconds (time_remaining);
931 printf (" remaining)");
939 /* Remove one message filename from the database. */
940 static notmuch_status_t
941 remove_filename (notmuch_database_t *notmuch,
943 add_files_state_t *add_files_state)
945 notmuch_status_t status;
946 notmuch_message_t *message;
948 status = notmuch_database_begin_atomic (notmuch);
951 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
952 if (status || message == NULL)
955 status = notmuch_database_remove_message (notmuch, path);
956 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
957 add_files_state->renamed_messages++;
958 if (add_files_state->synchronize_flags == true)
959 notmuch_message_maildir_flags_to_tags (message);
960 status = NOTMUCH_STATUS_SUCCESS;
961 } else if (status == NOTMUCH_STATUS_SUCCESS) {
962 add_files_state->removed_messages++;
964 notmuch_message_destroy (message);
967 notmuch_database_end_atomic (notmuch);
971 /* Recursively remove all filenames from the database referring to
972 * 'path' (or to any of its children). */
973 static notmuch_status_t
974 _remove_directory (notmuch_database_t *notmuch,
976 add_files_state_t *add_files_state)
978 notmuch_status_t status;
979 notmuch_directory_t *directory;
980 notmuch_filenames_t *files, *subdirs;
983 status = notmuch_database_get_directory (notmuch, path, &directory);
984 if (status || ! directory)
987 for (files = notmuch_directory_get_child_files (directory);
988 notmuch_filenames_valid (files);
989 notmuch_filenames_move_to_next (files)) {
990 absolute = talloc_asprintf (notmuch, "%s/%s", path,
991 notmuch_filenames_get (files));
992 status = remove_filename (notmuch, absolute, add_files_state);
993 talloc_free (absolute);
998 for (subdirs = notmuch_directory_get_child_directories (directory);
999 notmuch_filenames_valid (subdirs);
1000 notmuch_filenames_move_to_next (subdirs)) {
1001 absolute = talloc_asprintf (notmuch, "%s/%s", path,
1002 notmuch_filenames_get (subdirs));
1003 status = _remove_directory (notmuch, absolute, add_files_state);
1004 talloc_free (absolute);
1009 status = notmuch_directory_delete (directory);
1013 notmuch_directory_destroy (directory);
1018 print_results (const add_files_state_t *state)
1021 struct timeval tv_now;
1023 gettimeofday (&tv_now, NULL);
1024 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
1026 if (state->processed_files) {
1027 printf ("Processed %d %s in ", state->processed_files,
1028 state->processed_files == 1 ? "file" : "total files");
1029 notmuch_time_print_formatted_seconds (elapsed);
1031 printf (" (%d files/sec.)",
1032 (int) (state->processed_files / elapsed));
1033 printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
1036 if (state->added_messages)
1037 printf ("Added %d new %s to the database.", state->added_messages,
1038 state->added_messages == 1 ? "message" : "messages");
1040 printf ("No new mail.");
1042 if (state->removed_messages)
1043 printf (" Removed %d %s.", state->removed_messages,
1044 state->removed_messages == 1 ? "message" : "messages");
1046 if (state->renamed_messages)
1047 printf (" Detected %d file %s.", state->renamed_messages,
1048 state->renamed_messages == 1 ? "rename" : "renames");
1054 _maybe_upgrade (notmuch_database_t *notmuch, add_files_state_t *state)
1056 if (notmuch_database_needs_upgrade (notmuch)) {
1057 time_t now = time (NULL);
1058 struct tm *gm_time = gmtime (&now);
1060 notmuch_status_t status;
1061 const char *backup_dir = notmuch_config_get (notmuch, NOTMUCH_CONFIG_BACKUP_DIR);
1062 const char *backup_name;
1064 err = mkdir (backup_dir, 0755);
1065 if (err && errno != EEXIST) {
1066 fprintf (stderr, "Failed to create %s: %s\n", backup_dir, strerror (errno));
1067 return EXIT_FAILURE;
1070 /* since dump files are written atomically, the amount of
1071 * harm from overwriting one within a second seems
1072 * relatively small. */
1073 backup_name = talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1075 gm_time->tm_year + 1900,
1076 gm_time->tm_mon + 1,
1082 if (state->verbosity >= VERBOSITY_NORMAL) {
1083 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1084 printf ("This process is safe to interrupt.\n");
1085 printf ("Backing up tags to %s...\n", backup_name);
1088 if (notmuch_database_dump (notmuch, backup_name, "",
1089 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, true)) {
1090 fprintf (stderr, "Backup failed. Aborting upgrade.");
1091 return EXIT_FAILURE;
1094 gettimeofday (&state->tv_start, NULL);
1095 status = notmuch_database_upgrade (
1097 state->verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1100 printf ("Upgrade failed: %s\n",
1101 notmuch_status_to_string (status));
1102 notmuch_database_destroy (notmuch);
1103 return EXIT_FAILURE;
1105 if (state->verbosity >= VERBOSITY_NORMAL)
1106 printf ("Your notmuch database has now been upgraded.\n");
1108 return EXIT_SUCCESS;
1112 notmuch_new_command (notmuch_database_t *notmuch, int argc, char *argv[])
1114 add_files_state_t add_files_state = {
1115 .verbosity = VERBOSITY_NORMAL,
1118 .output_is_a_tty = isatty (fileno (stdout)),
1120 struct timeval tv_start;
1122 const char *db_path, *mail_root;
1123 struct sigaction action;
1124 _filename_node_t *f;
1127 bool timer_is_active = false;
1129 bool quiet = false, verbose = false;
1130 notmuch_status_t status;
1132 notmuch_opt_desc_t options[] = {
1133 { .opt_bool = &quiet, .name = "quiet" },
1134 { .opt_bool = &verbose, .name = "verbose" },
1135 { .opt_bool = &add_files_state.debug, .name = "debug" },
1136 { .opt_bool = &add_files_state.full_scan, .name = "full-scan" },
1137 { .opt_bool = &hooks, .name = "hooks" },
1138 { .opt_inherit = notmuch_shared_indexing_options },
1139 { .opt_inherit = notmuch_shared_options },
1143 opt_index = parse_arguments (argc, argv, options, 1);
1145 return EXIT_FAILURE;
1147 notmuch_process_shared_options (notmuch, argv[0]);
1149 /* quiet trumps verbose */
1151 add_files_state.verbosity = VERBOSITY_QUIET;
1153 add_files_state.verbosity = VERBOSITY_VERBOSE;
1155 add_files_state.indexopts = notmuch_database_get_default_indexopts (notmuch);
1157 add_files_state.new_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_TAGS);
1159 if (print_status_database (
1162 notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
1163 &add_files_state.synchronize_flags)))
1164 return EXIT_FAILURE;
1166 db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
1167 add_files_state.db_path = db_path;
1169 mail_root = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1170 add_files_state.mail_root = mail_root;
1172 if (! _setup_ignore (notmuch, &add_files_state))
1173 return EXIT_FAILURE;
1175 for (notmuch_config_values_start (add_files_state.new_tags);
1176 notmuch_config_values_valid (add_files_state.new_tags);
1177 notmuch_config_values_move_to_next (add_files_state.new_tags)) {
1178 const char *tag, *error_msg;
1180 tag = notmuch_config_values_get (add_files_state.new_tags);
1181 error_msg = illegal_tag (tag, false);
1183 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n", tag, error_msg);
1184 return EXIT_FAILURE;
1189 /* Drop write lock to run hook */
1190 status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_ONLY);
1191 if (print_status_database ("notmuch new", notmuch, status))
1192 return EXIT_FAILURE;
1194 ret = notmuch_run_hook (notmuch, "pre-new");
1196 return EXIT_FAILURE;
1198 /* acquire write lock again */
1199 status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_WRITE);
1200 if (print_status_database ("notmuch new", notmuch, status))
1201 return EXIT_FAILURE;
1204 if (notmuch_database_get_revision (notmuch, NULL) == 0) {
1206 count_files (mail_root, &count, &add_files_state);
1208 return EXIT_FAILURE;
1210 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1211 printf ("Found %d total files (that's not much mail).\n", count);
1213 add_files_state.total_files = count;
1215 if (_maybe_upgrade (notmuch, &add_files_state))
1216 return EXIT_FAILURE;
1218 add_files_state.total_files = 0;
1221 if (notmuch == NULL)
1222 return EXIT_FAILURE;
1224 status = notmuch_process_shared_indexing_options (add_files_state.indexopts);
1225 if (status != NOTMUCH_STATUS_SUCCESS) {
1226 fprintf (stderr, "Error: Failed to process index options. (%s)\n",
1227 notmuch_status_to_string (status));
1228 return EXIT_FAILURE;
1231 /* Set up our handler for SIGINT. We do this after having
1232 * potentially done a database upgrade we this interrupt handler
1234 memset (&action, 0, sizeof (struct sigaction));
1235 action.sa_handler = handle_sigint;
1236 sigemptyset (&action.sa_mask);
1237 action.sa_flags = SA_RESTART;
1238 sigaction (SIGINT, &action, NULL);
1240 gettimeofday (&add_files_state.tv_start, NULL);
1242 add_files_state.removed_files = _filename_list_create (notmuch);
1243 add_files_state.removed_directories = _filename_list_create (notmuch);
1244 add_files_state.directory_mtimes = _filename_list_create (notmuch);
1246 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1247 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1248 setup_progress_printing_timer ();
1249 timer_is_active = true;
1252 ret = add_files (notmuch, mail_root, &add_files_state);
1256 gettimeofday (&tv_start, NULL);
1257 for (f = add_files_state.removed_files->head; f && ! interrupted; f = f->next) {
1258 ret = remove_filename (notmuch, f->filename, &add_files_state);
1261 if (do_print_progress) {
1262 do_print_progress = 0;
1263 generic_print_progress ("Cleaned up", "messages",
1264 tv_start, add_files_state.removed_messages +
1265 add_files_state.renamed_messages,
1266 add_files_state.removed_files->count);
1270 gettimeofday (&tv_start, NULL);
1271 for (f = add_files_state.removed_directories->head, i = 0; f && ! interrupted; f = f->next, i++) {
1272 ret = _remove_directory (notmuch, f->filename, &add_files_state);
1275 if (do_print_progress) {
1276 do_print_progress = 0;
1277 generic_print_progress ("Cleaned up", "directories",
1279 add_files_state.removed_directories->count);
1283 for (f = add_files_state.directory_mtimes->head; f && ! interrupted; f = f->next) {
1284 notmuch_directory_t *directory;
1285 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1286 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1287 notmuch_directory_set_mtime (directory, f->mtime);
1288 notmuch_directory_destroy (directory);
1293 talloc_free (add_files_state.removed_files);
1294 talloc_free (add_files_state.removed_directories);
1295 talloc_free (add_files_state.directory_mtimes);
1297 if (timer_is_active)
1298 stop_progress_printing_timer ();
1300 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1301 print_results (&add_files_state);
1304 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1305 notmuch_status_to_string (ret));
1307 notmuch_database_close (notmuch);
1309 if (hooks && ! ret && ! interrupted)
1310 ret = notmuch_run_hook (notmuch, "post-new");
1312 notmuch_database_destroy (notmuch);
1314 if (ret || interrupted)
1315 return EXIT_FAILURE;
1317 if (add_files_state.vanished_files)
1318 return NOTMUCH_EXIT_TEMPFAIL;
1320 return EXIT_SUCCESS;