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;
50 const char **new_tags;
51 size_t new_tags_length;
52 const char **ignore_verbatim;
53 size_t ignore_verbatim_length;
54 regex_t *ignore_regex;
55 size_t ignore_regex_length;
59 int added_messages, removed_messages, renamed_messages;
61 struct timeval tv_start;
63 _filename_list_t *removed_files;
64 _filename_list_t *removed_directories;
65 _filename_list_t *directory_mtimes;
67 bool synchronize_flags;
70 static volatile sig_atomic_t do_print_progress = 0;
73 handle_sigalrm (unused (int signal))
75 do_print_progress = 1;
78 static volatile sig_atomic_t interrupted;
81 handle_sigint (unused (int sig))
83 static char msg[] = "Stopping... \n";
85 /* This write is "opportunistic", so it's okay to ignore the
86 * result. It is not required for correctness, and if it does
87 * fail or produce a short write, we want to get out of the signal
88 * handler as quickly as possible, not retry it. */
89 IGNORE_RESULT (write (2, msg, sizeof(msg)-1));
93 static _filename_list_t *
94 _filename_list_create (const void *ctx)
96 _filename_list_t *list;
98 list = talloc (ctx, _filename_list_t);
103 list->tail = &list->head;
109 static _filename_node_t *
110 _filename_list_add (_filename_list_t *list,
111 const char *filename)
113 _filename_node_t *node = talloc (list, _filename_node_t);
117 node->filename = talloc_strdup (list, filename);
120 *(list->tail) = node;
121 list->tail = &node->next;
127 generic_print_progress (const char *action, const char *object,
128 struct timeval tv_start, unsigned processed, unsigned total)
130 struct timeval tv_now;
131 double elapsed_overall, rate_overall;
133 gettimeofday (&tv_now, NULL);
135 elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
136 rate_overall = processed / elapsed_overall;
138 printf ("%s %u ", action, processed);
141 printf ("of %u %s", total, object);
142 if (processed > 0 && elapsed_overall > 0.5) {
143 double time_remaining = ((total - processed) / rate_overall);
145 notmuch_time_print_formatted_seconds (time_remaining);
146 printf (" remaining)");
149 printf ("%s", object);
150 if (elapsed_overall > 0.5)
151 printf (" (%d %s/sec.)", (int) rate_overall, object);
153 printf (".\033[K\r");
159 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
161 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
165 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
167 return strcmp ((*a)->d_name, (*b)->d_name);
170 /* Return the type of a directory entry relative to path as a stat(2)
171 * mode. Like stat, this follows symlinks. Returns -1 and sets errno
172 * if the file's type cannot be determined (which includes dangling
176 dirent_type (const char *path, const struct dirent *entry)
180 int err, saved_errno;
183 /* Mapping from d_type to stat mode_t. We omit DT_LNK so that
184 * we'll fall through to stat and get the real file type. */
185 static const mode_t modes[] = {
193 if (entry->d_type < ARRAY_SIZE(modes) && modes[entry->d_type])
194 return modes[entry->d_type];
197 abspath = talloc_asprintf (NULL, "%s/%s", path, entry->d_name);
202 err = stat(abspath, &statbuf);
204 talloc_free (abspath);
209 return statbuf.st_mode & S_IFMT;
212 /* Test if the directory looks like a Maildir directory.
214 * Search through the array of directory entries to see if we can find all
215 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
217 * Return 1 if the directory looks like a Maildir and 0 otherwise.
220 _entries_resemble_maildir (const char *path, struct dirent **entries, int count)
224 for (i = 0; i < count; i++) {
225 if (dirent_type (path, entries[i]) != S_IFDIR)
228 if (strcmp(entries[i]->d_name, "new") == 0 ||
229 strcmp(entries[i]->d_name, "cur") == 0 ||
230 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_config_t *config, add_files_state_t *state)
250 const char **ignore_list, **ignore;
251 int nregex = 0, nverbatim = 0;
252 const char **verbatim = NULL;
253 regex_t *regex = NULL;
255 ignore_list = notmuch_config_get_new_ignore (config, NULL);
259 for (ignore = ignore_list; *ignore; ignore++) {
260 const char *s = *ignore;
261 size_t len = strlen (s);
264 fprintf (stderr, "Error: Empty string in new.ignore list\n");
273 if (len < 3 || s[len - 1] != '/') {
274 fprintf (stderr, "Error: Malformed pattern '%s' in new.ignore\n",
279 r = talloc_strndup (config, s + 1, len - 2);
280 regex = talloc_realloc (config, regex, regex_t, nregex + 1);
281 preg = ®ex[nregex];
283 rerr = regcomp (preg, r, REG_EXTENDED | REG_NOSUB);
285 size_t error_size = regerror (rerr, preg, NULL, 0);
286 char *error = talloc_size (r, error_size);
288 regerror (rerr, preg, error, error_size);
290 fprintf (stderr, "Error: Invalid regex '%s' in new.ignore: %s\n",
298 verbatim = talloc_realloc (config, verbatim, const char *,
300 verbatim[nverbatim++] = s;
304 state->ignore_regex = regex;
305 state->ignore_regex_length = nregex;
306 state->ignore_verbatim = verbatim;
307 state->ignore_verbatim_length = nverbatim;
313 _get_relative_path (const char *db_path, const char *dirpath, const char *entry)
315 size_t db_path_len = strlen (db_path);
318 if (strncmp (dirpath, db_path, db_path_len) != 0) {
319 fprintf (stderr, "Warning: '%s' is not a subdirectory of '%s'\n",
324 dirpath += db_path_len;
325 while (*dirpath == '/')
329 return talloc_asprintf (NULL, "%s/%s", dirpath, entry);
331 return talloc_strdup (NULL, entry);
334 /* Test if the file/directory is to be ignored.
337 _entry_in_ignore_list (add_files_state_t *state, const char *dirpath,
344 for (i = 0; i < state->ignore_verbatim_length; i++) {
345 if (strcmp (entry, state->ignore_verbatim[i]) == 0)
349 if (state->ignore_regex_length == 0)
352 path = _get_relative_path (state->db_path, dirpath, entry);
356 for (i = 0; i < state->ignore_regex_length; i++) {
357 if (regexec (&state->ignore_regex[i], path, 0, NULL, 0) == 0) {
368 /* Add a single file to the database. */
369 static notmuch_status_t
370 add_file (notmuch_database_t *notmuch, const char *filename,
371 add_files_state_t *state)
373 notmuch_message_t *message = NULL;
375 notmuch_status_t status;
377 status = notmuch_database_begin_atomic (notmuch);
381 status = notmuch_database_index_file (notmuch, filename, indexing_cli_choices.opts, &message);
384 case NOTMUCH_STATUS_SUCCESS:
385 state->added_messages++;
386 notmuch_message_freeze (message);
387 if (state->synchronize_flags)
388 notmuch_message_maildir_flags_to_tags (message);
390 for (tag = state->new_tags; *tag != NULL; tag++) {
391 if (strcmp ("unread", *tag) !=0 ||
392 !notmuch_message_has_maildir_flag (message, 'S')) {
393 notmuch_message_add_tag (message, *tag);
397 notmuch_message_thaw (message);
399 /* Non-fatal issues (go on to next file). */
400 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
401 if (state->synchronize_flags)
402 notmuch_message_maildir_flags_to_tags (message);
404 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
405 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
407 case NOTMUCH_STATUS_FILE_ERROR:
408 /* Someone renamed/removed the file between scandir and now. */
409 state->vanished_files++;
410 fprintf (stderr, "Unexpected error with file %s\n", filename);
411 (void) print_status_database ("add_file", notmuch, status);
413 /* Fatal issues. Don't process anymore. */
414 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
415 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
416 case NOTMUCH_STATUS_OUT_OF_MEMORY:
417 (void) print_status_database("add_file", notmuch, status);
420 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
424 status = notmuch_database_end_atomic (notmuch);
428 notmuch_message_destroy (message);
433 /* Examine 'path' recursively as follows:
435 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
436 * o Ask the database for its timestamp of 'path' (db_mtime)
438 * o Ask the filesystem for files and directories within 'path'
439 * (via scandir and stored in fs_entries)
441 * o Pass 1: For each directory in fs_entries, recursively call into
442 * this same function.
444 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
445 * the algorithm at this point, (this directory has not been
446 * updated in the filesystem since the last database scan of PASS
449 * o Ask the database for files and directories within 'path'
450 * (db_files and db_subdirs)
452 * o Pass 2: Walk fs_entries simultaneously with db_files and
453 * db_subdirs. Look for one of three interesting cases:
455 * 1. Regular file in fs_entries and not in db_files
456 * This is a new file to add_message into the database.
458 * 2. Filename in db_files not in fs_entries.
459 * This is a file that has been removed from the mail store.
461 * 3. Directory in db_subdirs not in fs_entries
462 * This is a directory that has been removed from the mail store.
464 * Note that the addition of a directory is not interesting here,
465 * since that will have been taken care of in pass 1. Also, we
466 * don't immediately act on file/directory removal since we must
467 * ensure that in the case of a rename that the new filename is
468 * added before the old filename is removed, (so that no
469 * information is lost from the database).
471 * o Tell the database to update its time of 'path' to 'fs_mtime'
472 * if fs_mtime isn't the current wall-clock time.
474 static notmuch_status_t
475 add_files (notmuch_database_t *notmuch,
477 add_files_state_t *state)
479 struct dirent *entry = NULL;
481 time_t fs_mtime, db_mtime;
482 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
483 struct dirent **fs_entries = NULL;
484 int i, num_fs_entries = 0, entry_type;
485 notmuch_directory_t *directory;
486 notmuch_filenames_t *db_files = NULL;
487 notmuch_filenames_t *db_subdirs = NULL;
492 if (stat (path, &st)) {
493 fprintf (stderr, "Error reading directory %s: %s\n",
494 path, strerror (errno));
495 return NOTMUCH_STATUS_FILE_ERROR;
497 stat_time = time (NULL);
499 if (! S_ISDIR (st.st_mode)) {
500 fprintf (stderr, "Error: %s is not a directory.\n", path);
501 return NOTMUCH_STATUS_FILE_ERROR;
504 fs_mtime = st.st_mtime;
506 status = notmuch_database_get_directory (notmuch, path, &directory);
511 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
513 /* If the directory is unchanged from our last scan and has no
514 * sub-directories, then return without scanning it at all. In
515 * some situations, skipping the scan can substantially reduce the
516 * cost of notmuch new, especially since the huge numbers of files
517 * in Maildirs make scans expensive, but all files live in leaf
520 * To check for sub-directories, we borrow a trick from find,
521 * kpathsea, and many other UNIX tools: since a directory's link
522 * count is the number of sub-directories (specifically, their
523 * '..' entries) plus 2 (the link from the parent and the link for
524 * '.'). This check is safe even on weird file systems, since
525 * file systems that can't compute this will return 0 or 1. This
526 * is safe even on *really* weird file systems like HFS+ that
527 * mistakenly return the total number of directory entries, since
528 * that only inflates the count beyond 2.
530 if (directory && fs_mtime == db_mtime && st.st_nlink == 2) {
531 /* There's one catch: pass 1 below considers symlinks to
532 * directories to be directories, but these don't increase the
533 * file system link count. So, only bail early if the
534 * database agrees that there are no sub-directories. */
535 db_subdirs = notmuch_directory_get_child_directories (directory);
536 if (!notmuch_filenames_valid (db_subdirs))
538 notmuch_filenames_destroy (db_subdirs);
542 /* If the database knows about this directory, then we sort based
543 * on strcmp to match the database sorting. Otherwise, we can do
544 * inode-based sorting for faster filesystem operation. */
545 num_fs_entries = scandir (path, &fs_entries, 0,
547 dirent_sort_strcmp_name : dirent_sort_inode);
549 if (num_fs_entries == -1) {
550 fprintf (stderr, "Error opening directory %s: %s\n",
551 path, strerror (errno));
552 /* We consider this a fatal error because, if a user moved a
553 * message from another directory that we were able to scan
554 * into this directory, skipping this directory will cause
555 * that message to be lost. */
556 ret = NOTMUCH_STATUS_FILE_ERROR;
560 /* Pass 1: Recurse into all sub-directories. */
561 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
563 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
564 entry = fs_entries[i];
566 /* Ignore special directories to avoid infinite recursion. */
567 if (_special_directory (entry->d_name))
570 /* Ignore any files/directories the user has configured to
571 * ignore. We do this before dirent_type both for performance
572 * and because we don't care if dirent_type fails on entries
573 * that are explicitly ignored.
575 if (_entry_in_ignore_list (state, path, entry->d_name)) {
577 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
578 path, entry->d_name);
582 /* We only want to descend into directories (and symlinks to
584 entry_type = dirent_type (path, entry);
585 if (entry_type == -1) {
586 /* Be pessimistic, e.g. so we don't lose lots of mail just
587 * because a user broke a symlink. */
588 fprintf (stderr, "Error reading file %s/%s: %s\n",
589 path, entry->d_name, strerror (errno));
590 return NOTMUCH_STATUS_FILE_ERROR;
591 } else if (entry_type != S_IFDIR) {
595 /* Ignore the .notmuch directory and any "tmp" directory
596 * that appears within a maildir.
598 if ((is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
599 strcmp (entry->d_name, ".notmuch") == 0)
602 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
603 status = add_files (notmuch, next, state);
612 /* If the directory's modification time in the filesystem is the
613 * same as what we recorded in the database the last time we
614 * scanned it, then we can skip the second pass entirely.
616 * We test for strict equality here to avoid a bug that can happen
617 * if the system clock jumps backward, (preventing new mail from
618 * being discovered until the clock catches up and the directory
619 * is modified again).
621 if (directory && fs_mtime == db_mtime)
624 /* If the database has never seen this directory before, we can
625 * simply leave db_files and db_subdirs NULL. */
627 db_files = notmuch_directory_get_child_files (directory);
628 db_subdirs = notmuch_directory_get_child_directories (directory);
631 /* Pass 2: Scan for new files, removed files, and removed directories. */
632 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
633 entry = fs_entries[i];
635 /* Ignore special directories early. */
636 if (_special_directory (entry->d_name))
639 /* Ignore files & directories user has configured to be ignored */
640 if (_entry_in_ignore_list (state, path, entry->d_name)) {
642 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
643 path, entry->d_name);
647 /* Check if we've walked past any names in db_files or
648 * db_subdirs. If so, these have been deleted. */
649 while (notmuch_filenames_valid (db_files) &&
650 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
652 char *absolute = talloc_asprintf (state->removed_files,
654 notmuch_filenames_get (db_files));
657 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
660 _filename_list_add (state->removed_files, absolute);
662 notmuch_filenames_move_to_next (db_files);
665 while (notmuch_filenames_valid (db_subdirs) &&
666 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
668 const char *filename = notmuch_filenames_get (db_subdirs);
670 if (strcmp (filename, entry->d_name) < 0)
672 char *absolute = talloc_asprintf (state->removed_directories,
673 "%s/%s", path, filename);
675 printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
678 _filename_list_add (state->removed_directories, absolute);
681 notmuch_filenames_move_to_next (db_subdirs);
684 /* Only add regular files (and symlinks to regular files). */
685 entry_type = dirent_type (path, entry);
686 if (entry_type == -1) {
687 fprintf (stderr, "Error reading file %s/%s: %s\n",
688 path, entry->d_name, strerror (errno));
689 return NOTMUCH_STATUS_FILE_ERROR;
690 } else if (entry_type != S_IFREG) {
694 /* Don't add a file that we've added before. */
695 if (notmuch_filenames_valid (db_files) &&
696 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
698 notmuch_filenames_move_to_next (db_files);
702 /* We're now looking at a regular file that doesn't yet exist
703 * in the database, so add it. */
704 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
706 state->processed_files++;
708 if (state->verbosity >= VERBOSITY_VERBOSE) {
709 if (state->output_is_a_tty)
712 printf ("%i/%i: %s", state->processed_files, state->total_files,
715 putchar((state->output_is_a_tty) ? '\r' : '\n');
719 status = add_file (notmuch, next, state);
725 if (do_print_progress) {
726 do_print_progress = 0;
727 generic_print_progress ("Processed", "files", state->tv_start,
728 state->processed_files, state->total_files);
738 /* Now that we've walked the whole filesystem list, anything left
739 * over in the database lists has been deleted. */
740 while (notmuch_filenames_valid (db_files))
742 char *absolute = talloc_asprintf (state->removed_files,
744 notmuch_filenames_get (db_files));
746 printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
749 _filename_list_add (state->removed_files, absolute);
751 notmuch_filenames_move_to_next (db_files);
754 while (notmuch_filenames_valid (db_subdirs))
756 char *absolute = talloc_asprintf (state->removed_directories,
758 notmuch_filenames_get (db_subdirs));
761 printf ("(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
764 _filename_list_add (state->removed_directories, absolute);
766 notmuch_filenames_move_to_next (db_subdirs);
769 /* If the directory's mtime is the same as the wall-clock time
770 * when we stat'ed the directory, we skip updating the mtime in
771 * the database because a message could be delivered later in this
772 * same second. This may lead to unnecessary re-scans, but it
773 * avoids overlooking messages. */
774 if (fs_mtime != stat_time)
775 _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
781 for (i = 0; i < num_fs_entries; i++)
782 free (fs_entries[i]);
787 notmuch_filenames_destroy (db_subdirs);
789 notmuch_filenames_destroy (db_files);
791 notmuch_directory_destroy (directory);
797 setup_progress_printing_timer (void)
799 struct sigaction action;
800 struct itimerval timerval;
802 /* Set up our handler for SIGALRM */
803 memset (&action, 0, sizeof (struct sigaction));
804 action.sa_handler = handle_sigalrm;
805 sigemptyset (&action.sa_mask);
806 action.sa_flags = SA_RESTART;
807 sigaction (SIGALRM, &action, NULL);
809 /* Then start a timer to send SIGALRM once per second. */
810 timerval.it_interval.tv_sec = 1;
811 timerval.it_interval.tv_usec = 0;
812 timerval.it_value.tv_sec = 1;
813 timerval.it_value.tv_usec = 0;
814 setitimer (ITIMER_REAL, &timerval, NULL);
818 stop_progress_printing_timer (void)
820 struct sigaction action;
821 struct itimerval timerval;
823 /* Now stop the timer. */
824 timerval.it_interval.tv_sec = 0;
825 timerval.it_interval.tv_usec = 0;
826 timerval.it_value.tv_sec = 0;
827 timerval.it_value.tv_usec = 0;
828 setitimer (ITIMER_REAL, &timerval, NULL);
830 /* And disable the signal handler. */
831 action.sa_handler = SIG_IGN;
832 sigaction (SIGALRM, &action, NULL);
836 /* XXX: This should be merged with the add_files function since it
837 * shares a lot of logic with it. */
838 /* Recursively count all regular files in path and all sub-directories
839 * of path. The result is added to *count (which should be
840 * initialized to zero by the top-level caller before calling
843 count_files (const char *path, int *count, add_files_state_t *state)
845 struct dirent *entry = NULL;
847 struct dirent **fs_entries = NULL;
848 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
851 if (num_fs_entries == -1) {
852 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
853 path, strerror (errno));
857 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
858 entry = fs_entries[i];
860 /* Ignore special directories to avoid infinite recursion.
861 * Also ignore the .notmuch directory.
863 if (_special_directory (entry->d_name) ||
864 strcmp (entry->d_name, ".notmuch") == 0)
867 /* Ignore any files/directories the user has configured to be
870 if (_entry_in_ignore_list (state, path, entry->d_name)) {
872 printf ("(D) count_files: explicitly ignoring %s/%s\n",
873 path, entry->d_name);
877 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
879 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
880 path, entry->d_name);
884 entry_type = dirent_type (path, entry);
885 if (entry_type == S_IFREG) {
887 if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
888 printf ("Found %d files so far.\r", *count);
891 } else if (entry_type == S_IFDIR) {
892 count_files (next, count, state);
900 for (i = 0; i < num_fs_entries; i++)
901 free (fs_entries[i]);
908 upgrade_print_progress (void *closure,
911 add_files_state_t *state = closure;
913 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
916 struct timeval tv_now;
917 double elapsed, time_remaining;
919 gettimeofday (&tv_now, NULL);
921 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
922 time_remaining = (elapsed / progress) * (1.0 - progress);
924 notmuch_time_print_formatted_seconds (time_remaining);
925 printf (" remaining)");
933 /* Remove one message filename from the database. */
934 static notmuch_status_t
935 remove_filename (notmuch_database_t *notmuch,
937 add_files_state_t *add_files_state)
939 notmuch_status_t status;
940 notmuch_message_t *message;
941 status = notmuch_database_begin_atomic (notmuch);
944 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
945 if (status || message == NULL)
948 status = notmuch_database_remove_message (notmuch, path);
949 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
950 add_files_state->renamed_messages++;
951 if (add_files_state->synchronize_flags == true)
952 notmuch_message_maildir_flags_to_tags (message);
953 status = NOTMUCH_STATUS_SUCCESS;
954 } else if (status == NOTMUCH_STATUS_SUCCESS) {
955 add_files_state->removed_messages++;
957 notmuch_message_destroy (message);
960 notmuch_database_end_atomic (notmuch);
964 /* Recursively remove all filenames from the database referring to
965 * 'path' (or to any of its children). */
966 static notmuch_status_t
967 _remove_directory (void *ctx,
968 notmuch_database_t *notmuch,
970 add_files_state_t *add_files_state)
972 notmuch_status_t status;
973 notmuch_directory_t *directory;
974 notmuch_filenames_t *files, *subdirs;
977 status = notmuch_database_get_directory (notmuch, path, &directory);
978 if (status || !directory)
981 for (files = notmuch_directory_get_child_files (directory);
982 notmuch_filenames_valid (files);
983 notmuch_filenames_move_to_next (files))
985 absolute = talloc_asprintf (ctx, "%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))
997 absolute = talloc_asprintf (ctx, "%s/%s", path,
998 notmuch_filenames_get (subdirs));
999 status = _remove_directory (ctx, notmuch, absolute, add_files_state);
1000 talloc_free (absolute);
1005 status = notmuch_directory_delete (directory);
1009 notmuch_directory_destroy (directory);
1014 print_results (const add_files_state_t *state)
1017 struct timeval tv_now;
1019 gettimeofday (&tv_now, NULL);
1020 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
1022 if (state->processed_files) {
1023 printf ("Processed %d %s in ", state->processed_files,
1024 state->processed_files == 1 ? "file" : "total files");
1025 notmuch_time_print_formatted_seconds (elapsed);
1027 printf (" (%d files/sec.)",
1028 (int) (state->processed_files / elapsed));
1029 printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
1032 if (state->added_messages)
1033 printf ("Added %d new %s to the database.", state->added_messages,
1034 state->added_messages == 1 ? "message" : "messages");
1036 printf ("No new mail.");
1038 if (state->removed_messages)
1039 printf (" Removed %d %s.", state->removed_messages,
1040 state->removed_messages == 1 ? "message" : "messages");
1042 if (state->renamed_messages)
1043 printf (" Detected %d file %s.", state->renamed_messages,
1044 state->renamed_messages == 1 ? "rename" : "renames");
1050 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
1052 notmuch_database_t *notmuch;
1053 add_files_state_t add_files_state = {
1054 .verbosity = VERBOSITY_NORMAL,
1056 .output_is_a_tty = isatty (fileno (stdout)),
1058 struct timeval tv_start;
1061 const char *db_path;
1062 char *dot_notmuch_path;
1063 struct sigaction action;
1064 _filename_node_t *f;
1067 bool timer_is_active = false;
1069 bool quiet = false, verbose = false;
1070 notmuch_status_t status;
1072 notmuch_opt_desc_t options[] = {
1073 { .opt_bool = &quiet, .name = "quiet" },
1074 { .opt_bool = &verbose, .name = "verbose" },
1075 { .opt_bool = &add_files_state.debug, .name = "debug" },
1076 { .opt_bool = &hooks, .name = "hooks" },
1077 { .opt_inherit = notmuch_shared_indexing_options },
1078 { .opt_inherit = notmuch_shared_options },
1082 opt_index = parse_arguments (argc, argv, options, 1);
1084 return EXIT_FAILURE;
1086 notmuch_process_shared_options (argv[0]);
1088 /* quiet trumps verbose */
1090 add_files_state.verbosity = VERBOSITY_QUIET;
1092 add_files_state.verbosity = VERBOSITY_VERBOSE;
1094 add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
1095 add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
1096 db_path = notmuch_config_get_database_path (config);
1097 add_files_state.db_path = db_path;
1099 if (! _setup_ignore (config, &add_files_state))
1100 return EXIT_FAILURE;
1102 for (i = 0; i < add_files_state.new_tags_length; i++) {
1103 const char *error_msg;
1105 error_msg = illegal_tag (add_files_state.new_tags[i], false);
1107 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
1108 add_files_state.new_tags[i], error_msg);
1109 return EXIT_FAILURE;
1114 ret = notmuch_run_hook (db_path, "pre-new");
1116 return EXIT_FAILURE;
1119 dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
1121 if (stat (dot_notmuch_path, &st)) {
1125 count_files (db_path, &count, &add_files_state);
1127 return EXIT_FAILURE;
1129 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1130 printf ("Found %d total files (that's not much mail).\n", count);
1131 if (notmuch_database_create (db_path, ¬much))
1132 return EXIT_FAILURE;
1133 add_files_state.total_files = count;
1135 char *status_string = NULL;
1136 if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1137 ¬much, &status_string)) {
1138 if (status_string) {
1139 fputs (status_string, stderr);
1140 free (status_string);
1142 return EXIT_FAILURE;
1145 notmuch_exit_if_unmatched_db_uuid (notmuch);
1147 if (notmuch_database_needs_upgrade (notmuch)) {
1148 time_t now = time (NULL);
1149 struct tm *gm_time = gmtime (&now);
1151 /* since dump files are written atomically, the amount of
1152 * harm from overwriting one within a second seems
1153 * relatively small. */
1155 const char *backup_name =
1156 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1158 gm_time->tm_year + 1900,
1159 gm_time->tm_mon + 1,
1165 if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1166 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1167 printf ("This process is safe to interrupt.\n");
1168 printf ("Backing up tags to %s...\n", backup_name);
1171 if (notmuch_database_dump (notmuch, backup_name, "",
1172 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, true)) {
1173 fprintf (stderr, "Backup failed. Aborting upgrade.");
1174 return EXIT_FAILURE;
1177 gettimeofday (&add_files_state.tv_start, NULL);
1178 status = notmuch_database_upgrade (
1180 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1183 printf ("Upgrade failed: %s\n",
1184 notmuch_status_to_string (status));
1185 notmuch_database_destroy (notmuch);
1186 return EXIT_FAILURE;
1188 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1189 printf ("Your notmuch database has now been upgraded.\n");
1192 add_files_state.total_files = 0;
1195 if (notmuch == NULL)
1196 return EXIT_FAILURE;
1198 status = notmuch_process_shared_indexing_options (notmuch, config);
1199 if (status != NOTMUCH_STATUS_SUCCESS) {
1200 fprintf (stderr, "Error: Failed to process index options. (%s)\n",
1201 notmuch_status_to_string (status));
1202 return EXIT_FAILURE;
1205 /* Set up our handler for SIGINT. We do this after having
1206 * potentially done a database upgrade we this interrupt handler
1208 memset (&action, 0, sizeof (struct sigaction));
1209 action.sa_handler = handle_sigint;
1210 sigemptyset (&action.sa_mask);
1211 action.sa_flags = SA_RESTART;
1212 sigaction (SIGINT, &action, NULL);
1214 talloc_free (dot_notmuch_path);
1215 dot_notmuch_path = NULL;
1217 gettimeofday (&add_files_state.tv_start, NULL);
1219 add_files_state.removed_files = _filename_list_create (config);
1220 add_files_state.removed_directories = _filename_list_create (config);
1221 add_files_state.directory_mtimes = _filename_list_create (config);
1223 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1224 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1225 setup_progress_printing_timer ();
1226 timer_is_active = true;
1229 ret = add_files (notmuch, db_path, &add_files_state);
1233 gettimeofday (&tv_start, NULL);
1234 for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1235 ret = remove_filename (notmuch, f->filename, &add_files_state);
1238 if (do_print_progress) {
1239 do_print_progress = 0;
1240 generic_print_progress ("Cleaned up", "messages",
1241 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1242 add_files_state.removed_files->count);
1246 gettimeofday (&tv_start, NULL);
1247 for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1248 ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1251 if (do_print_progress) {
1252 do_print_progress = 0;
1253 generic_print_progress ("Cleaned up", "directories",
1255 add_files_state.removed_directories->count);
1259 for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1260 notmuch_directory_t *directory;
1261 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1262 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1263 notmuch_directory_set_mtime (directory, f->mtime);
1264 notmuch_directory_destroy (directory);
1269 talloc_free (add_files_state.removed_files);
1270 talloc_free (add_files_state.removed_directories);
1271 talloc_free (add_files_state.directory_mtimes);
1273 if (timer_is_active)
1274 stop_progress_printing_timer ();
1276 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1277 print_results (&add_files_state);
1280 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1281 notmuch_status_to_string (ret));
1283 notmuch_database_destroy (notmuch);
1285 if (hooks && !ret && !interrupted)
1286 ret = notmuch_run_hook (db_path, "post-new");
1288 if (ret || interrupted)
1289 return EXIT_FAILURE;
1291 if (add_files_state.vanished_files)
1292 return NOTMUCH_EXIT_TEMPFAIL;
1294 return EXIT_SUCCESS;