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 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 notmuch_message_maildir_flags_to_tags (message);
409 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
410 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
412 case NOTMUCH_STATUS_FILE_ERROR:
413 /* Someone renamed/removed the file between scandir and now. */
414 state->vanished_files++;
415 fprintf (stderr, "Unexpected error with file %s\n", filename);
416 (void) print_status_database ("add_file", notmuch, status);
418 /* Fatal issues. Don't process anymore. */
419 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
420 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
421 case NOTMUCH_STATUS_OUT_OF_MEMORY:
422 (void) print_status_database ("add_file", notmuch, status);
425 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
429 status = notmuch_database_end_atomic (notmuch);
433 notmuch_message_destroy (message);
438 /* Examine 'path' recursively as follows:
440 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
441 * o Ask the database for its timestamp of 'path' (db_mtime)
443 * o Ask the filesystem for files and directories within 'path'
444 * (via scandir and stored in fs_entries)
446 * o Pass 1: For each directory in fs_entries, recursively call into
447 * this same function.
449 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
450 * the algorithm at this point, (this directory has not been
451 * updated in the filesystem since the last database scan of PASS
454 * o Ask the database for files and directories within 'path'
455 * (db_files and db_subdirs)
457 * o Pass 2: Walk fs_entries simultaneously with db_files and
458 * db_subdirs. Look for one of three interesting cases:
460 * 1. Regular file in fs_entries and not in db_files
461 * This is a new file to add_message into the database.
463 * 2. Filename in db_files not in fs_entries.
464 * This is a file that has been removed from the mail store.
466 * 3. Directory in db_subdirs not in fs_entries
467 * This is a directory that has been removed from the mail store.
469 * Note that the addition of a directory is not interesting here,
470 * since that will have been taken care of in pass 1. Also, we
471 * don't immediately act on file/directory removal since we must
472 * ensure that in the case of a rename that the new filename is
473 * added before the old filename is removed, (so that no
474 * information is lost from the database).
476 * o Tell the database to update its time of 'path' to 'fs_mtime'
477 * if fs_mtime isn't the current wall-clock time.
479 static notmuch_status_t
480 add_files (notmuch_database_t *notmuch,
482 add_files_state_t *state)
484 struct dirent *entry = NULL;
486 time_t fs_mtime, db_mtime;
487 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
488 struct dirent **fs_entries = NULL;
489 int i, num_fs_entries = 0, entry_type;
490 notmuch_directory_t *directory;
491 notmuch_filenames_t *db_files = NULL;
492 notmuch_filenames_t *db_subdirs = NULL;
497 if (stat (path, &st)) {
498 fprintf (stderr, "Error reading directory %s: %s\n",
499 path, strerror (errno));
500 return NOTMUCH_STATUS_FILE_ERROR;
502 stat_time = time (NULL);
504 if (! S_ISDIR (st.st_mode)) {
505 fprintf (stderr, "Error: %s is not a directory.\n", path);
506 return NOTMUCH_STATUS_FILE_ERROR;
509 fs_mtime = st.st_mtime;
511 status = notmuch_database_get_directory (notmuch, path, &directory);
516 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
518 /* If the directory is unchanged from our last scan and has no
519 * sub-directories, then return without scanning it at all. In
520 * some situations, skipping the scan can substantially reduce the
521 * cost of notmuch new, especially since the huge numbers of files
522 * in Maildirs make scans expensive, but all files live in leaf
525 * To check for sub-directories, we borrow a trick from find,
526 * kpathsea, and many other UNIX tools: since a directory's link
527 * count is the number of sub-directories (specifically, their
528 * '..' entries) plus 2 (the link from the parent and the link for
529 * '.'). This check is safe even on weird file systems, since
530 * file systems that can't compute this will return 0 or 1. This
531 * is safe even on *really* weird file systems like HFS+ that
532 * mistakenly return the total number of directory entries, since
533 * that only inflates the count beyond 2.
535 if (directory && (! state->full_scan) && fs_mtime == db_mtime && st.st_nlink == 2) {
536 /* There's one catch: pass 1 below considers symlinks to
537 * directories to be directories, but these don't increase the
538 * file system link count. So, only bail early if the
539 * database agrees that there are no sub-directories. */
540 db_subdirs = notmuch_directory_get_child_directories (directory);
541 if (! notmuch_filenames_valid (db_subdirs))
543 notmuch_filenames_destroy (db_subdirs);
547 /* If the database knows about this directory, then we sort based
548 * on strcmp to match the database sorting. Otherwise, we can do
549 * inode-based sorting for faster filesystem operation. */
550 num_fs_entries = scandir (path, &fs_entries, 0,
552 dirent_sort_strcmp_name : dirent_sort_inode);
554 if (num_fs_entries == -1) {
555 fprintf (stderr, "Error opening directory %s: %s\n",
556 path, strerror (errno));
557 /* We consider this a fatal error because, if a user moved a
558 * message from another directory that we were able to scan
559 * into this directory, skipping this directory will cause
560 * that message to be lost. */
561 ret = NOTMUCH_STATUS_FILE_ERROR;
565 /* Pass 1: Recurse into all sub-directories. */
566 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
568 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
569 entry = fs_entries[i];
571 /* Ignore special directories to avoid infinite recursion. */
572 if (_special_directory (entry->d_name))
575 /* Ignore any files/directories the user has configured to
576 * ignore. We do this before dirent_type both for performance
577 * and because we don't care if dirent_type fails on entries
578 * that are explicitly ignored.
580 if (_entry_in_ignore_list (state, path, entry->d_name)) {
582 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
583 path, entry->d_name);
587 /* We only want to descend into directories (and symlinks to
589 entry_type = dirent_type (path, entry);
590 if (entry_type == -1) {
591 /* Be pessimistic, e.g. so we don't lose lots of mail just
592 * because a user broke a symlink. */
593 fprintf (stderr, "Error reading file %s/%s: %s\n",
594 path, entry->d_name, strerror (errno));
595 return NOTMUCH_STATUS_FILE_ERROR;
596 } else if (entry_type != S_IFDIR) {
600 /* Ignore the .notmuch directory and any "tmp" directory
601 * that appears within a maildir.
603 if ((is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
604 strcmp (entry->d_name, ".notmuch") == 0)
607 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
608 status = add_files (notmuch, next, state);
617 /* If the directory's modification time in the filesystem is the
618 * same as what we recorded in the database the last time we
619 * scanned it, then we can skip the second pass entirely.
621 * We test for strict equality here to avoid a bug that can happen
622 * if the system clock jumps backward, (preventing new mail from
623 * being discovered until the clock catches up and the directory
624 * is modified again).
626 if (directory && (! state->full_scan) && fs_mtime == db_mtime)
629 /* If the database has never seen this directory before, we can
630 * simply leave db_files and db_subdirs NULL. */
632 db_files = notmuch_directory_get_child_files (directory);
633 db_subdirs = notmuch_directory_get_child_directories (directory);
636 /* Pass 2: Scan for new files, removed files, and removed directories. */
637 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
638 entry = fs_entries[i];
640 /* Ignore special directories early. */
641 if (_special_directory (entry->d_name))
644 /* Ignore files & directories user has configured to be ignored */
645 if (_entry_in_ignore_list (state, path, entry->d_name)) {
647 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
648 path, entry->d_name);
652 /* Check if we've walked past any names in db_files or
653 * db_subdirs. If so, these have been deleted. */
654 while (notmuch_filenames_valid (db_files) &&
655 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0) {
656 char *absolute = talloc_asprintf (state->removed_files,
658 notmuch_filenames_get (db_files));
661 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
664 _filename_list_add (state->removed_files, absolute);
666 notmuch_filenames_move_to_next (db_files);
669 while (notmuch_filenames_valid (db_subdirs) &&
670 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0) {
671 const char *filename = notmuch_filenames_get (db_subdirs);
673 if (strcmp (filename, entry->d_name) < 0) {
674 char *absolute = talloc_asprintf (state->removed_directories,
675 "%s/%s", path, filename);
678 "(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
681 _filename_list_add (state->removed_directories, absolute);
684 notmuch_filenames_move_to_next (db_subdirs);
687 /* Only add regular files (and symlinks to regular files). */
688 entry_type = dirent_type (path, entry);
689 if (entry_type == -1) {
690 fprintf (stderr, "Error reading file %s/%s: %s\n",
691 path, entry->d_name, strerror (errno));
692 return NOTMUCH_STATUS_FILE_ERROR;
693 } else if (entry_type != S_IFREG) {
697 /* Don't add a file that we've added before. */
698 if (notmuch_filenames_valid (db_files) &&
699 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0) {
700 notmuch_filenames_move_to_next (db_files);
704 /* We're now looking at a regular file that doesn't yet exist
705 * in the database, so add it. */
706 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
708 state->processed_files++;
710 if (state->verbosity >= VERBOSITY_VERBOSE) {
711 if (state->output_is_a_tty)
714 printf ("%i/%i: %s", state->processed_files, state->total_files,
717 putchar ((state->output_is_a_tty) ? '\r' : '\n');
721 status = add_file (notmuch, next, state);
727 if (do_print_progress) {
728 do_print_progress = 0;
729 generic_print_progress ("Processed", "files", state->tv_start,
730 state->processed_files, state->total_files);
740 /* Now that we've walked the whole filesystem list, anything left
741 * over in the database lists has been deleted. */
742 while (notmuch_filenames_valid (db_files)) {
743 char *absolute = talloc_asprintf (state->removed_files,
745 notmuch_filenames_get (db_files));
747 printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
750 _filename_list_add (state->removed_files, absolute);
752 notmuch_filenames_move_to_next (db_files);
755 while (notmuch_filenames_valid (db_subdirs)) {
756 char *absolute = talloc_asprintf (state->removed_directories,
758 notmuch_filenames_get (db_subdirs));
762 "(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
765 _filename_list_add (state->removed_directories, absolute);
767 notmuch_filenames_move_to_next (db_subdirs);
770 /* If the directory's mtime is the same as the wall-clock time
771 * when we stat'ed the directory, we skip updating the mtime in
772 * the database because a message could be delivered later in this
773 * same second. This may lead to unnecessary re-scans, but it
774 * avoids overlooking messages. */
775 if (fs_mtime != stat_time)
776 _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
782 for (i = 0; i < num_fs_entries; i++)
783 free (fs_entries[i]);
788 notmuch_filenames_destroy (db_subdirs);
790 notmuch_filenames_destroy (db_files);
792 notmuch_directory_destroy (directory);
798 setup_progress_printing_timer (void)
800 struct sigaction action;
801 struct itimerval timerval;
803 /* Set up our handler for SIGALRM */
804 memset (&action, 0, sizeof (struct sigaction));
805 action.sa_handler = handle_sigalrm;
806 sigemptyset (&action.sa_mask);
807 action.sa_flags = SA_RESTART;
808 sigaction (SIGALRM, &action, NULL);
810 /* Then start a timer to send SIGALRM once per second. */
811 timerval.it_interval.tv_sec = 1;
812 timerval.it_interval.tv_usec = 0;
813 timerval.it_value.tv_sec = 1;
814 timerval.it_value.tv_usec = 0;
815 setitimer (ITIMER_REAL, &timerval, NULL);
819 stop_progress_printing_timer (void)
821 struct sigaction action;
822 struct itimerval timerval;
824 /* Now stop the timer. */
825 timerval.it_interval.tv_sec = 0;
826 timerval.it_interval.tv_usec = 0;
827 timerval.it_value.tv_sec = 0;
828 timerval.it_value.tv_usec = 0;
829 setitimer (ITIMER_REAL, &timerval, NULL);
831 /* And disable the signal handler. */
832 action.sa_handler = SIG_IGN;
833 sigaction (SIGALRM, &action, NULL);
837 /* XXX: This should be merged with the add_files function since it
838 * shares a lot of logic with it. */
839 /* Recursively count all regular files in path and all sub-directories
840 * of path. The result is added to *count (which should be
841 * initialized to zero by the top-level caller before calling
844 count_files (const char *path, int *count, add_files_state_t *state)
846 struct dirent *entry = NULL;
848 struct dirent **fs_entries = NULL;
849 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
852 if (num_fs_entries == -1) {
853 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
854 path, strerror (errno));
858 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
859 entry = fs_entries[i];
861 /* Ignore special directories to avoid infinite recursion.
862 * Also ignore the .notmuch directory.
864 if (_special_directory (entry->d_name) ||
865 strcmp (entry->d_name, ".notmuch") == 0)
868 /* Ignore any files/directories the user has configured to be
871 if (_entry_in_ignore_list (state, path, entry->d_name)) {
873 printf ("(D) count_files: explicitly ignoring %s/%s\n",
874 path, entry->d_name);
878 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
880 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
881 path, entry->d_name);
885 entry_type = dirent_type (path, entry);
886 if (entry_type == S_IFREG) {
888 if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
889 printf ("Found %d files so far.\r", *count);
892 } else if (entry_type == S_IFDIR) {
893 count_files (next, count, state);
901 for (i = 0; i < num_fs_entries; i++)
902 free (fs_entries[i]);
909 upgrade_print_progress (void *closure,
912 add_files_state_t *state = closure;
914 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
917 struct timeval tv_now;
918 double elapsed, time_remaining;
920 gettimeofday (&tv_now, NULL);
922 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
923 time_remaining = (elapsed / progress) * (1.0 - progress);
925 notmuch_time_print_formatted_seconds (time_remaining);
926 printf (" remaining)");
934 /* Remove one message filename from the database. */
935 static notmuch_status_t
936 remove_filename (notmuch_database_t *notmuch,
938 add_files_state_t *add_files_state)
940 notmuch_status_t status;
941 notmuch_message_t *message;
943 status = notmuch_database_begin_atomic (notmuch);
946 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
947 if (status || message == NULL)
950 status = notmuch_database_remove_message (notmuch, path);
951 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
952 add_files_state->renamed_messages++;
953 if (add_files_state->synchronize_flags == true)
954 notmuch_message_maildir_flags_to_tags (message);
955 status = NOTMUCH_STATUS_SUCCESS;
956 } else if (status == NOTMUCH_STATUS_SUCCESS) {
957 add_files_state->removed_messages++;
959 notmuch_message_destroy (message);
962 notmuch_database_end_atomic (notmuch);
966 /* Recursively remove all filenames from the database referring to
967 * 'path' (or to any of its children). */
968 static notmuch_status_t
969 _remove_directory (notmuch_database_t *notmuch,
971 add_files_state_t *add_files_state)
973 notmuch_status_t status;
974 notmuch_directory_t *directory;
975 notmuch_filenames_t *files, *subdirs;
978 status = notmuch_database_get_directory (notmuch, path, &directory);
979 if (status || ! directory)
982 for (files = notmuch_directory_get_child_files (directory);
983 notmuch_filenames_valid (files);
984 notmuch_filenames_move_to_next (files)) {
985 absolute = talloc_asprintf (notmuch, "%s/%s", path,
986 notmuch_filenames_get (files));
987 status = remove_filename (notmuch, absolute, add_files_state);
988 talloc_free (absolute);
993 for (subdirs = notmuch_directory_get_child_directories (directory);
994 notmuch_filenames_valid (subdirs);
995 notmuch_filenames_move_to_next (subdirs)) {
996 absolute = talloc_asprintf (notmuch, "%s/%s", path,
997 notmuch_filenames_get (subdirs));
998 status = _remove_directory (notmuch, absolute, add_files_state);
999 talloc_free (absolute);
1004 status = notmuch_directory_delete (directory);
1008 notmuch_directory_destroy (directory);
1013 print_results (const add_files_state_t *state)
1016 struct timeval tv_now;
1018 gettimeofday (&tv_now, NULL);
1019 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
1021 if (state->processed_files) {
1022 printf ("Processed %d %s in ", state->processed_files,
1023 state->processed_files == 1 ? "file" : "total files");
1024 notmuch_time_print_formatted_seconds (elapsed);
1026 printf (" (%d files/sec.)",
1027 (int) (state->processed_files / elapsed));
1028 printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
1031 if (state->added_messages)
1032 printf ("Added %d new %s to the database.", state->added_messages,
1033 state->added_messages == 1 ? "message" : "messages");
1035 printf ("No new mail.");
1037 if (state->removed_messages)
1038 printf (" Removed %d %s.", state->removed_messages,
1039 state->removed_messages == 1 ? "message" : "messages");
1041 if (state->renamed_messages)
1042 printf (" Detected %d file %s.", state->renamed_messages,
1043 state->renamed_messages == 1 ? "rename" : "renames");
1049 _maybe_upgrade (notmuch_database_t *notmuch, add_files_state_t *state)
1051 if (notmuch_database_needs_upgrade (notmuch)) {
1052 time_t now = time (NULL);
1053 struct tm *gm_time = gmtime (&now);
1055 notmuch_status_t status;
1056 const char *backup_dir = notmuch_config_get (notmuch, NOTMUCH_CONFIG_BACKUP_DIR);
1057 const char *backup_name;
1059 err = mkdir (backup_dir, 0755);
1060 if (err && errno != EEXIST) {
1061 fprintf (stderr, "Failed to create %s: %s\n", backup_dir, strerror (errno));
1062 return EXIT_FAILURE;
1065 /* since dump files are written atomically, the amount of
1066 * harm from overwriting one within a second seems
1067 * relatively small. */
1068 backup_name = talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1070 gm_time->tm_year + 1900,
1071 gm_time->tm_mon + 1,
1077 if (state->verbosity >= VERBOSITY_NORMAL) {
1078 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1079 printf ("This process is safe to interrupt.\n");
1080 printf ("Backing up tags to %s...\n", backup_name);
1083 if (notmuch_database_dump (notmuch, backup_name, "",
1084 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, true)) {
1085 fprintf (stderr, "Backup failed. Aborting upgrade.");
1086 return EXIT_FAILURE;
1089 gettimeofday (&state->tv_start, NULL);
1090 status = notmuch_database_upgrade (
1092 state->verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1095 printf ("Upgrade failed: %s\n",
1096 notmuch_status_to_string (status));
1097 notmuch_database_destroy (notmuch);
1098 return EXIT_FAILURE;
1100 if (state->verbosity >= VERBOSITY_NORMAL)
1101 printf ("Your notmuch database has now been upgraded.\n");
1103 return EXIT_SUCCESS;
1107 notmuch_new_command (notmuch_database_t *notmuch, int argc, char *argv[])
1109 add_files_state_t add_files_state = {
1110 .verbosity = VERBOSITY_NORMAL,
1113 .output_is_a_tty = isatty (fileno (stdout)),
1115 struct timeval tv_start;
1117 const char *db_path, *mail_root;
1118 struct sigaction action;
1119 _filename_node_t *f;
1122 bool timer_is_active = false;
1124 bool quiet = false, verbose = false;
1125 notmuch_status_t status;
1127 notmuch_opt_desc_t options[] = {
1128 { .opt_bool = &quiet, .name = "quiet" },
1129 { .opt_bool = &verbose, .name = "verbose" },
1130 { .opt_bool = &add_files_state.debug, .name = "debug" },
1131 { .opt_bool = &add_files_state.full_scan, .name = "full-scan" },
1132 { .opt_bool = &hooks, .name = "hooks" },
1133 { .opt_inherit = notmuch_shared_indexing_options },
1134 { .opt_inherit = notmuch_shared_options },
1138 opt_index = parse_arguments (argc, argv, options, 1);
1140 return EXIT_FAILURE;
1142 notmuch_process_shared_options (argv[0]);
1144 /* quiet trumps verbose */
1146 add_files_state.verbosity = VERBOSITY_QUIET;
1148 add_files_state.verbosity = VERBOSITY_VERBOSE;
1150 add_files_state.new_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_TAGS);
1152 if (print_status_database (
1155 notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
1156 &add_files_state.synchronize_flags)))
1157 return EXIT_FAILURE;
1159 db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
1160 add_files_state.db_path = db_path;
1162 mail_root = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1163 add_files_state.mail_root = mail_root;
1165 if (! _setup_ignore (notmuch, &add_files_state))
1166 return EXIT_FAILURE;
1168 for (notmuch_config_values_start (add_files_state.new_tags);
1169 notmuch_config_values_valid (add_files_state.new_tags);
1170 notmuch_config_values_move_to_next (add_files_state.new_tags)) {
1171 const char *tag, *error_msg;
1173 tag = notmuch_config_values_get (add_files_state.new_tags);
1174 error_msg = illegal_tag (tag, false);
1176 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n", tag, error_msg);
1177 return EXIT_FAILURE;
1182 /* Drop write lock to run hook */
1183 status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_ONLY);
1184 if (print_status_database ("notmuch new", notmuch, status))
1185 return EXIT_FAILURE;
1187 ret = notmuch_run_hook (notmuch, "pre-new");
1189 return EXIT_FAILURE;
1191 /* acquire write lock again */
1192 status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_WRITE);
1193 if (print_status_database ("notmuch new", notmuch, status))
1194 return EXIT_FAILURE;
1197 notmuch_exit_if_unmatched_db_uuid (notmuch);
1199 if (notmuch_database_get_revision (notmuch, NULL) == 0) {
1201 count_files (mail_root, &count, &add_files_state);
1203 return EXIT_FAILURE;
1205 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1206 printf ("Found %d total files (that's not much mail).\n", count);
1208 add_files_state.total_files = count;
1210 if (_maybe_upgrade (notmuch, &add_files_state))
1211 return EXIT_FAILURE;
1213 add_files_state.total_files = 0;
1216 if (notmuch == NULL)
1217 return EXIT_FAILURE;
1219 status = notmuch_process_shared_indexing_options (notmuch);
1220 if (status != NOTMUCH_STATUS_SUCCESS) {
1221 fprintf (stderr, "Error: Failed to process index options. (%s)\n",
1222 notmuch_status_to_string (status));
1223 return EXIT_FAILURE;
1226 /* Set up our handler for SIGINT. We do this after having
1227 * potentially done a database upgrade we this interrupt handler
1229 memset (&action, 0, sizeof (struct sigaction));
1230 action.sa_handler = handle_sigint;
1231 sigemptyset (&action.sa_mask);
1232 action.sa_flags = SA_RESTART;
1233 sigaction (SIGINT, &action, NULL);
1235 gettimeofday (&add_files_state.tv_start, NULL);
1237 add_files_state.removed_files = _filename_list_create (notmuch);
1238 add_files_state.removed_directories = _filename_list_create (notmuch);
1239 add_files_state.directory_mtimes = _filename_list_create (notmuch);
1241 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1242 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1243 setup_progress_printing_timer ();
1244 timer_is_active = true;
1247 ret = add_files (notmuch, mail_root, &add_files_state);
1251 gettimeofday (&tv_start, NULL);
1252 for (f = add_files_state.removed_files->head; f && ! interrupted; f = f->next) {
1253 ret = remove_filename (notmuch, f->filename, &add_files_state);
1256 if (do_print_progress) {
1257 do_print_progress = 0;
1258 generic_print_progress ("Cleaned up", "messages",
1259 tv_start, add_files_state.removed_messages +
1260 add_files_state.renamed_messages,
1261 add_files_state.removed_files->count);
1265 gettimeofday (&tv_start, NULL);
1266 for (f = add_files_state.removed_directories->head, i = 0; f && ! interrupted; f = f->next, i++) {
1267 ret = _remove_directory (notmuch, f->filename, &add_files_state);
1270 if (do_print_progress) {
1271 do_print_progress = 0;
1272 generic_print_progress ("Cleaned up", "directories",
1274 add_files_state.removed_directories->count);
1278 for (f = add_files_state.directory_mtimes->head; f && ! interrupted; f = f->next) {
1279 notmuch_directory_t *directory;
1280 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1281 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1282 notmuch_directory_set_mtime (directory, f->mtime);
1283 notmuch_directory_destroy (directory);
1288 talloc_free (add_files_state.removed_files);
1289 talloc_free (add_files_state.removed_directories);
1290 talloc_free (add_files_state.directory_mtimes);
1292 if (timer_is_active)
1293 stop_progress_printing_timer ();
1295 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1296 print_results (&add_files_state);
1299 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1300 notmuch_status_to_string (ret));
1302 notmuch_database_close (notmuch);
1304 if (hooks && ! ret && ! interrupted)
1305 ret = notmuch_run_hook (notmuch, "post-new");
1307 notmuch_database_destroy (notmuch);
1309 if (ret || interrupted)
1310 return EXIT_FAILURE;
1312 if (add_files_state.vanished_files)
1313 return NOTMUCH_EXIT_TEMPFAIL;
1315 return EXIT_SUCCESS;