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;
48 enum verbosity verbosity;
51 const char **new_tags;
52 size_t new_tags_length;
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 bool 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)
243 _special_directory (const char *entry)
245 return strcmp (entry, ".") == 0 || strcmp (entry, "..") == 0;
249 _setup_ignore (notmuch_config_t *config, add_files_state_t *state)
251 const char **ignore_list, **ignore;
252 int nregex = 0, nverbatim = 0;
253 const char **verbatim = NULL;
254 regex_t *regex = NULL;
256 ignore_list = notmuch_config_get_new_ignore (config, NULL);
260 for (ignore = ignore_list; *ignore; ignore++) {
261 const char *s = *ignore;
262 size_t len = strlen (s);
265 fprintf (stderr, "Error: Empty string in new.ignore list\n");
274 if (len < 3 || s[len - 1] != '/') {
275 fprintf (stderr, "Error: Malformed pattern '%s' in new.ignore\n",
280 r = talloc_strndup (config, s + 1, len - 2);
281 regex = talloc_realloc (config, regex, regex_t, nregex + 1);
282 preg = ®ex[nregex];
284 rerr = regcomp (preg, r, REG_EXTENDED | REG_NOSUB);
286 size_t error_size = regerror (rerr, preg, NULL, 0);
287 char *error = talloc_size (r, error_size);
289 regerror (rerr, preg, error, error_size);
291 fprintf (stderr, "Error: Invalid regex '%s' in new.ignore: %s\n",
299 verbatim = talloc_realloc (config, verbatim, const char *,
301 verbatim[nverbatim++] = s;
305 state->ignore_regex = regex;
306 state->ignore_regex_length = nregex;
307 state->ignore_verbatim = verbatim;
308 state->ignore_verbatim_length = nverbatim;
314 _get_relative_path (const char *db_path, const char *dirpath, const char *entry)
316 size_t db_path_len = strlen (db_path);
319 if (strncmp (dirpath, db_path, db_path_len) != 0) {
320 fprintf (stderr, "Warning: '%s' is not a subdirectory of '%s'\n",
325 dirpath += db_path_len;
326 while (*dirpath == '/')
330 return talloc_asprintf (NULL, "%s/%s", dirpath, entry);
332 return talloc_strdup (NULL, entry);
335 /* Test if the file/directory is to be ignored.
338 _entry_in_ignore_list (add_files_state_t *state, const char *dirpath,
345 for (i = 0; i < state->ignore_verbatim_length; i++) {
346 if (strcmp (entry, state->ignore_verbatim[i]) == 0)
350 if (state->ignore_regex_length == 0)
353 path = _get_relative_path (state->db_path, dirpath, entry);
357 for (i = 0; i < state->ignore_regex_length; i++) {
358 if (regexec (&state->ignore_regex[i], path, 0, NULL, 0) == 0) {
369 /* Add a single file to the database. */
370 static notmuch_status_t
371 add_file (notmuch_database_t *notmuch, const char *filename,
372 add_files_state_t *state)
374 notmuch_message_t *message = NULL;
376 notmuch_status_t status;
378 status = notmuch_database_begin_atomic (notmuch);
382 status = notmuch_database_index_file (notmuch, filename, indexing_cli_choices.opts, &message);
385 case NOTMUCH_STATUS_SUCCESS:
386 state->added_messages++;
387 notmuch_message_freeze (message);
388 if (state->synchronize_flags)
389 notmuch_message_maildir_flags_to_tags (message);
391 for (tag = state->new_tags; *tag != NULL; tag++) {
392 if (strcmp ("unread", *tag) !=0 ||
393 !notmuch_message_has_maildir_flag (message, 'S')) {
394 notmuch_message_add_tag (message, *tag);
398 notmuch_message_thaw (message);
400 /* Non-fatal issues (go on to next file). */
401 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
402 if (state->synchronize_flags)
403 notmuch_message_maildir_flags_to_tags (message);
405 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
406 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
408 case NOTMUCH_STATUS_FILE_ERROR:
409 /* Someone renamed/removed the file between scandir and now. */
410 state->vanished_files++;
411 fprintf (stderr, "Unexpected error with file %s\n", filename);
412 (void) print_status_database ("add_file", notmuch, status);
414 /* Fatal issues. Don't process anymore. */
415 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
416 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
417 case NOTMUCH_STATUS_OUT_OF_MEMORY:
418 (void) print_status_database("add_file", notmuch, status);
421 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
425 status = notmuch_database_end_atomic (notmuch);
429 notmuch_message_destroy (message);
434 /* Examine 'path' recursively as follows:
436 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
437 * o Ask the database for its timestamp of 'path' (db_mtime)
439 * o Ask the filesystem for files and directories within 'path'
440 * (via scandir and stored in fs_entries)
442 * o Pass 1: For each directory in fs_entries, recursively call into
443 * this same function.
445 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
446 * the algorithm at this point, (this directory has not been
447 * updated in the filesystem since the last database scan of PASS
450 * o Ask the database for files and directories within 'path'
451 * (db_files and db_subdirs)
453 * o Pass 2: Walk fs_entries simultaneously with db_files and
454 * db_subdirs. Look for one of three interesting cases:
456 * 1. Regular file in fs_entries and not in db_files
457 * This is a new file to add_message into the database.
459 * 2. Filename in db_files not in fs_entries.
460 * This is a file that has been removed from the mail store.
462 * 3. Directory in db_subdirs not in fs_entries
463 * This is a directory that has been removed from the mail store.
465 * Note that the addition of a directory is not interesting here,
466 * since that will have been taken care of in pass 1. Also, we
467 * don't immediately act on file/directory removal since we must
468 * ensure that in the case of a rename that the new filename is
469 * added before the old filename is removed, (so that no
470 * information is lost from the database).
472 * o Tell the database to update its time of 'path' to 'fs_mtime'
473 * if fs_mtime isn't the current wall-clock time.
475 static notmuch_status_t
476 add_files (notmuch_database_t *notmuch,
478 add_files_state_t *state)
480 struct dirent *entry = NULL;
482 time_t fs_mtime, db_mtime;
483 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
484 struct dirent **fs_entries = NULL;
485 int i, num_fs_entries = 0, entry_type;
486 notmuch_directory_t *directory;
487 notmuch_filenames_t *db_files = NULL;
488 notmuch_filenames_t *db_subdirs = NULL;
493 if (stat (path, &st)) {
494 fprintf (stderr, "Error reading directory %s: %s\n",
495 path, strerror (errno));
496 return NOTMUCH_STATUS_FILE_ERROR;
498 stat_time = time (NULL);
500 if (! S_ISDIR (st.st_mode)) {
501 fprintf (stderr, "Error: %s is not a directory.\n", path);
502 return NOTMUCH_STATUS_FILE_ERROR;
505 fs_mtime = st.st_mtime;
507 status = notmuch_database_get_directory (notmuch, path, &directory);
512 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
514 /* If the directory is unchanged from our last scan and has no
515 * sub-directories, then return without scanning it at all. In
516 * some situations, skipping the scan can substantially reduce the
517 * cost of notmuch new, especially since the huge numbers of files
518 * in Maildirs make scans expensive, but all files live in leaf
521 * To check for sub-directories, we borrow a trick from find,
522 * kpathsea, and many other UNIX tools: since a directory's link
523 * count is the number of sub-directories (specifically, their
524 * '..' entries) plus 2 (the link from the parent and the link for
525 * '.'). This check is safe even on weird file systems, since
526 * file systems that can't compute this will return 0 or 1. This
527 * is safe even on *really* weird file systems like HFS+ that
528 * mistakenly return the total number of directory entries, since
529 * that only inflates the count beyond 2.
531 if (directory && (! state->full_scan) && fs_mtime == db_mtime && st.st_nlink == 2) {
532 /* There's one catch: pass 1 below considers symlinks to
533 * directories to be directories, but these don't increase the
534 * file system link count. So, only bail early if the
535 * database agrees that there are no sub-directories. */
536 db_subdirs = notmuch_directory_get_child_directories (directory);
537 if (!notmuch_filenames_valid (db_subdirs))
539 notmuch_filenames_destroy (db_subdirs);
543 /* If the database knows about this directory, then we sort based
544 * on strcmp to match the database sorting. Otherwise, we can do
545 * inode-based sorting for faster filesystem operation. */
546 num_fs_entries = scandir (path, &fs_entries, 0,
548 dirent_sort_strcmp_name : dirent_sort_inode);
550 if (num_fs_entries == -1) {
551 fprintf (stderr, "Error opening directory %s: %s\n",
552 path, strerror (errno));
553 /* We consider this a fatal error because, if a user moved a
554 * message from another directory that we were able to scan
555 * into this directory, skipping this directory will cause
556 * that message to be lost. */
557 ret = NOTMUCH_STATUS_FILE_ERROR;
561 /* Pass 1: Recurse into all sub-directories. */
562 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
564 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
565 entry = fs_entries[i];
567 /* Ignore special directories to avoid infinite recursion. */
568 if (_special_directory (entry->d_name))
571 /* Ignore any files/directories the user has configured to
572 * ignore. We do this before dirent_type both for performance
573 * and because we don't care if dirent_type fails on entries
574 * that are explicitly ignored.
576 if (_entry_in_ignore_list (state, path, entry->d_name)) {
578 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
579 path, entry->d_name);
583 /* We only want to descend into directories (and symlinks to
585 entry_type = dirent_type (path, entry);
586 if (entry_type == -1) {
587 /* Be pessimistic, e.g. so we don't lose lots of mail just
588 * because a user broke a symlink. */
589 fprintf (stderr, "Error reading file %s/%s: %s\n",
590 path, entry->d_name, strerror (errno));
591 return NOTMUCH_STATUS_FILE_ERROR;
592 } else if (entry_type != S_IFDIR) {
596 /* Ignore the .notmuch directory and any "tmp" directory
597 * that appears within a maildir.
599 if ((is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
600 strcmp (entry->d_name, ".notmuch") == 0)
603 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
604 status = add_files (notmuch, next, state);
613 /* If the directory's modification time in the filesystem is the
614 * same as what we recorded in the database the last time we
615 * scanned it, then we can skip the second pass entirely.
617 * We test for strict equality here to avoid a bug that can happen
618 * if the system clock jumps backward, (preventing new mail from
619 * being discovered until the clock catches up and the directory
620 * is modified again).
622 if (directory && (! state->full_scan) && fs_mtime == db_mtime)
625 /* If the database has never seen this directory before, we can
626 * simply leave db_files and db_subdirs NULL. */
628 db_files = notmuch_directory_get_child_files (directory);
629 db_subdirs = notmuch_directory_get_child_directories (directory);
632 /* Pass 2: Scan for new files, removed files, and removed directories. */
633 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
634 entry = fs_entries[i];
636 /* Ignore special directories early. */
637 if (_special_directory (entry->d_name))
640 /* Ignore files & directories user has configured to be ignored */
641 if (_entry_in_ignore_list (state, path, entry->d_name)) {
643 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
644 path, entry->d_name);
648 /* Check if we've walked past any names in db_files or
649 * db_subdirs. If so, these have been deleted. */
650 while (notmuch_filenames_valid (db_files) &&
651 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
653 char *absolute = talloc_asprintf (state->removed_files,
655 notmuch_filenames_get (db_files));
658 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
661 _filename_list_add (state->removed_files, absolute);
663 notmuch_filenames_move_to_next (db_files);
666 while (notmuch_filenames_valid (db_subdirs) &&
667 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
669 const char *filename = notmuch_filenames_get (db_subdirs);
671 if (strcmp (filename, entry->d_name) < 0)
673 char *absolute = talloc_asprintf (state->removed_directories,
674 "%s/%s", path, filename);
676 printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
679 _filename_list_add (state->removed_directories, absolute);
682 notmuch_filenames_move_to_next (db_subdirs);
685 /* Only add regular files (and symlinks to regular files). */
686 entry_type = dirent_type (path, entry);
687 if (entry_type == -1) {
688 fprintf (stderr, "Error reading file %s/%s: %s\n",
689 path, entry->d_name, strerror (errno));
690 return NOTMUCH_STATUS_FILE_ERROR;
691 } else if (entry_type != S_IFREG) {
695 /* Don't add a file that we've added before. */
696 if (notmuch_filenames_valid (db_files) &&
697 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
699 notmuch_filenames_move_to_next (db_files);
703 /* We're now looking at a regular file that doesn't yet exist
704 * in the database, so add it. */
705 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
707 state->processed_files++;
709 if (state->verbosity >= VERBOSITY_VERBOSE) {
710 if (state->output_is_a_tty)
713 printf ("%i/%i: %s", state->processed_files, state->total_files,
716 putchar((state->output_is_a_tty) ? '\r' : '\n');
720 status = add_file (notmuch, next, state);
726 if (do_print_progress) {
727 do_print_progress = 0;
728 generic_print_progress ("Processed", "files", state->tv_start,
729 state->processed_files, state->total_files);
739 /* Now that we've walked the whole filesystem list, anything left
740 * over in the database lists has been deleted. */
741 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))
757 char *absolute = talloc_asprintf (state->removed_directories,
759 notmuch_filenames_get (db_subdirs));
762 printf ("(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;
942 status = notmuch_database_begin_atomic (notmuch);
945 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
946 if (status || message == NULL)
949 status = notmuch_database_remove_message (notmuch, path);
950 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
951 add_files_state->renamed_messages++;
952 if (add_files_state->synchronize_flags == true)
953 notmuch_message_maildir_flags_to_tags (message);
954 status = NOTMUCH_STATUS_SUCCESS;
955 } else if (status == NOTMUCH_STATUS_SUCCESS) {
956 add_files_state->removed_messages++;
958 notmuch_message_destroy (message);
961 notmuch_database_end_atomic (notmuch);
965 /* Recursively remove all filenames from the database referring to
966 * 'path' (or to any of its children). */
967 static notmuch_status_t
968 _remove_directory (void *ctx,
969 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))
986 absolute = talloc_asprintf (ctx, "%s/%s", path,
987 notmuch_filenames_get (files));
988 status = remove_filename (notmuch, absolute, add_files_state);
989 talloc_free (absolute);
994 for (subdirs = notmuch_directory_get_child_directories (directory);
995 notmuch_filenames_valid (subdirs);
996 notmuch_filenames_move_to_next (subdirs))
998 absolute = talloc_asprintf (ctx, "%s/%s", path,
999 notmuch_filenames_get (subdirs));
1000 status = _remove_directory (ctx, notmuch, absolute, add_files_state);
1001 talloc_free (absolute);
1006 status = notmuch_directory_delete (directory);
1010 notmuch_directory_destroy (directory);
1015 print_results (const add_files_state_t *state)
1018 struct timeval tv_now;
1020 gettimeofday (&tv_now, NULL);
1021 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
1023 if (state->processed_files) {
1024 printf ("Processed %d %s in ", state->processed_files,
1025 state->processed_files == 1 ? "file" : "total files");
1026 notmuch_time_print_formatted_seconds (elapsed);
1028 printf (" (%d files/sec.)",
1029 (int) (state->processed_files / elapsed));
1030 printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
1033 if (state->added_messages)
1034 printf ("Added %d new %s to the database.", state->added_messages,
1035 state->added_messages == 1 ? "message" : "messages");
1037 printf ("No new mail.");
1039 if (state->removed_messages)
1040 printf (" Removed %d %s.", state->removed_messages,
1041 state->removed_messages == 1 ? "message" : "messages");
1043 if (state->renamed_messages)
1044 printf (" Detected %d file %s.", state->renamed_messages,
1045 state->renamed_messages == 1 ? "rename" : "renames");
1051 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
1053 notmuch_database_t *notmuch;
1054 add_files_state_t add_files_state = {
1055 .verbosity = VERBOSITY_NORMAL,
1058 .output_is_a_tty = isatty (fileno (stdout)),
1060 struct timeval tv_start;
1063 const char *db_path;
1064 char *dot_notmuch_path;
1065 struct sigaction action;
1066 _filename_node_t *f;
1069 bool timer_is_active = false;
1071 bool quiet = false, verbose = false;
1072 notmuch_status_t status;
1074 notmuch_opt_desc_t options[] = {
1075 { .opt_bool = &quiet, .name = "quiet" },
1076 { .opt_bool = &verbose, .name = "verbose" },
1077 { .opt_bool = &add_files_state.debug, .name = "debug" },
1078 { .opt_bool = &add_files_state.full_scan, .name = "full-scan" },
1079 { .opt_bool = &hooks, .name = "hooks" },
1080 { .opt_inherit = notmuch_shared_indexing_options },
1081 { .opt_inherit = notmuch_shared_options },
1085 opt_index = parse_arguments (argc, argv, options, 1);
1087 return EXIT_FAILURE;
1089 notmuch_process_shared_options (argv[0]);
1091 /* quiet trumps verbose */
1093 add_files_state.verbosity = VERBOSITY_QUIET;
1095 add_files_state.verbosity = VERBOSITY_VERBOSE;
1097 add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
1098 add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
1099 db_path = notmuch_config_get_database_path (config);
1100 add_files_state.db_path = db_path;
1102 if (! _setup_ignore (config, &add_files_state))
1103 return EXIT_FAILURE;
1105 for (i = 0; i < add_files_state.new_tags_length; i++) {
1106 const char *error_msg;
1108 error_msg = illegal_tag (add_files_state.new_tags[i], false);
1110 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
1111 add_files_state.new_tags[i], error_msg);
1112 return EXIT_FAILURE;
1117 ret = notmuch_run_hook (db_path, "pre-new");
1119 return EXIT_FAILURE;
1122 dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
1124 if (stat (dot_notmuch_path, &st)) {
1128 count_files (db_path, &count, &add_files_state);
1130 return EXIT_FAILURE;
1132 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1133 printf ("Found %d total files (that's not much mail).\n", count);
1134 if (notmuch_database_create (db_path, ¬much))
1135 return EXIT_FAILURE;
1136 add_files_state.total_files = count;
1138 char *status_string = NULL;
1139 if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1140 ¬much, &status_string)) {
1141 if (status_string) {
1142 fputs (status_string, stderr);
1143 free (status_string);
1145 return EXIT_FAILURE;
1148 notmuch_exit_if_unmatched_db_uuid (notmuch);
1150 if (notmuch_database_needs_upgrade (notmuch)) {
1151 time_t now = time (NULL);
1152 struct tm *gm_time = gmtime (&now);
1154 /* since dump files are written atomically, the amount of
1155 * harm from overwriting one within a second seems
1156 * relatively small. */
1158 const char *backup_name =
1159 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1161 gm_time->tm_year + 1900,
1162 gm_time->tm_mon + 1,
1168 if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1169 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1170 printf ("This process is safe to interrupt.\n");
1171 printf ("Backing up tags to %s...\n", backup_name);
1174 if (notmuch_database_dump (notmuch, backup_name, "",
1175 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, true)) {
1176 fprintf (stderr, "Backup failed. Aborting upgrade.");
1177 return EXIT_FAILURE;
1180 gettimeofday (&add_files_state.tv_start, NULL);
1181 status = notmuch_database_upgrade (
1183 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1186 printf ("Upgrade failed: %s\n",
1187 notmuch_status_to_string (status));
1188 notmuch_database_destroy (notmuch);
1189 return EXIT_FAILURE;
1191 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1192 printf ("Your notmuch database has now been upgraded.\n");
1195 add_files_state.total_files = 0;
1198 if (notmuch == NULL)
1199 return EXIT_FAILURE;
1201 status = notmuch_process_shared_indexing_options (notmuch, config);
1202 if (status != NOTMUCH_STATUS_SUCCESS) {
1203 fprintf (stderr, "Error: Failed to process index options. (%s)\n",
1204 notmuch_status_to_string (status));
1205 return EXIT_FAILURE;
1208 /* Set up our handler for SIGINT. We do this after having
1209 * potentially done a database upgrade we this interrupt handler
1211 memset (&action, 0, sizeof (struct sigaction));
1212 action.sa_handler = handle_sigint;
1213 sigemptyset (&action.sa_mask);
1214 action.sa_flags = SA_RESTART;
1215 sigaction (SIGINT, &action, NULL);
1217 talloc_free (dot_notmuch_path);
1218 dot_notmuch_path = NULL;
1220 gettimeofday (&add_files_state.tv_start, NULL);
1222 add_files_state.removed_files = _filename_list_create (config);
1223 add_files_state.removed_directories = _filename_list_create (config);
1224 add_files_state.directory_mtimes = _filename_list_create (config);
1226 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1227 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1228 setup_progress_printing_timer ();
1229 timer_is_active = true;
1232 ret = add_files (notmuch, db_path, &add_files_state);
1236 gettimeofday (&tv_start, NULL);
1237 for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1238 ret = remove_filename (notmuch, f->filename, &add_files_state);
1241 if (do_print_progress) {
1242 do_print_progress = 0;
1243 generic_print_progress ("Cleaned up", "messages",
1244 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1245 add_files_state.removed_files->count);
1249 gettimeofday (&tv_start, NULL);
1250 for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1251 ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1254 if (do_print_progress) {
1255 do_print_progress = 0;
1256 generic_print_progress ("Cleaned up", "directories",
1258 add_files_state.removed_directories->count);
1262 for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1263 notmuch_directory_t *directory;
1264 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1265 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1266 notmuch_directory_set_mtime (directory, f->mtime);
1267 notmuch_directory_destroy (directory);
1272 talloc_free (add_files_state.removed_files);
1273 talloc_free (add_files_state.removed_directories);
1274 talloc_free (add_files_state.directory_mtimes);
1276 if (timer_is_active)
1277 stop_progress_printing_timer ();
1279 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1280 print_results (&add_files_state);
1283 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1284 notmuch_status_to_string (ret));
1286 notmuch_database_destroy (notmuch);
1288 if (hooks && !ret && !interrupted)
1289 ret = notmuch_run_hook (db_path, "post-new");
1291 if (ret || interrupted)
1292 return EXIT_FAILURE;
1294 if (add_files_state.vanished_files)
1295 return NOTMUCH_EXIT_TEMPFAIL;
1297 return EXIT_SUCCESS;