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 enum verbosity verbosity;
48 const char **new_tags;
49 size_t new_tags_length;
50 const char **new_ignore;
51 size_t new_ignore_length;
55 int added_messages, removed_messages, renamed_messages;
56 struct timeval tv_start;
58 _filename_list_t *removed_files;
59 _filename_list_t *removed_directories;
60 _filename_list_t *directory_mtimes;
62 notmuch_bool_t synchronize_flags;
65 static volatile sig_atomic_t do_print_progress = 0;
68 handle_sigalrm (unused (int signal))
70 do_print_progress = 1;
73 static volatile sig_atomic_t interrupted;
76 handle_sigint (unused (int sig))
78 static char msg[] = "Stopping... \n";
80 /* This write is "opportunistic", so it's okay to ignore the
81 * result. It is not required for correctness, and if it does
82 * fail or produce a short write, we want to get out of the signal
83 * handler as quickly as possible, not retry it. */
84 IGNORE_RESULT (write (2, msg, sizeof(msg)-1));
88 static _filename_list_t *
89 _filename_list_create (const void *ctx)
91 _filename_list_t *list;
93 list = talloc (ctx, _filename_list_t);
98 list->tail = &list->head;
104 static _filename_node_t *
105 _filename_list_add (_filename_list_t *list,
106 const char *filename)
108 _filename_node_t *node = talloc (list, _filename_node_t);
112 node->filename = talloc_strdup (list, filename);
115 *(list->tail) = node;
116 list->tail = &node->next;
122 generic_print_progress (const char *action, const char *object,
123 struct timeval tv_start, unsigned processed, unsigned total)
125 struct timeval tv_now;
126 double elapsed_overall, rate_overall;
128 gettimeofday (&tv_now, NULL);
130 elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
131 rate_overall = processed / elapsed_overall;
133 printf ("%s %d ", action, processed);
136 printf ("of %d %s", total, object);
137 if (processed > 0 && elapsed_overall > 0.5) {
138 double time_remaining = ((total - processed) / rate_overall);
140 notmuch_time_print_formatted_seconds (time_remaining);
141 printf (" remaining)");
144 printf ("%s", object);
145 if (elapsed_overall > 0.5)
146 printf (" (%d %s/sec.)", (int) rate_overall, object);
148 printf (".\033[K\r");
154 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
156 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
160 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
162 return strcmp ((*a)->d_name, (*b)->d_name);
165 /* Return the type of a directory entry relative to path as a stat(2)
166 * mode. Like stat, this follows symlinks. Returns -1 and sets errno
167 * if the file's type cannot be determined (which includes dangling
171 dirent_type (const char *path, const struct dirent *entry)
175 int err, saved_errno;
178 /* Mapping from d_type to stat mode_t. We omit DT_LNK so that
179 * we'll fall through to stat and get the real file type. */
180 static const mode_t modes[] = {
188 if (entry->d_type < ARRAY_SIZE(modes) && modes[entry->d_type])
189 return modes[entry->d_type];
192 abspath = talloc_asprintf (NULL, "%s/%s", path, entry->d_name);
197 err = stat(abspath, &statbuf);
199 talloc_free (abspath);
204 return statbuf.st_mode & S_IFMT;
207 /* Test if the directory looks like a Maildir directory.
209 * Search through the array of directory entries to see if we can find all
210 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
212 * Return 1 if the directory looks like a Maildir and 0 otherwise.
215 _entries_resemble_maildir (const char *path, struct dirent **entries, int count)
219 for (i = 0; i < count; i++) {
220 if (dirent_type (path, entries[i]) != S_IFDIR)
223 if (strcmp(entries[i]->d_name, "new") == 0 ||
224 strcmp(entries[i]->d_name, "cur") == 0 ||
225 strcmp(entries[i]->d_name, "tmp") == 0)
236 /* Test if the file/directory is to be ignored.
238 static notmuch_bool_t
239 _entry_in_ignore_list (const char *entry, add_files_state_t *state)
243 for (i = 0; i < state->new_ignore_length; i++)
244 if (strcmp (entry, state->new_ignore[i]) == 0)
250 /* Add a single file to the database. */
251 static notmuch_status_t
252 add_file (notmuch_database_t *notmuch, const char *filename,
253 add_files_state_t *state)
255 notmuch_message_t *message = NULL;
257 notmuch_status_t status;
259 status = notmuch_database_begin_atomic (notmuch);
263 status = notmuch_database_add_message (notmuch, filename, &message);
266 case NOTMUCH_STATUS_SUCCESS:
267 state->added_messages++;
268 notmuch_message_freeze (message);
269 for (tag = state->new_tags; *tag != NULL; tag++)
270 notmuch_message_add_tag (message, *tag);
271 if (state->synchronize_flags)
272 notmuch_message_maildir_flags_to_tags (message);
273 notmuch_message_thaw (message);
275 /* Non-fatal issues (go on to next file). */
276 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
277 if (state->synchronize_flags)
278 notmuch_message_maildir_flags_to_tags (message);
280 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
281 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
283 /* Fatal issues. Don't process anymore. */
284 case NOTMUCH_STATUS_FILE_ERROR:
285 fprintf (stderr, "Unexpected error with file %s\n", filename);
286 (void) print_status_database ("add_file", notmuch, status);
288 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
289 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
290 case NOTMUCH_STATUS_OUT_OF_MEMORY:
291 fprintf (stderr, "Error: %s. Halting processing.\n",
292 notmuch_status_to_string (status));
295 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
299 status = notmuch_database_end_atomic (notmuch);
303 notmuch_message_destroy (message);
308 /* Examine 'path' recursively as follows:
310 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
311 * o Ask the database for its timestamp of 'path' (db_mtime)
313 * o Ask the filesystem for files and directories within 'path'
314 * (via scandir and stored in fs_entries)
316 * o Pass 1: For each directory in fs_entries, recursively call into
317 * this same function.
319 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
320 * the algorithm at this point, (this directory has not been
321 * updated in the filesystem since the last database scan of PASS
324 * o Ask the database for files and directories within 'path'
325 * (db_files and db_subdirs)
327 * o Pass 2: Walk fs_entries simultaneously with db_files and
328 * db_subdirs. Look for one of three interesting cases:
330 * 1. Regular file in fs_entries and not in db_files
331 * This is a new file to add_message into the database.
333 * 2. Filename in db_files not in fs_entries.
334 * This is a file that has been removed from the mail store.
336 * 3. Directory in db_subdirs not in fs_entries
337 * This is a directory that has been removed from the mail store.
339 * Note that the addition of a directory is not interesting here,
340 * since that will have been taken care of in pass 1. Also, we
341 * don't immediately act on file/directory removal since we must
342 * ensure that in the case of a rename that the new filename is
343 * added before the old filename is removed, (so that no
344 * information is lost from the database).
346 * o Tell the database to update its time of 'path' to 'fs_mtime'
347 * if fs_mtime isn't the current wall-clock time.
349 static notmuch_status_t
350 add_files (notmuch_database_t *notmuch,
352 add_files_state_t *state)
354 struct dirent *entry = NULL;
356 time_t fs_mtime, db_mtime;
357 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
358 struct dirent **fs_entries = NULL;
359 int i, num_fs_entries = 0, entry_type;
360 notmuch_directory_t *directory;
361 notmuch_filenames_t *db_files = NULL;
362 notmuch_filenames_t *db_subdirs = NULL;
365 notmuch_bool_t is_maildir;
367 if (stat (path, &st)) {
368 fprintf (stderr, "Error reading directory %s: %s\n",
369 path, strerror (errno));
370 return NOTMUCH_STATUS_FILE_ERROR;
372 stat_time = time (NULL);
374 if (! S_ISDIR (st.st_mode)) {
375 fprintf (stderr, "Error: %s is not a directory.\n", path);
376 return NOTMUCH_STATUS_FILE_ERROR;
379 fs_mtime = st.st_mtime;
381 status = notmuch_database_get_directory (notmuch, path, &directory);
386 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
388 /* If the directory is unchanged from our last scan and has no
389 * sub-directories, then return without scanning it at all. In
390 * some situations, skipping the scan can substantially reduce the
391 * cost of notmuch new, especially since the huge numbers of files
392 * in Maildirs make scans expensive, but all files live in leaf
395 * To check for sub-directories, we borrow a trick from find,
396 * kpathsea, and many other UNIX tools: since a directory's link
397 * count is the number of sub-directories (specifically, their
398 * '..' entries) plus 2 (the link from the parent and the link for
399 * '.'). This check is safe even on weird file systems, since
400 * file systems that can't compute this will return 0 or 1. This
401 * is safe even on *really* weird file systems like HFS+ that
402 * mistakenly return the total number of directory entries, since
403 * that only inflates the count beyond 2.
405 if (directory && fs_mtime == db_mtime && st.st_nlink == 2) {
406 /* There's one catch: pass 1 below considers symlinks to
407 * directories to be directories, but these don't increase the
408 * file system link count. So, only bail early if the
409 * database agrees that there are no sub-directories. */
410 db_subdirs = notmuch_directory_get_child_directories (directory);
411 if (!notmuch_filenames_valid (db_subdirs))
413 notmuch_filenames_destroy (db_subdirs);
417 /* If the database knows about this directory, then we sort based
418 * on strcmp to match the database sorting. Otherwise, we can do
419 * inode-based sorting for faster filesystem operation. */
420 num_fs_entries = scandir (path, &fs_entries, 0,
422 dirent_sort_strcmp_name : dirent_sort_inode);
424 if (num_fs_entries == -1) {
425 fprintf (stderr, "Error opening directory %s: %s\n",
426 path, strerror (errno));
427 /* We consider this a fatal error because, if a user moved a
428 * message from another directory that we were able to scan
429 * into this directory, skipping this directory will cause
430 * that message to be lost. */
431 ret = NOTMUCH_STATUS_FILE_ERROR;
435 /* Pass 1: Recurse into all sub-directories. */
436 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
438 for (i = 0; i < num_fs_entries; i++) {
442 entry = fs_entries[i];
444 /* Ignore any files/directories the user has configured to
445 * ignore. We do this before dirent_type both for performance
446 * and because we don't care if dirent_type fails on entries
447 * that are explicitly ignored.
449 if (_entry_in_ignore_list (entry->d_name, state)) {
451 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
452 path, entry->d_name);
456 /* We only want to descend into directories (and symlinks to
458 entry_type = dirent_type (path, entry);
459 if (entry_type == -1) {
460 /* Be pessimistic, e.g. so we don't lose lots of mail just
461 * because a user broke a symlink. */
462 fprintf (stderr, "Error reading file %s/%s: %s\n",
463 path, entry->d_name, strerror (errno));
464 return NOTMUCH_STATUS_FILE_ERROR;
465 } else if (entry_type != S_IFDIR) {
469 /* Ignore special directories to avoid infinite recursion.
470 * Also ignore the .notmuch directory and any "tmp" directory
471 * that appears within a maildir.
473 if (strcmp (entry->d_name, ".") == 0 ||
474 strcmp (entry->d_name, "..") == 0 ||
475 (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
476 strcmp (entry->d_name, ".notmuch") == 0)
479 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
480 status = add_files (notmuch, next, state);
489 /* If the directory's modification time in the filesystem is the
490 * same as what we recorded in the database the last time we
491 * scanned it, then we can skip the second pass entirely.
493 * We test for strict equality here to avoid a bug that can happen
494 * if the system clock jumps backward, (preventing new mail from
495 * being discovered until the clock catches up and the directory
496 * is modified again).
498 if (directory && fs_mtime == db_mtime)
501 /* If the database has never seen this directory before, we can
502 * simply leave db_files and db_subdirs NULL. */
504 db_files = notmuch_directory_get_child_files (directory);
505 db_subdirs = notmuch_directory_get_child_directories (directory);
508 /* Pass 2: Scan for new files, removed files, and removed directories. */
509 for (i = 0; i < num_fs_entries; i++)
514 entry = fs_entries[i];
516 /* Ignore files & directories user has configured to be ignored */
517 if (_entry_in_ignore_list (entry->d_name, state)) {
519 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
520 path, entry->d_name);
524 /* Check if we've walked past any names in db_files or
525 * db_subdirs. If so, these have been deleted. */
526 while (notmuch_filenames_valid (db_files) &&
527 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
529 char *absolute = talloc_asprintf (state->removed_files,
531 notmuch_filenames_get (db_files));
534 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
537 _filename_list_add (state->removed_files, absolute);
539 notmuch_filenames_move_to_next (db_files);
542 while (notmuch_filenames_valid (db_subdirs) &&
543 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
545 const char *filename = notmuch_filenames_get (db_subdirs);
547 if (strcmp (filename, entry->d_name) < 0)
549 char *absolute = talloc_asprintf (state->removed_directories,
550 "%s/%s", path, filename);
552 printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
555 _filename_list_add (state->removed_directories, absolute);
558 notmuch_filenames_move_to_next (db_subdirs);
561 /* Only add regular files (and symlinks to regular files). */
562 entry_type = dirent_type (path, entry);
563 if (entry_type == -1) {
564 fprintf (stderr, "Error reading file %s/%s: %s\n",
565 path, entry->d_name, strerror (errno));
566 return NOTMUCH_STATUS_FILE_ERROR;
567 } else if (entry_type != S_IFREG) {
571 /* Don't add a file that we've added before. */
572 if (notmuch_filenames_valid (db_files) &&
573 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
575 notmuch_filenames_move_to_next (db_files);
579 /* We're now looking at a regular file that doesn't yet exist
580 * in the database, so add it. */
581 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
583 state->processed_files++;
585 if (state->verbosity >= VERBOSITY_VERBOSE) {
586 if (state->output_is_a_tty)
589 printf ("%i/%i: %s", state->processed_files, state->total_files,
592 putchar((state->output_is_a_tty) ? '\r' : '\n');
596 status = add_file (notmuch, next, state);
602 if (do_print_progress) {
603 do_print_progress = 0;
604 generic_print_progress ("Processed", "files", state->tv_start,
605 state->processed_files, state->total_files);
615 /* Now that we've walked the whole filesystem list, anything left
616 * over in the database lists has been deleted. */
617 while (notmuch_filenames_valid (db_files))
619 char *absolute = talloc_asprintf (state->removed_files,
621 notmuch_filenames_get (db_files));
623 printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
626 _filename_list_add (state->removed_files, absolute);
628 notmuch_filenames_move_to_next (db_files);
631 while (notmuch_filenames_valid (db_subdirs))
633 char *absolute = talloc_asprintf (state->removed_directories,
635 notmuch_filenames_get (db_subdirs));
638 printf ("(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
641 _filename_list_add (state->removed_directories, absolute);
643 notmuch_filenames_move_to_next (db_subdirs);
646 /* If the directory's mtime is the same as the wall-clock time
647 * when we stat'ed the directory, we skip updating the mtime in
648 * the database because a message could be delivered later in this
649 * same second. This may lead to unnecessary re-scans, but it
650 * avoids overlooking messages. */
651 if (fs_mtime != stat_time)
652 _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
658 for (i = 0; i < num_fs_entries; i++)
659 free (fs_entries[i]);
664 notmuch_filenames_destroy (db_subdirs);
666 notmuch_filenames_destroy (db_files);
668 notmuch_directory_destroy (directory);
674 setup_progress_printing_timer (void)
676 struct sigaction action;
677 struct itimerval timerval;
679 /* Set up our handler for SIGALRM */
680 memset (&action, 0, sizeof (struct sigaction));
681 action.sa_handler = handle_sigalrm;
682 sigemptyset (&action.sa_mask);
683 action.sa_flags = SA_RESTART;
684 sigaction (SIGALRM, &action, NULL);
686 /* Then start a timer to send SIGALRM once per second. */
687 timerval.it_interval.tv_sec = 1;
688 timerval.it_interval.tv_usec = 0;
689 timerval.it_value.tv_sec = 1;
690 timerval.it_value.tv_usec = 0;
691 setitimer (ITIMER_REAL, &timerval, NULL);
695 stop_progress_printing_timer (void)
697 struct sigaction action;
698 struct itimerval timerval;
700 /* Now stop the timer. */
701 timerval.it_interval.tv_sec = 0;
702 timerval.it_interval.tv_usec = 0;
703 timerval.it_value.tv_sec = 0;
704 timerval.it_value.tv_usec = 0;
705 setitimer (ITIMER_REAL, &timerval, NULL);
707 /* And disable the signal handler. */
708 action.sa_handler = SIG_IGN;
709 sigaction (SIGALRM, &action, NULL);
713 /* XXX: This should be merged with the add_files function since it
714 * shares a lot of logic with it. */
715 /* Recursively count all regular files in path and all sub-directories
716 * of path. The result is added to *count (which should be
717 * initialized to zero by the top-level caller before calling
720 count_files (const char *path, int *count, add_files_state_t *state)
722 struct dirent *entry = NULL;
724 struct dirent **fs_entries = NULL;
725 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
728 if (num_fs_entries == -1) {
729 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
730 path, strerror (errno));
734 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
735 entry = fs_entries[i];
737 /* Ignore special directories to avoid infinite recursion.
738 * Also ignore the .notmuch directory and files/directories
739 * the user has configured to be ignored.
741 if (strcmp (entry->d_name, ".") == 0 ||
742 strcmp (entry->d_name, "..") == 0 ||
743 strcmp (entry->d_name, ".notmuch") == 0 ||
744 _entry_in_ignore_list (entry->d_name, state))
746 if (state->debug && _entry_in_ignore_list (entry->d_name, state))
747 printf ("(D) count_files: explicitly ignoring %s/%s\n",
753 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
755 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
756 path, entry->d_name);
760 entry_type = dirent_type (path, entry);
761 if (entry_type == S_IFREG) {
763 if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
764 printf ("Found %d files so far.\r", *count);
767 } else if (entry_type == S_IFDIR) {
768 count_files (next, count, state);
776 for (i = 0; i < num_fs_entries; i++)
777 free (fs_entries[i]);
784 upgrade_print_progress (void *closure,
787 add_files_state_t *state = closure;
789 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
792 struct timeval tv_now;
793 double elapsed, time_remaining;
795 gettimeofday (&tv_now, NULL);
797 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
798 time_remaining = (elapsed / progress) * (1.0 - progress);
800 notmuch_time_print_formatted_seconds (time_remaining);
801 printf (" remaining)");
809 /* Remove one message filename from the database. */
810 static notmuch_status_t
811 remove_filename (notmuch_database_t *notmuch,
813 add_files_state_t *add_files_state)
815 notmuch_status_t status;
816 notmuch_message_t *message;
817 status = notmuch_database_begin_atomic (notmuch);
820 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
821 if (status || message == NULL)
824 status = notmuch_database_remove_message (notmuch, path);
825 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
826 add_files_state->renamed_messages++;
827 if (add_files_state->synchronize_flags == TRUE)
828 notmuch_message_maildir_flags_to_tags (message);
829 status = NOTMUCH_STATUS_SUCCESS;
830 } else if (status == NOTMUCH_STATUS_SUCCESS) {
831 add_files_state->removed_messages++;
833 notmuch_message_destroy (message);
836 notmuch_database_end_atomic (notmuch);
840 /* Recursively remove all filenames from the database referring to
841 * 'path' (or to any of its children). */
842 static notmuch_status_t
843 _remove_directory (void *ctx,
844 notmuch_database_t *notmuch,
846 add_files_state_t *add_files_state)
848 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
849 notmuch_directory_t *directory;
850 notmuch_filenames_t *files, *subdirs;
853 status = notmuch_database_get_directory (notmuch, path, &directory);
854 if (status || !directory)
857 for (files = notmuch_directory_get_child_files (directory);
858 notmuch_filenames_valid (files);
859 notmuch_filenames_move_to_next (files))
861 absolute = talloc_asprintf (ctx, "%s/%s", path,
862 notmuch_filenames_get (files));
863 status = remove_filename (notmuch, absolute, add_files_state);
864 talloc_free (absolute);
869 for (subdirs = notmuch_directory_get_child_directories (directory);
870 notmuch_filenames_valid (subdirs);
871 notmuch_filenames_move_to_next (subdirs))
873 absolute = talloc_asprintf (ctx, "%s/%s", path,
874 notmuch_filenames_get (subdirs));
875 status = _remove_directory (ctx, notmuch, absolute, add_files_state);
876 talloc_free (absolute);
881 status = notmuch_directory_delete (directory);
885 notmuch_directory_destroy (directory);
890 print_results (const add_files_state_t *state)
893 struct timeval tv_now;
895 gettimeofday (&tv_now, NULL);
896 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
898 if (state->processed_files) {
899 printf ("Processed %d %s in ", state->processed_files,
900 state->processed_files == 1 ? "file" : "total files");
901 notmuch_time_print_formatted_seconds (elapsed);
903 printf (" (%d files/sec.).\033[K\n",
904 (int) (state->processed_files / elapsed));
906 printf (".\033[K\n");
909 if (state->added_messages)
910 printf ("Added %d new %s to the database.", state->added_messages,
911 state->added_messages == 1 ? "message" : "messages");
913 printf ("No new mail.");
915 if (state->removed_messages)
916 printf (" Removed %d %s.", state->removed_messages,
917 state->removed_messages == 1 ? "message" : "messages");
919 if (state->renamed_messages)
920 printf (" Detected %d file %s.", state->renamed_messages,
921 state->renamed_messages == 1 ? "rename" : "renames");
927 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
929 notmuch_database_t *notmuch;
930 add_files_state_t add_files_state = {
931 .verbosity = VERBOSITY_NORMAL,
933 .output_is_a_tty = isatty (fileno (stdout)),
935 struct timeval tv_start;
939 char *dot_notmuch_path;
940 struct sigaction action;
944 notmuch_bool_t timer_is_active = FALSE;
945 notmuch_bool_t no_hooks = FALSE;
946 notmuch_bool_t quiet = FALSE, verbose = FALSE;
947 notmuch_status_t status;
949 notmuch_opt_desc_t options[] = {
950 { NOTMUCH_OPT_BOOLEAN, &quiet, "quiet", 'q', 0 },
951 { NOTMUCH_OPT_BOOLEAN, &verbose, "verbose", 'v', 0 },
952 { NOTMUCH_OPT_BOOLEAN, &add_files_state.debug, "debug", 'd', 0 },
953 { NOTMUCH_OPT_BOOLEAN, &no_hooks, "no-hooks", 'n', 0 },
954 { NOTMUCH_OPT_INHERIT, (void *) ¬much_shared_options, NULL, 0, 0 },
958 opt_index = parse_arguments (argc, argv, options, 1);
962 notmuch_process_shared_options (argv[0]);
964 /* quiet trumps verbose */
966 add_files_state.verbosity = VERBOSITY_QUIET;
968 add_files_state.verbosity = VERBOSITY_VERBOSE;
970 add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
971 add_files_state.new_ignore = notmuch_config_get_new_ignore (config, &add_files_state.new_ignore_length);
972 add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
973 db_path = notmuch_config_get_database_path (config);
975 for (i = 0; i < add_files_state.new_tags_length; i++) {
976 const char *error_msg;
978 error_msg = illegal_tag (add_files_state.new_tags[i], FALSE);
980 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
981 add_files_state.new_tags[i], error_msg);
987 ret = notmuch_run_hook (db_path, "pre-new");
992 dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
994 if (stat (dot_notmuch_path, &st)) {
998 count_files (db_path, &count, &add_files_state);
1000 return EXIT_FAILURE;
1002 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1003 printf ("Found %d total files (that's not much mail).\n", count);
1004 if (notmuch_database_create (db_path, ¬much))
1005 return EXIT_FAILURE;
1006 add_files_state.total_files = count;
1008 char *status_string = NULL;
1009 if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1010 ¬much, &status_string)) {
1011 if (status_string) {
1012 fputs (status_string, stderr);
1013 free (status_string);
1015 return EXIT_FAILURE;
1018 notmuch_exit_if_unmatched_db_uuid (notmuch);
1020 if (notmuch_database_needs_upgrade (notmuch)) {
1021 time_t now = time (NULL);
1022 struct tm *gm_time = gmtime (&now);
1024 /* since dump files are written atomically, the amount of
1025 * harm from overwriting one within a second seems
1026 * relatively small. */
1028 const char *backup_name =
1029 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1031 gm_time->tm_year + 1900,
1032 gm_time->tm_mon + 1,
1038 if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1039 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1040 printf ("This process is safe to interrupt.\n");
1041 printf ("Backing up tags to %s...\n", backup_name);
1044 if (notmuch_database_dump (notmuch, backup_name, "",
1045 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, TRUE)) {
1046 fprintf (stderr, "Backup failed. Aborting upgrade.");
1047 return EXIT_FAILURE;
1050 gettimeofday (&add_files_state.tv_start, NULL);
1051 status = notmuch_database_upgrade (
1053 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1056 printf ("Upgrade failed: %s\n",
1057 notmuch_status_to_string (status));
1058 notmuch_database_destroy (notmuch);
1059 return EXIT_FAILURE;
1061 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1062 printf ("Your notmuch database has now been upgraded.\n");
1065 add_files_state.total_files = 0;
1068 if (notmuch == NULL)
1069 return EXIT_FAILURE;
1071 /* Set up our handler for SIGINT. We do this after having
1072 * potentially done a database upgrade we this interrupt handler
1074 memset (&action, 0, sizeof (struct sigaction));
1075 action.sa_handler = handle_sigint;
1076 sigemptyset (&action.sa_mask);
1077 action.sa_flags = SA_RESTART;
1078 sigaction (SIGINT, &action, NULL);
1080 talloc_free (dot_notmuch_path);
1081 dot_notmuch_path = NULL;
1083 gettimeofday (&add_files_state.tv_start, NULL);
1085 add_files_state.removed_files = _filename_list_create (config);
1086 add_files_state.removed_directories = _filename_list_create (config);
1087 add_files_state.directory_mtimes = _filename_list_create (config);
1089 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1090 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1091 setup_progress_printing_timer ();
1092 timer_is_active = TRUE;
1095 ret = add_files (notmuch, db_path, &add_files_state);
1099 gettimeofday (&tv_start, NULL);
1100 for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1101 ret = remove_filename (notmuch, f->filename, &add_files_state);
1104 if (do_print_progress) {
1105 do_print_progress = 0;
1106 generic_print_progress ("Cleaned up", "messages",
1107 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1108 add_files_state.removed_files->count);
1112 gettimeofday (&tv_start, NULL);
1113 for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1114 ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1117 if (do_print_progress) {
1118 do_print_progress = 0;
1119 generic_print_progress ("Cleaned up", "directories",
1121 add_files_state.removed_directories->count);
1125 for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1126 notmuch_directory_t *directory;
1127 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1128 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1129 notmuch_directory_set_mtime (directory, f->mtime);
1130 notmuch_directory_destroy (directory);
1135 talloc_free (add_files_state.removed_files);
1136 talloc_free (add_files_state.removed_directories);
1137 talloc_free (add_files_state.directory_mtimes);
1139 if (timer_is_active)
1140 stop_progress_printing_timer ();
1142 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1143 print_results (&add_files_state);
1146 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1147 notmuch_status_to_string (ret));
1149 notmuch_database_destroy (notmuch);
1151 if (!no_hooks && !ret && !interrupted)
1152 ret = notmuch_run_hook (db_path, "post-new");
1154 return ret || interrupted ? EXIT_FAILURE : EXIT_SUCCESS;