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;
49 enum verbosity verbosity;
52 notmuch_config_values_t *new_tags;
53 const char **ignore_verbatim;
54 size_t ignore_verbatim_length;
55 regex_t *ignore_regex;
56 size_t ignore_regex_length;
60 int added_messages, removed_messages, renamed_messages;
62 struct timeval tv_start;
64 _filename_list_t *removed_files;
65 _filename_list_t *removed_directories;
66 _filename_list_t *directory_mtimes;
68 notmuch_bool_t synchronize_flags;
71 static volatile sig_atomic_t do_print_progress = 0;
74 handle_sigalrm (unused (int signal))
76 do_print_progress = 1;
79 static volatile sig_atomic_t interrupted;
82 handle_sigint (unused (int sig))
84 static const char msg[] = "Stopping... \n";
86 /* This write is "opportunistic", so it's okay to ignore the
87 * result. It is not required for correctness, and if it does
88 * fail or produce a short write, we want to get out of the signal
89 * handler as quickly as possible, not retry it. */
90 IGNORE_RESULT (write (2, msg, sizeof (msg) - 1));
94 static _filename_list_t *
95 _filename_list_create (const void *ctx)
97 _filename_list_t *list;
99 list = talloc (ctx, _filename_list_t);
104 list->tail = &list->head;
110 static _filename_node_t *
111 _filename_list_add (_filename_list_t *list,
112 const char *filename)
114 _filename_node_t *node = talloc (list, _filename_node_t);
118 node->filename = talloc_strdup (list, filename);
121 *(list->tail) = node;
122 list->tail = &node->next;
128 generic_print_progress (const char *action, const char *object,
129 struct timeval tv_start, unsigned processed, unsigned total)
131 struct timeval tv_now;
132 double elapsed_overall, rate_overall;
134 gettimeofday (&tv_now, NULL);
136 elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
137 rate_overall = processed / elapsed_overall;
139 printf ("%s %u ", action, processed);
142 printf ("of %u %s", total, object);
143 if (processed > 0 && elapsed_overall > 0.5) {
144 double time_remaining = ((total - processed) / rate_overall);
146 notmuch_time_print_formatted_seconds (time_remaining);
147 printf (" remaining)");
150 printf ("%s", object);
151 if (elapsed_overall > 0.5)
152 printf (" (%d %s/sec.)", (int) rate_overall, object);
154 printf (".\033[K\r");
160 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
162 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
166 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
168 return strcmp ((*a)->d_name, (*b)->d_name);
171 /* Return the type of a directory entry relative to path as a stat(2)
172 * mode. Like stat, this follows symlinks. Returns -1 and sets errno
173 * if the file's type cannot be determined (which includes dangling
177 dirent_type (const char *path, const struct dirent *entry)
181 int err, saved_errno;
184 /* Mapping from d_type to stat mode_t. We omit DT_LNK so that
185 * we'll fall through to stat and get the real file type. */
186 static const mode_t modes[] = {
194 if (entry->d_type < ARRAY_SIZE (modes) && modes[entry->d_type])
195 return modes[entry->d_type];
198 abspath = talloc_asprintf (NULL, "%s/%s", path, entry->d_name);
203 err = stat (abspath, &statbuf);
205 talloc_free (abspath);
210 return statbuf.st_mode & S_IFMT;
213 /* Test if the directory looks like a Maildir directory.
215 * Search through the array of directory entries to see if we can find all
216 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
218 * Return 1 if the directory looks like a Maildir and 0 otherwise.
221 _entries_resemble_maildir (const char *path, struct dirent **entries, int count)
225 for (i = 0; i < count; i++) {
226 if (dirent_type (path, entries[i]) != S_IFDIR)
229 if (strcmp (entries[i]->d_name, "new") == 0 ||
230 strcmp (entries[i]->d_name, "cur") == 0 ||
231 strcmp (entries[i]->d_name, "tmp") == 0) {
242 _special_directory (const char *entry)
244 return strcmp (entry, ".") == 0 || strcmp (entry, "..") == 0;
248 _setup_ignore (notmuch_database_t *notmuch, add_files_state_t *state)
250 notmuch_config_values_t *ignore_list;
251 int nregex = 0, nverbatim = 0;
252 const char **verbatim = NULL;
253 regex_t *regex = NULL;
255 for (ignore_list = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_IGNORE);
256 notmuch_config_values_valid (ignore_list);
257 notmuch_config_values_move_to_next (ignore_list)) {
258 const char *s = notmuch_config_values_get (ignore_list);
259 size_t len = strlen (s);
262 fprintf (stderr, "Error: Empty string in new.ignore list\n");
271 if (len < 3 || s[len - 1] != '/') {
272 fprintf (stderr, "Error: Malformed pattern '%s' in new.ignore\n",
277 r = talloc_strndup (notmuch, s + 1, len - 2);
278 regex = talloc_realloc (notmuch, regex, regex_t, nregex + 1);
279 preg = ®ex[nregex];
281 rerr = regcomp (preg, r, REG_EXTENDED | REG_NOSUB);
283 size_t error_size = regerror (rerr, preg, NULL, 0);
284 char *error = talloc_size (r, error_size);
286 regerror (rerr, preg, error, error_size);
288 fprintf (stderr, "Error: Invalid regex '%s' in new.ignore: %s\n",
296 verbatim = talloc_realloc (notmuch, verbatim, const char *,
298 verbatim[nverbatim++] = s;
302 state->ignore_regex = regex;
303 state->ignore_regex_length = nregex;
304 state->ignore_verbatim = verbatim;
305 state->ignore_verbatim_length = nverbatim;
311 _get_relative_path (const char *mail_root, const char *dirpath, const char *entry)
313 size_t mail_root_len = strlen (mail_root);
316 if (strncmp (dirpath, mail_root, mail_root_len) != 0) {
317 fprintf (stderr, "Warning: '%s' is not a subdirectory of '%s'\n",
322 dirpath += mail_root_len;
323 while (*dirpath == '/')
327 return talloc_asprintf (NULL, "%s/%s", dirpath, entry);
329 return talloc_strdup (NULL, entry);
332 /* Test if the file/directory is to be ignored.
335 _entry_in_ignore_list (add_files_state_t *state, const char *dirpath,
342 for (i = 0; i < state->ignore_verbatim_length; i++) {
343 if (strcmp (entry, state->ignore_verbatim[i]) == 0)
347 if (state->ignore_regex_length == 0)
350 path = _get_relative_path (state->mail_root, dirpath, entry);
354 for (i = 0; i < state->ignore_regex_length; i++) {
355 if (regexec (&state->ignore_regex[i], path, 0, NULL, 0) == 0) {
366 /* Add a single file to the database. */
367 static notmuch_status_t
368 add_file (notmuch_database_t *notmuch, const char *filename,
369 add_files_state_t *state)
371 notmuch_message_t *message = NULL;
373 notmuch_status_t status;
375 status = notmuch_database_begin_atomic (notmuch);
379 status = notmuch_database_index_file (notmuch, filename, indexing_cli_choices.opts, &message);
382 case NOTMUCH_STATUS_SUCCESS:
383 state->added_messages++;
384 notmuch_message_freeze (message);
385 if (state->synchronize_flags)
386 notmuch_message_maildir_flags_to_tags (message);
388 for (notmuch_config_values_start (state->new_tags);
389 notmuch_config_values_valid (state->new_tags);
390 notmuch_config_values_move_to_next (state->new_tags)) {
391 notmuch_bool_t is_set;
393 tag = notmuch_config_values_get (state->new_tags);
394 /* Currently all errors from has_maildir_flag are fatal */
395 if ((status = notmuch_message_has_maildir_flag_st (message, 'S', &is_set)))
397 if (strcmp ("unread", tag) != 0 || ! is_set) {
398 notmuch_message_add_tag (message, tag);
402 notmuch_message_thaw (message);
404 /* Non-fatal issues (go on to next file). */
405 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
406 if (state->synchronize_flags) {
407 status = notmuch_message_maildir_flags_to_tags (message);
408 if (print_status_message ("add_file", message, status))
412 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
413 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
415 case NOTMUCH_STATUS_FILE_ERROR:
416 /* Someone renamed/removed the file between scandir and now. */
417 state->vanished_files++;
418 fprintf (stderr, "Unexpected error with file %s\n", filename);
419 (void) print_status_database ("add_file", notmuch, status);
421 /* Fatal issues. Don't process anymore. */
422 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
423 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
424 case NOTMUCH_STATUS_OUT_OF_MEMORY:
425 (void) print_status_database ("add_file", notmuch, status);
428 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
432 status = notmuch_database_end_atomic (notmuch);
436 notmuch_message_destroy (message);
441 /* Examine 'path' recursively as follows:
443 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
444 * o Ask the database for its timestamp of 'path' (db_mtime)
446 * o Ask the filesystem for files and directories within 'path'
447 * (via scandir and stored in fs_entries)
449 * o Pass 1: For each directory in fs_entries, recursively call into
450 * this same function.
452 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
453 * the algorithm at this point, (this directory has not been
454 * updated in the filesystem since the last database scan of PASS
457 * o Ask the database for files and directories within 'path'
458 * (db_files and db_subdirs)
460 * o Pass 2: Walk fs_entries simultaneously with db_files and
461 * db_subdirs. Look for one of three interesting cases:
463 * 1. Regular file in fs_entries and not in db_files
464 * This is a new file to add_message into the database.
466 * 2. Filename in db_files not in fs_entries.
467 * This is a file that has been removed from the mail store.
469 * 3. Directory in db_subdirs not in fs_entries
470 * This is a directory that has been removed from the mail store.
472 * Note that the addition of a directory is not interesting here,
473 * since that will have been taken care of in pass 1. Also, we
474 * don't immediately act on file/directory removal since we must
475 * ensure that in the case of a rename that the new filename is
476 * added before the old filename is removed, (so that no
477 * information is lost from the database).
479 * o Tell the database to update its time of 'path' to 'fs_mtime'
480 * if fs_mtime isn't the current wall-clock time.
482 static notmuch_status_t
483 add_files (notmuch_database_t *notmuch,
485 add_files_state_t *state)
487 struct dirent *entry = NULL;
489 time_t fs_mtime, db_mtime;
490 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
491 struct dirent **fs_entries = NULL;
492 int i, num_fs_entries = 0, entry_type;
493 notmuch_directory_t *directory;
494 notmuch_filenames_t *db_files = NULL;
495 notmuch_filenames_t *db_subdirs = NULL;
500 if (stat (path, &st)) {
501 fprintf (stderr, "Error reading directory %s: %s\n",
502 path, strerror (errno));
503 return NOTMUCH_STATUS_FILE_ERROR;
505 stat_time = time (NULL);
507 if (! S_ISDIR (st.st_mode)) {
508 fprintf (stderr, "Error: %s is not a directory.\n", path);
509 return NOTMUCH_STATUS_FILE_ERROR;
512 fs_mtime = st.st_mtime;
514 status = notmuch_database_get_directory (notmuch, path, &directory);
519 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
521 /* If the directory is unchanged from our last scan and has no
522 * sub-directories, then return without scanning it at all. In
523 * some situations, skipping the scan can substantially reduce the
524 * cost of notmuch new, especially since the huge numbers of files
525 * in Maildirs make scans expensive, but all files live in leaf
528 * To check for sub-directories, we borrow a trick from find,
529 * kpathsea, and many other UNIX tools: since a directory's link
530 * count is the number of sub-directories (specifically, their
531 * '..' entries) plus 2 (the link from the parent and the link for
532 * '.'). This check is safe even on weird file systems, since
533 * file systems that can't compute this will return 0 or 1. This
534 * is safe even on *really* weird file systems like HFS+ that
535 * mistakenly return the total number of directory entries, since
536 * that only inflates the count beyond 2.
538 if (directory && (! state->full_scan) && fs_mtime == db_mtime && st.st_nlink == 2) {
539 /* There's one catch: pass 1 below considers symlinks to
540 * directories to be directories, but these don't increase the
541 * file system link count. So, only bail early if the
542 * database agrees that there are no sub-directories. */
543 db_subdirs = notmuch_directory_get_child_directories (directory);
544 if (! notmuch_filenames_valid (db_subdirs))
546 notmuch_filenames_destroy (db_subdirs);
550 /* If the database knows about this directory, then we sort based
551 * on strcmp to match the database sorting. Otherwise, we can do
552 * inode-based sorting for faster filesystem operation. */
553 num_fs_entries = scandir (path, &fs_entries, 0,
555 dirent_sort_strcmp_name : dirent_sort_inode);
557 if (num_fs_entries == -1) {
558 fprintf (stderr, "Error opening directory %s: %s\n",
559 path, strerror (errno));
560 /* We consider this a fatal error because, if a user moved a
561 * message from another directory that we were able to scan
562 * into this directory, skipping this directory will cause
563 * that message to be lost. */
564 ret = NOTMUCH_STATUS_FILE_ERROR;
568 /* Pass 1: Recurse into all sub-directories. */
569 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
571 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
572 entry = fs_entries[i];
574 /* Ignore special directories to avoid infinite recursion. */
575 if (_special_directory (entry->d_name))
578 /* Ignore any files/directories the user has configured to
579 * ignore. We do this before dirent_type both for performance
580 * and because we don't care if dirent_type fails on entries
581 * that are explicitly ignored.
583 if (_entry_in_ignore_list (state, path, entry->d_name)) {
585 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
586 path, entry->d_name);
590 /* We only want to descend into directories (and symlinks to
592 entry_type = dirent_type (path, entry);
593 if (entry_type == -1) {
594 /* Be pessimistic, e.g. so we don't lose lots of mail just
595 * because a user broke a symlink. */
596 fprintf (stderr, "Error reading file %s/%s: %s\n",
597 path, entry->d_name, strerror (errno));
598 return NOTMUCH_STATUS_FILE_ERROR;
599 } else if (entry_type != S_IFDIR) {
603 /* Ignore the .notmuch directory and any "tmp" directory
604 * that appears within a maildir.
606 if ((is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
607 strcmp (entry->d_name, ".notmuch") == 0)
610 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
611 status = add_files (notmuch, next, state);
620 /* If the directory's modification time in the filesystem is the
621 * same as what we recorded in the database the last time we
622 * scanned it, then we can skip the second pass entirely.
624 * We test for strict equality here to avoid a bug that can happen
625 * if the system clock jumps backward, (preventing new mail from
626 * being discovered until the clock catches up and the directory
627 * is modified again).
629 if (directory && (! state->full_scan) && fs_mtime == db_mtime)
632 /* If the database has never seen this directory before, we can
633 * simply leave db_files and db_subdirs NULL. */
635 db_files = notmuch_directory_get_child_files (directory);
636 db_subdirs = notmuch_directory_get_child_directories (directory);
639 /* Pass 2: Scan for new files, removed files, and removed directories. */
640 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
641 entry = fs_entries[i];
643 /* Ignore special directories early. */
644 if (_special_directory (entry->d_name))
647 /* Ignore files & directories user has configured to be ignored */
648 if (_entry_in_ignore_list (state, path, entry->d_name)) {
650 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
651 path, entry->d_name);
655 /* Check if we've walked past any names in db_files or
656 * db_subdirs. If so, these have been deleted. */
657 while (notmuch_filenames_valid (db_files) &&
658 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0) {
659 char *absolute = talloc_asprintf (state->removed_files,
661 notmuch_filenames_get (db_files));
664 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
667 _filename_list_add (state->removed_files, absolute);
669 notmuch_filenames_move_to_next (db_files);
672 while (notmuch_filenames_valid (db_subdirs) &&
673 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0) {
674 const char *filename = notmuch_filenames_get (db_subdirs);
676 if (strcmp (filename, entry->d_name) < 0) {
677 char *absolute = talloc_asprintf (state->removed_directories,
678 "%s/%s", path, filename);
681 "(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
684 _filename_list_add (state->removed_directories, absolute);
687 notmuch_filenames_move_to_next (db_subdirs);
690 /* Only add regular files (and symlinks to regular files). */
691 entry_type = dirent_type (path, entry);
692 if (entry_type == -1) {
693 fprintf (stderr, "Error reading file %s/%s: %s\n",
694 path, entry->d_name, strerror (errno));
695 return NOTMUCH_STATUS_FILE_ERROR;
696 } else if (entry_type != S_IFREG) {
700 /* Don't add a file that we've added before. */
701 if (notmuch_filenames_valid (db_files) &&
702 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0) {
703 notmuch_filenames_move_to_next (db_files);
707 /* We're now looking at a regular file that doesn't yet exist
708 * in the database, so add it. */
709 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
711 state->processed_files++;
713 if (state->verbosity >= VERBOSITY_VERBOSE) {
714 if (state->output_is_a_tty)
717 printf ("%i/%i: %s", state->processed_files, state->total_files,
720 putchar ((state->output_is_a_tty) ? '\r' : '\n');
724 status = add_file (notmuch, next, state);
730 if (do_print_progress) {
731 do_print_progress = 0;
732 generic_print_progress ("Processed", "files", state->tv_start,
733 state->processed_files, state->total_files);
743 /* Now that we've walked the whole filesystem list, anything left
744 * over in the database lists has been deleted. */
745 while (notmuch_filenames_valid (db_files)) {
746 char *absolute = talloc_asprintf (state->removed_files,
748 notmuch_filenames_get (db_files));
750 printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
753 _filename_list_add (state->removed_files, absolute);
755 notmuch_filenames_move_to_next (db_files);
758 while (notmuch_filenames_valid (db_subdirs)) {
759 char *absolute = talloc_asprintf (state->removed_directories,
761 notmuch_filenames_get (db_subdirs));
765 "(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
768 _filename_list_add (state->removed_directories, absolute);
770 notmuch_filenames_move_to_next (db_subdirs);
773 /* If the directory's mtime is the same as the wall-clock time
774 * when we stat'ed the directory, we skip updating the mtime in
775 * the database because a message could be delivered later in this
776 * same second. This may lead to unnecessary re-scans, but it
777 * avoids overlooking messages. */
778 if (fs_mtime != stat_time)
779 _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
785 for (i = 0; i < num_fs_entries; i++)
786 free (fs_entries[i]);
791 notmuch_filenames_destroy (db_subdirs);
793 notmuch_filenames_destroy (db_files);
795 notmuch_directory_destroy (directory);
801 setup_progress_printing_timer (void)
803 struct sigaction action;
804 struct itimerval timerval;
806 /* Set up our handler for SIGALRM */
807 memset (&action, 0, sizeof (struct sigaction));
808 action.sa_handler = handle_sigalrm;
809 sigemptyset (&action.sa_mask);
810 action.sa_flags = SA_RESTART;
811 sigaction (SIGALRM, &action, NULL);
813 /* Then start a timer to send SIGALRM once per second. */
814 timerval.it_interval.tv_sec = 1;
815 timerval.it_interval.tv_usec = 0;
816 timerval.it_value.tv_sec = 1;
817 timerval.it_value.tv_usec = 0;
818 setitimer (ITIMER_REAL, &timerval, NULL);
822 stop_progress_printing_timer (void)
824 struct sigaction action;
825 struct itimerval timerval;
827 /* Now stop the timer. */
828 timerval.it_interval.tv_sec = 0;
829 timerval.it_interval.tv_usec = 0;
830 timerval.it_value.tv_sec = 0;
831 timerval.it_value.tv_usec = 0;
832 setitimer (ITIMER_REAL, &timerval, NULL);
834 /* And disable the signal handler. */
835 action.sa_handler = SIG_IGN;
836 sigaction (SIGALRM, &action, NULL);
840 /* XXX: This should be merged with the add_files function since it
841 * shares a lot of logic with it. */
842 /* Recursively count all regular files in path and all sub-directories
843 * of path. The result is added to *count (which should be
844 * initialized to zero by the top-level caller before calling
847 count_files (const char *path, int *count, add_files_state_t *state)
849 struct dirent *entry = NULL;
851 struct dirent **fs_entries = NULL;
852 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
855 if (num_fs_entries == -1) {
856 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
857 path, strerror (errno));
861 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
862 entry = fs_entries[i];
864 /* Ignore special directories to avoid infinite recursion.
865 * Also ignore the .notmuch directory.
867 if (_special_directory (entry->d_name) ||
868 strcmp (entry->d_name, ".notmuch") == 0)
871 /* Ignore any files/directories the user has configured to be
874 if (_entry_in_ignore_list (state, path, entry->d_name)) {
876 printf ("(D) count_files: explicitly ignoring %s/%s\n",
877 path, entry->d_name);
881 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
883 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
884 path, entry->d_name);
888 entry_type = dirent_type (path, entry);
889 if (entry_type == S_IFREG) {
891 if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
892 printf ("Found %d files so far.\r", *count);
895 } else if (entry_type == S_IFDIR) {
896 count_files (next, count, state);
904 for (i = 0; i < num_fs_entries; i++)
905 free (fs_entries[i]);
912 upgrade_print_progress (void *closure,
915 add_files_state_t *state = closure;
917 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
920 struct timeval tv_now;
921 double elapsed, time_remaining;
923 gettimeofday (&tv_now, NULL);
925 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
926 time_remaining = (elapsed / progress) * (1.0 - progress);
928 notmuch_time_print_formatted_seconds (time_remaining);
929 printf (" remaining)");
937 /* Remove one message filename from the database. */
938 static notmuch_status_t
939 remove_filename (notmuch_database_t *notmuch,
941 add_files_state_t *add_files_state)
943 notmuch_status_t status;
944 notmuch_message_t *message;
946 status = notmuch_database_begin_atomic (notmuch);
949 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
950 if (status || message == NULL)
953 status = notmuch_database_remove_message (notmuch, path);
954 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
955 add_files_state->renamed_messages++;
956 if (add_files_state->synchronize_flags == true)
957 notmuch_message_maildir_flags_to_tags (message);
958 status = NOTMUCH_STATUS_SUCCESS;
959 } else if (status == NOTMUCH_STATUS_SUCCESS) {
960 add_files_state->removed_messages++;
962 notmuch_message_destroy (message);
965 notmuch_database_end_atomic (notmuch);
969 /* Recursively remove all filenames from the database referring to
970 * 'path' (or to any of its children). */
971 static notmuch_status_t
972 _remove_directory (notmuch_database_t *notmuch,
974 add_files_state_t *add_files_state)
976 notmuch_status_t status;
977 notmuch_directory_t *directory;
978 notmuch_filenames_t *files, *subdirs;
981 status = notmuch_database_get_directory (notmuch, path, &directory);
982 if (status || ! directory)
985 for (files = notmuch_directory_get_child_files (directory);
986 notmuch_filenames_valid (files);
987 notmuch_filenames_move_to_next (files)) {
988 absolute = talloc_asprintf (notmuch, "%s/%s", path,
989 notmuch_filenames_get (files));
990 status = remove_filename (notmuch, absolute, add_files_state);
991 talloc_free (absolute);
996 for (subdirs = notmuch_directory_get_child_directories (directory);
997 notmuch_filenames_valid (subdirs);
998 notmuch_filenames_move_to_next (subdirs)) {
999 absolute = talloc_asprintf (notmuch, "%s/%s", path,
1000 notmuch_filenames_get (subdirs));
1001 status = _remove_directory (notmuch, absolute, add_files_state);
1002 talloc_free (absolute);
1007 status = notmuch_directory_delete (directory);
1011 notmuch_directory_destroy (directory);
1016 print_results (const add_files_state_t *state)
1019 struct timeval tv_now;
1021 gettimeofday (&tv_now, NULL);
1022 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
1024 if (state->processed_files) {
1025 printf ("Processed %d %s in ", state->processed_files,
1026 state->processed_files == 1 ? "file" : "total files");
1027 notmuch_time_print_formatted_seconds (elapsed);
1029 printf (" (%d files/sec.)",
1030 (int) (state->processed_files / elapsed));
1031 printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
1034 if (state->added_messages)
1035 printf ("Added %d new %s to the database.", state->added_messages,
1036 state->added_messages == 1 ? "message" : "messages");
1038 printf ("No new mail.");
1040 if (state->removed_messages)
1041 printf (" Removed %d %s.", state->removed_messages,
1042 state->removed_messages == 1 ? "message" : "messages");
1044 if (state->renamed_messages)
1045 printf (" Detected %d file %s.", state->renamed_messages,
1046 state->renamed_messages == 1 ? "rename" : "renames");
1052 _maybe_upgrade (notmuch_database_t *notmuch, add_files_state_t *state)
1054 if (notmuch_database_needs_upgrade (notmuch)) {
1055 time_t now = time (NULL);
1056 struct tm *gm_time = gmtime (&now);
1058 notmuch_status_t status;
1059 const char *backup_dir = notmuch_config_get (notmuch, NOTMUCH_CONFIG_BACKUP_DIR);
1060 const char *backup_name;
1062 err = mkdir (backup_dir, 0755);
1063 if (err && errno != EEXIST) {
1064 fprintf (stderr, "Failed to create %s: %s\n", backup_dir, strerror (errno));
1065 return EXIT_FAILURE;
1068 /* since dump files are written atomically, the amount of
1069 * harm from overwriting one within a second seems
1070 * relatively small. */
1071 backup_name = talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1073 gm_time->tm_year + 1900,
1074 gm_time->tm_mon + 1,
1080 if (state->verbosity >= VERBOSITY_NORMAL) {
1081 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1082 printf ("This process is safe to interrupt.\n");
1083 printf ("Backing up tags to %s...\n", backup_name);
1086 if (notmuch_database_dump (notmuch, backup_name, "",
1087 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, true)) {
1088 fprintf (stderr, "Backup failed. Aborting upgrade.");
1089 return EXIT_FAILURE;
1092 gettimeofday (&state->tv_start, NULL);
1093 status = notmuch_database_upgrade (
1095 state->verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1098 printf ("Upgrade failed: %s\n",
1099 notmuch_status_to_string (status));
1100 notmuch_database_destroy (notmuch);
1101 return EXIT_FAILURE;
1103 if (state->verbosity >= VERBOSITY_NORMAL)
1104 printf ("Your notmuch database has now been upgraded.\n");
1106 return EXIT_SUCCESS;
1110 notmuch_new_command (notmuch_database_t *notmuch, int argc, char *argv[])
1112 add_files_state_t add_files_state = {
1113 .verbosity = VERBOSITY_NORMAL,
1116 .output_is_a_tty = isatty (fileno (stdout)),
1118 struct timeval tv_start;
1120 const char *db_path, *mail_root;
1121 struct sigaction action;
1122 _filename_node_t *f;
1125 bool timer_is_active = false;
1127 bool quiet = false, verbose = false;
1128 notmuch_status_t status;
1130 notmuch_opt_desc_t options[] = {
1131 { .opt_bool = &quiet, .name = "quiet" },
1132 { .opt_bool = &verbose, .name = "verbose" },
1133 { .opt_bool = &add_files_state.debug, .name = "debug" },
1134 { .opt_bool = &add_files_state.full_scan, .name = "full-scan" },
1135 { .opt_bool = &hooks, .name = "hooks" },
1136 { .opt_inherit = notmuch_shared_indexing_options },
1137 { .opt_inherit = notmuch_shared_options },
1141 opt_index = parse_arguments (argc, argv, options, 1);
1143 return EXIT_FAILURE;
1145 notmuch_process_shared_options (notmuch, argv[0]);
1147 /* quiet trumps verbose */
1149 add_files_state.verbosity = VERBOSITY_QUIET;
1151 add_files_state.verbosity = VERBOSITY_VERBOSE;
1153 add_files_state.new_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_TAGS);
1155 if (print_status_database (
1158 notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
1159 &add_files_state.synchronize_flags)))
1160 return EXIT_FAILURE;
1162 db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
1163 add_files_state.db_path = db_path;
1165 mail_root = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1166 add_files_state.mail_root = mail_root;
1168 if (! _setup_ignore (notmuch, &add_files_state))
1169 return EXIT_FAILURE;
1171 for (notmuch_config_values_start (add_files_state.new_tags);
1172 notmuch_config_values_valid (add_files_state.new_tags);
1173 notmuch_config_values_move_to_next (add_files_state.new_tags)) {
1174 const char *tag, *error_msg;
1176 tag = notmuch_config_values_get (add_files_state.new_tags);
1177 error_msg = illegal_tag (tag, false);
1179 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n", tag, error_msg);
1180 return EXIT_FAILURE;
1185 /* Drop write lock to run hook */
1186 status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_ONLY);
1187 if (print_status_database ("notmuch new", notmuch, status))
1188 return EXIT_FAILURE;
1190 ret = notmuch_run_hook (notmuch, "pre-new");
1192 return EXIT_FAILURE;
1194 /* acquire write lock again */
1195 status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_WRITE);
1196 if (print_status_database ("notmuch new", notmuch, status))
1197 return EXIT_FAILURE;
1200 if (notmuch_database_get_revision (notmuch, NULL) == 0) {
1202 count_files (mail_root, &count, &add_files_state);
1204 return EXIT_FAILURE;
1206 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1207 printf ("Found %d total files (that's not much mail).\n", count);
1209 add_files_state.total_files = count;
1211 if (_maybe_upgrade (notmuch, &add_files_state))
1212 return EXIT_FAILURE;
1214 add_files_state.total_files = 0;
1217 if (notmuch == NULL)
1218 return EXIT_FAILURE;
1220 status = notmuch_process_shared_indexing_options (notmuch);
1221 if (status != NOTMUCH_STATUS_SUCCESS) {
1222 fprintf (stderr, "Error: Failed to process index options. (%s)\n",
1223 notmuch_status_to_string (status));
1224 return EXIT_FAILURE;
1227 /* Set up our handler for SIGINT. We do this after having
1228 * potentially done a database upgrade we this interrupt handler
1230 memset (&action, 0, sizeof (struct sigaction));
1231 action.sa_handler = handle_sigint;
1232 sigemptyset (&action.sa_mask);
1233 action.sa_flags = SA_RESTART;
1234 sigaction (SIGINT, &action, NULL);
1236 gettimeofday (&add_files_state.tv_start, NULL);
1238 add_files_state.removed_files = _filename_list_create (notmuch);
1239 add_files_state.removed_directories = _filename_list_create (notmuch);
1240 add_files_state.directory_mtimes = _filename_list_create (notmuch);
1242 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1243 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1244 setup_progress_printing_timer ();
1245 timer_is_active = true;
1248 ret = add_files (notmuch, mail_root, &add_files_state);
1252 gettimeofday (&tv_start, NULL);
1253 for (f = add_files_state.removed_files->head; f && ! interrupted; f = f->next) {
1254 ret = remove_filename (notmuch, f->filename, &add_files_state);
1257 if (do_print_progress) {
1258 do_print_progress = 0;
1259 generic_print_progress ("Cleaned up", "messages",
1260 tv_start, add_files_state.removed_messages +
1261 add_files_state.renamed_messages,
1262 add_files_state.removed_files->count);
1266 gettimeofday (&tv_start, NULL);
1267 for (f = add_files_state.removed_directories->head, i = 0; f && ! interrupted; f = f->next, i++) {
1268 ret = _remove_directory (notmuch, f->filename, &add_files_state);
1271 if (do_print_progress) {
1272 do_print_progress = 0;
1273 generic_print_progress ("Cleaned up", "directories",
1275 add_files_state.removed_directories->count);
1279 for (f = add_files_state.directory_mtimes->head; f && ! interrupted; f = f->next) {
1280 notmuch_directory_t *directory;
1281 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1282 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1283 notmuch_directory_set_mtime (directory, f->mtime);
1284 notmuch_directory_destroy (directory);
1289 talloc_free (add_files_state.removed_files);
1290 talloc_free (add_files_state.removed_directories);
1291 talloc_free (add_files_state.directory_mtimes);
1293 if (timer_is_active)
1294 stop_progress_printing_timer ();
1296 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1297 print_results (&add_files_state);
1300 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1301 notmuch_status_to_string (ret));
1303 notmuch_database_close (notmuch);
1305 if (hooks && ! ret && ! interrupted)
1306 ret = notmuch_run_hook (notmuch, "post-new");
1308 notmuch_database_destroy (notmuch);
1310 if (ret || interrupted)
1311 return EXIT_FAILURE;
1313 if (add_files_state.vanished_files)
1314 return NOTMUCH_EXIT_TEMPFAIL;
1316 return EXIT_SUCCESS;