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;
57 struct timeval tv_start;
59 _filename_list_t *removed_files;
60 _filename_list_t *removed_directories;
61 _filename_list_t *directory_mtimes;
63 notmuch_bool_t synchronize_flags;
66 static volatile sig_atomic_t do_print_progress = 0;
69 handle_sigalrm (unused (int signal))
71 do_print_progress = 1;
74 static volatile sig_atomic_t interrupted;
77 handle_sigint (unused (int sig))
79 static char msg[] = "Stopping... \n";
81 /* This write is "opportunistic", so it's okay to ignore the
82 * result. It is not required for correctness, and if it does
83 * fail or produce a short write, we want to get out of the signal
84 * handler as quickly as possible, not retry it. */
85 IGNORE_RESULT (write (2, msg, sizeof(msg)-1));
89 static _filename_list_t *
90 _filename_list_create (const void *ctx)
92 _filename_list_t *list;
94 list = talloc (ctx, _filename_list_t);
99 list->tail = &list->head;
105 static _filename_node_t *
106 _filename_list_add (_filename_list_t *list,
107 const char *filename)
109 _filename_node_t *node = talloc (list, _filename_node_t);
113 node->filename = talloc_strdup (list, filename);
116 *(list->tail) = node;
117 list->tail = &node->next;
123 generic_print_progress (const char *action, const char *object,
124 struct timeval tv_start, unsigned processed, unsigned total)
126 struct timeval tv_now;
127 double elapsed_overall, rate_overall;
129 gettimeofday (&tv_now, NULL);
131 elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
132 rate_overall = processed / elapsed_overall;
134 printf ("%s %u ", action, processed);
137 printf ("of %u %s", total, object);
138 if (processed > 0 && elapsed_overall > 0.5) {
139 double time_remaining = ((total - processed) / rate_overall);
141 notmuch_time_print_formatted_seconds (time_remaining);
142 printf (" remaining)");
145 printf ("%s", object);
146 if (elapsed_overall > 0.5)
147 printf (" (%d %s/sec.)", (int) rate_overall, object);
149 printf (".\033[K\r");
155 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
157 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
161 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
163 return strcmp ((*a)->d_name, (*b)->d_name);
166 /* Return the type of a directory entry relative to path as a stat(2)
167 * mode. Like stat, this follows symlinks. Returns -1 and sets errno
168 * if the file's type cannot be determined (which includes dangling
172 dirent_type (const char *path, const struct dirent *entry)
176 int err, saved_errno;
179 /* Mapping from d_type to stat mode_t. We omit DT_LNK so that
180 * we'll fall through to stat and get the real file type. */
181 static const mode_t modes[] = {
189 if (entry->d_type < ARRAY_SIZE(modes) && modes[entry->d_type])
190 return modes[entry->d_type];
193 abspath = talloc_asprintf (NULL, "%s/%s", path, entry->d_name);
198 err = stat(abspath, &statbuf);
200 talloc_free (abspath);
205 return statbuf.st_mode & S_IFMT;
208 /* Test if the directory looks like a Maildir directory.
210 * Search through the array of directory entries to see if we can find all
211 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
213 * Return 1 if the directory looks like a Maildir and 0 otherwise.
216 _entries_resemble_maildir (const char *path, struct dirent **entries, int count)
220 for (i = 0; i < count; i++) {
221 if (dirent_type (path, entries[i]) != S_IFDIR)
224 if (strcmp(entries[i]->d_name, "new") == 0 ||
225 strcmp(entries[i]->d_name, "cur") == 0 ||
226 strcmp(entries[i]->d_name, "tmp") == 0)
237 static notmuch_bool_t
238 _special_directory (const char *entry)
240 return strcmp (entry, ".") == 0 || strcmp (entry, "..") == 0;
243 /* Test if the file/directory is to be ignored.
245 static notmuch_bool_t
246 _entry_in_ignore_list (const char *entry, add_files_state_t *state)
250 for (i = 0; i < state->new_ignore_length; i++)
251 if (strcmp (entry, state->new_ignore[i]) == 0)
257 /* Add a single file to the database. */
258 static notmuch_status_t
259 add_file (notmuch_database_t *notmuch, const char *filename,
260 add_files_state_t *state)
262 notmuch_message_t *message = NULL;
264 notmuch_status_t status;
266 status = notmuch_database_begin_atomic (notmuch);
270 status = notmuch_database_index_file (notmuch, filename, NULL, &message);
273 case NOTMUCH_STATUS_SUCCESS:
274 state->added_messages++;
275 notmuch_message_freeze (message);
276 if (state->synchronize_flags)
277 notmuch_message_maildir_flags_to_tags (message);
279 for (tag = state->new_tags; *tag != NULL; tag++) {
280 if (strcmp ("unread", *tag) !=0 ||
281 !notmuch_message_has_maildir_flag (message, 'S')) {
282 notmuch_message_add_tag (message, *tag);
286 notmuch_message_thaw (message);
288 /* Non-fatal issues (go on to next file). */
289 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
290 if (state->synchronize_flags)
291 notmuch_message_maildir_flags_to_tags (message);
293 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
294 fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
296 case NOTMUCH_STATUS_FILE_ERROR:
297 /* Someone renamed/removed the file between scandir and now. */
298 state->vanished_files++;
299 fprintf (stderr, "Unexpected error with file %s\n", filename);
300 (void) print_status_database ("add_file", notmuch, status);
302 /* Fatal issues. Don't process anymore. */
303 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
304 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
305 case NOTMUCH_STATUS_OUT_OF_MEMORY:
306 (void) print_status_database("add_file", notmuch, status);
309 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
313 status = notmuch_database_end_atomic (notmuch);
317 notmuch_message_destroy (message);
322 /* Examine 'path' recursively as follows:
324 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
325 * o Ask the database for its timestamp of 'path' (db_mtime)
327 * o Ask the filesystem for files and directories within 'path'
328 * (via scandir and stored in fs_entries)
330 * o Pass 1: For each directory in fs_entries, recursively call into
331 * this same function.
333 * o Compare fs_mtime to db_mtime. If they are equivalent, terminate
334 * the algorithm at this point, (this directory has not been
335 * updated in the filesystem since the last database scan of PASS
338 * o Ask the database for files and directories within 'path'
339 * (db_files and db_subdirs)
341 * o Pass 2: Walk fs_entries simultaneously with db_files and
342 * db_subdirs. Look for one of three interesting cases:
344 * 1. Regular file in fs_entries and not in db_files
345 * This is a new file to add_message into the database.
347 * 2. Filename in db_files not in fs_entries.
348 * This is a file that has been removed from the mail store.
350 * 3. Directory in db_subdirs not in fs_entries
351 * This is a directory that has been removed from the mail store.
353 * Note that the addition of a directory is not interesting here,
354 * since that will have been taken care of in pass 1. Also, we
355 * don't immediately act on file/directory removal since we must
356 * ensure that in the case of a rename that the new filename is
357 * added before the old filename is removed, (so that no
358 * information is lost from the database).
360 * o Tell the database to update its time of 'path' to 'fs_mtime'
361 * if fs_mtime isn't the current wall-clock time.
363 static notmuch_status_t
364 add_files (notmuch_database_t *notmuch,
366 add_files_state_t *state)
368 struct dirent *entry = NULL;
370 time_t fs_mtime, db_mtime;
371 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
372 struct dirent **fs_entries = NULL;
373 int i, num_fs_entries = 0, entry_type;
374 notmuch_directory_t *directory;
375 notmuch_filenames_t *db_files = NULL;
376 notmuch_filenames_t *db_subdirs = NULL;
379 notmuch_bool_t is_maildir;
381 if (stat (path, &st)) {
382 fprintf (stderr, "Error reading directory %s: %s\n",
383 path, strerror (errno));
384 return NOTMUCH_STATUS_FILE_ERROR;
386 stat_time = time (NULL);
388 if (! S_ISDIR (st.st_mode)) {
389 fprintf (stderr, "Error: %s is not a directory.\n", path);
390 return NOTMUCH_STATUS_FILE_ERROR;
393 fs_mtime = st.st_mtime;
395 status = notmuch_database_get_directory (notmuch, path, &directory);
400 db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
402 /* If the directory is unchanged from our last scan and has no
403 * sub-directories, then return without scanning it at all. In
404 * some situations, skipping the scan can substantially reduce the
405 * cost of notmuch new, especially since the huge numbers of files
406 * in Maildirs make scans expensive, but all files live in leaf
409 * To check for sub-directories, we borrow a trick from find,
410 * kpathsea, and many other UNIX tools: since a directory's link
411 * count is the number of sub-directories (specifically, their
412 * '..' entries) plus 2 (the link from the parent and the link for
413 * '.'). This check is safe even on weird file systems, since
414 * file systems that can't compute this will return 0 or 1. This
415 * is safe even on *really* weird file systems like HFS+ that
416 * mistakenly return the total number of directory entries, since
417 * that only inflates the count beyond 2.
419 if (directory && fs_mtime == db_mtime && st.st_nlink == 2) {
420 /* There's one catch: pass 1 below considers symlinks to
421 * directories to be directories, but these don't increase the
422 * file system link count. So, only bail early if the
423 * database agrees that there are no sub-directories. */
424 db_subdirs = notmuch_directory_get_child_directories (directory);
425 if (!notmuch_filenames_valid (db_subdirs))
427 notmuch_filenames_destroy (db_subdirs);
431 /* If the database knows about this directory, then we sort based
432 * on strcmp to match the database sorting. Otherwise, we can do
433 * inode-based sorting for faster filesystem operation. */
434 num_fs_entries = scandir (path, &fs_entries, 0,
436 dirent_sort_strcmp_name : dirent_sort_inode);
438 if (num_fs_entries == -1) {
439 fprintf (stderr, "Error opening directory %s: %s\n",
440 path, strerror (errno));
441 /* We consider this a fatal error because, if a user moved a
442 * message from another directory that we were able to scan
443 * into this directory, skipping this directory will cause
444 * that message to be lost. */
445 ret = NOTMUCH_STATUS_FILE_ERROR;
449 /* Pass 1: Recurse into all sub-directories. */
450 is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
452 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
453 entry = fs_entries[i];
455 /* Ignore any files/directories the user has configured to
456 * ignore. We do this before dirent_type both for performance
457 * and because we don't care if dirent_type fails on entries
458 * that are explicitly ignored.
460 if (_entry_in_ignore_list (entry->d_name, state)) {
462 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
463 path, entry->d_name);
467 /* We only want to descend into directories (and symlinks to
469 entry_type = dirent_type (path, entry);
470 if (entry_type == -1) {
471 /* Be pessimistic, e.g. so we don't lose lots of mail just
472 * because a user broke a symlink. */
473 fprintf (stderr, "Error reading file %s/%s: %s\n",
474 path, entry->d_name, strerror (errno));
475 return NOTMUCH_STATUS_FILE_ERROR;
476 } else if (entry_type != S_IFDIR) {
480 /* Ignore special directories to avoid infinite recursion.
481 * Also ignore the .notmuch directory and any "tmp" directory
482 * that appears within a maildir.
484 if (_special_directory (entry->d_name) ||
485 (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
486 strcmp (entry->d_name, ".notmuch") == 0)
489 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
490 status = add_files (notmuch, next, state);
499 /* If the directory's modification time in the filesystem is the
500 * same as what we recorded in the database the last time we
501 * scanned it, then we can skip the second pass entirely.
503 * We test for strict equality here to avoid a bug that can happen
504 * if the system clock jumps backward, (preventing new mail from
505 * being discovered until the clock catches up and the directory
506 * is modified again).
508 if (directory && fs_mtime == db_mtime)
511 /* If the database has never seen this directory before, we can
512 * simply leave db_files and db_subdirs NULL. */
514 db_files = notmuch_directory_get_child_files (directory);
515 db_subdirs = notmuch_directory_get_child_directories (directory);
518 /* Pass 2: Scan for new files, removed files, and removed directories. */
519 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
520 entry = fs_entries[i];
522 /* Ignore files & directories user has configured to be ignored */
523 if (_entry_in_ignore_list (entry->d_name, state)) {
525 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
526 path, entry->d_name);
530 /* Check if we've walked past any names in db_files or
531 * db_subdirs. If so, these have been deleted. */
532 while (notmuch_filenames_valid (db_files) &&
533 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
535 char *absolute = talloc_asprintf (state->removed_files,
537 notmuch_filenames_get (db_files));
540 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
543 _filename_list_add (state->removed_files, absolute);
545 notmuch_filenames_move_to_next (db_files);
548 while (notmuch_filenames_valid (db_subdirs) &&
549 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
551 const char *filename = notmuch_filenames_get (db_subdirs);
553 if (strcmp (filename, entry->d_name) < 0)
555 char *absolute = talloc_asprintf (state->removed_directories,
556 "%s/%s", path, filename);
558 printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
561 _filename_list_add (state->removed_directories, absolute);
564 notmuch_filenames_move_to_next (db_subdirs);
567 /* Only add regular files (and symlinks to regular files). */
568 entry_type = dirent_type (path, entry);
569 if (entry_type == -1) {
570 fprintf (stderr, "Error reading file %s/%s: %s\n",
571 path, entry->d_name, strerror (errno));
572 return NOTMUCH_STATUS_FILE_ERROR;
573 } else if (entry_type != S_IFREG) {
577 /* Don't add a file that we've added before. */
578 if (notmuch_filenames_valid (db_files) &&
579 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
581 notmuch_filenames_move_to_next (db_files);
585 /* We're now looking at a regular file that doesn't yet exist
586 * in the database, so add it. */
587 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
589 state->processed_files++;
591 if (state->verbosity >= VERBOSITY_VERBOSE) {
592 if (state->output_is_a_tty)
595 printf ("%i/%i: %s", state->processed_files, state->total_files,
598 putchar((state->output_is_a_tty) ? '\r' : '\n');
602 status = add_file (notmuch, next, state);
608 if (do_print_progress) {
609 do_print_progress = 0;
610 generic_print_progress ("Processed", "files", state->tv_start,
611 state->processed_files, state->total_files);
621 /* Now that we've walked the whole filesystem list, anything left
622 * over in the database lists has been deleted. */
623 while (notmuch_filenames_valid (db_files))
625 char *absolute = talloc_asprintf (state->removed_files,
627 notmuch_filenames_get (db_files));
629 printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
632 _filename_list_add (state->removed_files, absolute);
634 notmuch_filenames_move_to_next (db_files);
637 while (notmuch_filenames_valid (db_subdirs))
639 char *absolute = talloc_asprintf (state->removed_directories,
641 notmuch_filenames_get (db_subdirs));
644 printf ("(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
647 _filename_list_add (state->removed_directories, absolute);
649 notmuch_filenames_move_to_next (db_subdirs);
652 /* If the directory's mtime is the same as the wall-clock time
653 * when we stat'ed the directory, we skip updating the mtime in
654 * the database because a message could be delivered later in this
655 * same second. This may lead to unnecessary re-scans, but it
656 * avoids overlooking messages. */
657 if (fs_mtime != stat_time)
658 _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
664 for (i = 0; i < num_fs_entries; i++)
665 free (fs_entries[i]);
670 notmuch_filenames_destroy (db_subdirs);
672 notmuch_filenames_destroy (db_files);
674 notmuch_directory_destroy (directory);
680 setup_progress_printing_timer (void)
682 struct sigaction action;
683 struct itimerval timerval;
685 /* Set up our handler for SIGALRM */
686 memset (&action, 0, sizeof (struct sigaction));
687 action.sa_handler = handle_sigalrm;
688 sigemptyset (&action.sa_mask);
689 action.sa_flags = SA_RESTART;
690 sigaction (SIGALRM, &action, NULL);
692 /* Then start a timer to send SIGALRM once per second. */
693 timerval.it_interval.tv_sec = 1;
694 timerval.it_interval.tv_usec = 0;
695 timerval.it_value.tv_sec = 1;
696 timerval.it_value.tv_usec = 0;
697 setitimer (ITIMER_REAL, &timerval, NULL);
701 stop_progress_printing_timer (void)
703 struct sigaction action;
704 struct itimerval timerval;
706 /* Now stop the timer. */
707 timerval.it_interval.tv_sec = 0;
708 timerval.it_interval.tv_usec = 0;
709 timerval.it_value.tv_sec = 0;
710 timerval.it_value.tv_usec = 0;
711 setitimer (ITIMER_REAL, &timerval, NULL);
713 /* And disable the signal handler. */
714 action.sa_handler = SIG_IGN;
715 sigaction (SIGALRM, &action, NULL);
719 /* XXX: This should be merged with the add_files function since it
720 * shares a lot of logic with it. */
721 /* Recursively count all regular files in path and all sub-directories
722 * of path. The result is added to *count (which should be
723 * initialized to zero by the top-level caller before calling
726 count_files (const char *path, int *count, add_files_state_t *state)
728 struct dirent *entry = NULL;
730 struct dirent **fs_entries = NULL;
731 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
734 if (num_fs_entries == -1) {
735 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
736 path, strerror (errno));
740 for (i = 0; i < num_fs_entries && ! interrupted; i++) {
741 entry = fs_entries[i];
743 /* Ignore special directories to avoid infinite recursion.
744 * Also ignore the .notmuch directory.
746 if (_special_directory (entry->d_name) ||
747 strcmp (entry->d_name, ".notmuch") == 0)
750 /* Ignore any files/directories the user has configured to be
753 if (_entry_in_ignore_list (entry->d_name, state)) {
755 printf ("(D) count_files: explicitly ignoring %s/%s\n",
756 path, entry->d_name);
760 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
762 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
763 path, entry->d_name);
767 entry_type = dirent_type (path, entry);
768 if (entry_type == S_IFREG) {
770 if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
771 printf ("Found %d files so far.\r", *count);
774 } else if (entry_type == S_IFDIR) {
775 count_files (next, count, state);
783 for (i = 0; i < num_fs_entries; i++)
784 free (fs_entries[i]);
791 upgrade_print_progress (void *closure,
794 add_files_state_t *state = closure;
796 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
799 struct timeval tv_now;
800 double elapsed, time_remaining;
802 gettimeofday (&tv_now, NULL);
804 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
805 time_remaining = (elapsed / progress) * (1.0 - progress);
807 notmuch_time_print_formatted_seconds (time_remaining);
808 printf (" remaining)");
816 /* Remove one message filename from the database. */
817 static notmuch_status_t
818 remove_filename (notmuch_database_t *notmuch,
820 add_files_state_t *add_files_state)
822 notmuch_status_t status;
823 notmuch_message_t *message;
824 status = notmuch_database_begin_atomic (notmuch);
827 status = notmuch_database_find_message_by_filename (notmuch, path, &message);
828 if (status || message == NULL)
831 status = notmuch_database_remove_message (notmuch, path);
832 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
833 add_files_state->renamed_messages++;
834 if (add_files_state->synchronize_flags == TRUE)
835 notmuch_message_maildir_flags_to_tags (message);
836 status = NOTMUCH_STATUS_SUCCESS;
837 } else if (status == NOTMUCH_STATUS_SUCCESS) {
838 add_files_state->removed_messages++;
840 notmuch_message_destroy (message);
843 notmuch_database_end_atomic (notmuch);
847 /* Recursively remove all filenames from the database referring to
848 * 'path' (or to any of its children). */
849 static notmuch_status_t
850 _remove_directory (void *ctx,
851 notmuch_database_t *notmuch,
853 add_files_state_t *add_files_state)
855 notmuch_status_t status;
856 notmuch_directory_t *directory;
857 notmuch_filenames_t *files, *subdirs;
860 status = notmuch_database_get_directory (notmuch, path, &directory);
861 if (status || !directory)
864 for (files = notmuch_directory_get_child_files (directory);
865 notmuch_filenames_valid (files);
866 notmuch_filenames_move_to_next (files))
868 absolute = talloc_asprintf (ctx, "%s/%s", path,
869 notmuch_filenames_get (files));
870 status = remove_filename (notmuch, absolute, add_files_state);
871 talloc_free (absolute);
876 for (subdirs = notmuch_directory_get_child_directories (directory);
877 notmuch_filenames_valid (subdirs);
878 notmuch_filenames_move_to_next (subdirs))
880 absolute = talloc_asprintf (ctx, "%s/%s", path,
881 notmuch_filenames_get (subdirs));
882 status = _remove_directory (ctx, notmuch, absolute, add_files_state);
883 talloc_free (absolute);
888 status = notmuch_directory_delete (directory);
892 notmuch_directory_destroy (directory);
897 print_results (const add_files_state_t *state)
900 struct timeval tv_now;
902 gettimeofday (&tv_now, NULL);
903 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
905 if (state->processed_files) {
906 printf ("Processed %d %s in ", state->processed_files,
907 state->processed_files == 1 ? "file" : "total files");
908 notmuch_time_print_formatted_seconds (elapsed);
910 printf (" (%d files/sec.)",
911 (int) (state->processed_files / elapsed));
912 printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
915 if (state->added_messages)
916 printf ("Added %d new %s to the database.", state->added_messages,
917 state->added_messages == 1 ? "message" : "messages");
919 printf ("No new mail.");
921 if (state->removed_messages)
922 printf (" Removed %d %s.", state->removed_messages,
923 state->removed_messages == 1 ? "message" : "messages");
925 if (state->renamed_messages)
926 printf (" Detected %d file %s.", state->renamed_messages,
927 state->renamed_messages == 1 ? "rename" : "renames");
933 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
935 notmuch_database_t *notmuch;
936 add_files_state_t add_files_state = {
937 .verbosity = VERBOSITY_NORMAL,
939 .output_is_a_tty = isatty (fileno (stdout)),
941 struct timeval tv_start;
945 char *dot_notmuch_path;
946 struct sigaction action;
950 notmuch_bool_t timer_is_active = FALSE;
951 notmuch_bool_t no_hooks = FALSE;
952 notmuch_bool_t quiet = FALSE, verbose = FALSE;
953 notmuch_status_t status;
955 notmuch_opt_desc_t options[] = {
956 { NOTMUCH_OPT_BOOLEAN, &quiet, "quiet", 'q', 0 },
957 { NOTMUCH_OPT_BOOLEAN, &verbose, "verbose", 'v', 0 },
958 { NOTMUCH_OPT_BOOLEAN, &add_files_state.debug, "debug", 'd', 0 },
959 { NOTMUCH_OPT_BOOLEAN, &no_hooks, "no-hooks", 'n', 0 },
960 { NOTMUCH_OPT_INHERIT, (void *) ¬much_shared_options, NULL, 0, 0 },
964 opt_index = parse_arguments (argc, argv, options, 1);
968 notmuch_process_shared_options (argv[0]);
970 /* quiet trumps verbose */
972 add_files_state.verbosity = VERBOSITY_QUIET;
974 add_files_state.verbosity = VERBOSITY_VERBOSE;
976 add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
977 add_files_state.new_ignore = notmuch_config_get_new_ignore (config, &add_files_state.new_ignore_length);
978 add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
979 db_path = notmuch_config_get_database_path (config);
981 for (i = 0; i < add_files_state.new_tags_length; i++) {
982 const char *error_msg;
984 error_msg = illegal_tag (add_files_state.new_tags[i], FALSE);
986 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
987 add_files_state.new_tags[i], error_msg);
993 ret = notmuch_run_hook (db_path, "pre-new");
998 dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
1000 if (stat (dot_notmuch_path, &st)) {
1004 count_files (db_path, &count, &add_files_state);
1006 return EXIT_FAILURE;
1008 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1009 printf ("Found %d total files (that's not much mail).\n", count);
1010 if (notmuch_database_create (db_path, ¬much))
1011 return EXIT_FAILURE;
1012 add_files_state.total_files = count;
1014 char *status_string = NULL;
1015 if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1016 ¬much, &status_string)) {
1017 if (status_string) {
1018 fputs (status_string, stderr);
1019 free (status_string);
1021 return EXIT_FAILURE;
1024 notmuch_exit_if_unmatched_db_uuid (notmuch);
1026 if (notmuch_database_needs_upgrade (notmuch)) {
1027 time_t now = time (NULL);
1028 struct tm *gm_time = gmtime (&now);
1030 /* since dump files are written atomically, the amount of
1031 * harm from overwriting one within a second seems
1032 * relatively small. */
1034 const char *backup_name =
1035 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1037 gm_time->tm_year + 1900,
1038 gm_time->tm_mon + 1,
1044 if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1045 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1046 printf ("This process is safe to interrupt.\n");
1047 printf ("Backing up tags to %s...\n", backup_name);
1050 if (notmuch_database_dump (notmuch, backup_name, "",
1051 DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, TRUE)) {
1052 fprintf (stderr, "Backup failed. Aborting upgrade.");
1053 return EXIT_FAILURE;
1056 gettimeofday (&add_files_state.tv_start, NULL);
1057 status = notmuch_database_upgrade (
1059 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1062 printf ("Upgrade failed: %s\n",
1063 notmuch_status_to_string (status));
1064 notmuch_database_destroy (notmuch);
1065 return EXIT_FAILURE;
1067 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1068 printf ("Your notmuch database has now been upgraded.\n");
1071 add_files_state.total_files = 0;
1074 if (notmuch == NULL)
1075 return EXIT_FAILURE;
1077 /* Set up our handler for SIGINT. We do this after having
1078 * potentially done a database upgrade we this interrupt handler
1080 memset (&action, 0, sizeof (struct sigaction));
1081 action.sa_handler = handle_sigint;
1082 sigemptyset (&action.sa_mask);
1083 action.sa_flags = SA_RESTART;
1084 sigaction (SIGINT, &action, NULL);
1086 talloc_free (dot_notmuch_path);
1087 dot_notmuch_path = NULL;
1089 gettimeofday (&add_files_state.tv_start, NULL);
1091 add_files_state.removed_files = _filename_list_create (config);
1092 add_files_state.removed_directories = _filename_list_create (config);
1093 add_files_state.directory_mtimes = _filename_list_create (config);
1095 if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1096 add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1097 setup_progress_printing_timer ();
1098 timer_is_active = TRUE;
1101 ret = add_files (notmuch, db_path, &add_files_state);
1105 gettimeofday (&tv_start, NULL);
1106 for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1107 ret = remove_filename (notmuch, f->filename, &add_files_state);
1110 if (do_print_progress) {
1111 do_print_progress = 0;
1112 generic_print_progress ("Cleaned up", "messages",
1113 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1114 add_files_state.removed_files->count);
1118 gettimeofday (&tv_start, NULL);
1119 for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1120 ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1123 if (do_print_progress) {
1124 do_print_progress = 0;
1125 generic_print_progress ("Cleaned up", "directories",
1127 add_files_state.removed_directories->count);
1131 for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1132 notmuch_directory_t *directory;
1133 status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1134 if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1135 notmuch_directory_set_mtime (directory, f->mtime);
1136 notmuch_directory_destroy (directory);
1141 talloc_free (add_files_state.removed_files);
1142 talloc_free (add_files_state.removed_directories);
1143 talloc_free (add_files_state.directory_mtimes);
1145 if (timer_is_active)
1146 stop_progress_printing_timer ();
1148 if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1149 print_results (&add_files_state);
1152 fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1153 notmuch_status_to_string (ret));
1155 notmuch_database_destroy (notmuch);
1157 if (!no_hooks && !ret && !interrupted)
1158 ret = notmuch_run_hook (db_path, "post-new");
1160 if (ret || interrupted)
1161 return EXIT_FAILURE;
1163 if (add_files_state.vanished_files)
1164 return NOTMUCH_EXIT_TEMPFAIL;
1166 return EXIT_SUCCESS;