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 http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "notmuch-client.h"
32 struct timeval tv_start;
35 static volatile sig_atomic_t do_add_files_print_progress = 0;
38 handle_sigalrm (unused (int signal))
40 do_add_files_print_progress = 1;
43 static volatile sig_atomic_t interrupted;
46 handle_sigint (unused (int sig))
49 static char msg[] = "Stopping... \n";
51 ignored = write(2, msg, sizeof(msg)-1);
56 tag_inbox_and_unread (notmuch_message_t *message)
58 notmuch_message_add_tag (message, "inbox");
59 notmuch_message_add_tag (message, "unread");
63 add_files_print_progress (add_files_state_t *state)
65 struct timeval tv_now;
66 double elapsed_overall, rate_overall;
68 gettimeofday (&tv_now, NULL);
70 elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
71 rate_overall = (state->processed_files) / elapsed_overall;
73 printf ("Processed %d", state->processed_files);
75 if (state->total_files) {
76 double time_remaining;
78 time_remaining = ((state->total_files - state->processed_files) /
80 printf (" of %d files (", state->total_files);
81 notmuch_time_print_formatted_seconds (time_remaining);
82 printf (" remaining). \r");
84 printf (" files (%d files/sec.) \r", (int) rate_overall);
91 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
93 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
97 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
99 return strcmp ((*a)->d_name, (*b)->d_name);
102 /* Test if the directory looks like a Maildir directory.
104 * Search through the array of directory entries to see if we can find all
105 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
107 * Return 1 if the directory looks like a Maildir and 0 otherwise.
110 _entries_resemble_maildir (struct dirent **entries, int count)
114 for (i = 0; i < count; i++) {
115 if (entries[i]->d_type != DT_DIR)
118 if (strcmp(entries[i]->d_name, "new") == 0 ||
119 strcmp(entries[i]->d_name, "cur") == 0 ||
120 strcmp(entries[i]->d_name, "tmp") == 0)
131 /* Examine 'path' recursively as follows:
133 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
134 * o Ask the database for its timestamp of 'path' (db_mtime)
136 * o Ask the filesystem for files and directories within 'path'
137 * (via scandir and stored in fs_entries)
138 * o Ask the database for files and directories within 'path'
139 * (db_files and db_subdirs)
141 * o Pass 1: For each directory in fs_entries, recursively call into
142 * this same function.
144 * o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
145 * simultaneously with db_files and db_subdirs. Look for one of
146 * three interesting cases:
148 * 1. Regular file in fs_entries and not in db_files
149 * This is a new file to add_message into the database.
151 * 2. Filename in db_files not in fs_entries.
152 * This is a file that has been removed from the mail store.
154 * 3. Directory in db_subdirs not in fs_entries
155 * This is a directory that has been removed from the mail store.
157 * Note that the addition of a directory is not interesting here,
158 * since that will have been taken care of in pass 1. Also, we
159 * don't immediately act on file/directory removal since we must
160 * ensure that in the case of a rename that the new filename is
161 * added before the old filename is removed, (so that no
162 * information is lost from the database).
164 * o Tell the database to update its time of 'path' to 'fs_mtime'
166 static notmuch_status_t
167 add_files_recursive (notmuch_database_t *notmuch,
169 add_files_state_t *state)
172 struct dirent *entry = NULL;
174 time_t fs_mtime, db_mtime;
175 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
176 notmuch_message_t *message = NULL;
177 struct dirent **fs_entries = NULL;
178 int i, num_fs_entries;
179 notmuch_directory_t *directory;
180 notmuch_filenames_t *db_files = NULL;
181 notmuch_filenames_t *db_subdirs = NULL;
183 notmuch_bool_t is_maildir;
185 if (stat (path, &st)) {
186 fprintf (stderr, "Error reading directory %s: %s\n",
187 path, strerror (errno));
188 return NOTMUCH_STATUS_FILE_ERROR;
191 if (! S_ISDIR (st.st_mode)) {
192 fprintf (stderr, "Error: %s is not a directory.\n", path);
193 return NOTMUCH_STATUS_FILE_ERROR;
196 fs_mtime = st.st_mtime;
198 directory = notmuch_database_get_directory (notmuch, path);
199 db_mtime = notmuch_directory_get_mtime (directory);
201 /* If the database knows about this directory, then we sort based
202 * on strcmp to match the database sorting. Otherwise, we can do
203 * inode-based sorting for faster filesystem operation. */
204 num_fs_entries = scandir (path, &fs_entries, 0,
206 dirent_sort_strcmp_name : dirent_sort_inode);
208 if (num_fs_entries == -1) {
209 fprintf (stderr, "Error opening directory %s: %s\n",
210 path, strerror (errno));
211 ret = NOTMUCH_STATUS_FILE_ERROR;
215 /* Pass 1: Recurse into all sub-directories. */
216 is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
218 for (i = 0; i < num_fs_entries; i++) {
222 entry = fs_entries[i];
224 if (entry->d_type != DT_DIR)
227 /* Ignore special directories to avoid infinite recursion.
228 * Also ignore the .notmuch directory and any "tmp" directory
229 * that appears within a maildir.
231 /* XXX: Eventually we'll want more sophistication to let the
232 * user specify files to be ignored. */
233 if (strcmp (entry->d_name, ".") == 0 ||
234 strcmp (entry->d_name, "..") == 0 ||
235 (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
236 strcmp (entry->d_name, ".notmuch") ==0)
241 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
242 status = add_files_recursive (notmuch, next, state);
243 if (status && ret == NOTMUCH_STATUS_SUCCESS)
249 /* If this directory hasn't been modified since the last
250 * "notmuch new", then we can skip the second pass entirely. */
251 if (fs_mtime <= db_mtime)
254 /* Pass 2: Scan for new files, removed files, and removed directories. */
255 db_files = notmuch_directory_get_child_files (directory);
256 db_subdirs = notmuch_directory_get_child_directories (directory);
258 for (i = 0; i < num_fs_entries; i++)
263 entry = fs_entries[i];
265 /* Check if we've walked past any names in db_files or
266 * db_subdirs. If so, these have been deleted. */
267 while (notmuch_filenames_has_more (db_files) &&
268 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
270 printf ("Detected deleted file %s/%s\n", path,
271 notmuch_filenames_get (db_files));
273 notmuch_filenames_advance (db_files);
276 while (notmuch_filenames_has_more (db_subdirs) &&
277 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
279 if (strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) < 0)
280 printf ("Detected deleted directory %s/%s", path,
281 notmuch_filenames_get (db_subdirs));
283 notmuch_filenames_advance (db_subdirs);
286 if (entry->d_type != DT_REG)
289 /* Don't add a file that we've added before. */
290 if (notmuch_filenames_has_more (db_files) &&
291 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
293 notmuch_filenames_advance (db_files);
297 /* We're not looking at a regular file that doesn't yet exist
298 * in the database, so add it. */
299 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
301 state->processed_files++;
303 if (state->verbose) {
304 if (state->output_is_a_tty)
308 state->processed_files,
312 putchar((state->output_is_a_tty) ? '\r' : '\n');
316 status = notmuch_database_add_message (notmuch, next, &message);
319 case NOTMUCH_STATUS_SUCCESS:
320 state->added_messages++;
321 tag_inbox_and_unread (message);
323 /* Non-fatal issues (go on to next file) */
324 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
325 /* Stay silent on this one. */
327 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
328 fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
331 /* Fatal issues. Don't process anymore. */
332 case NOTMUCH_STATUS_READONLY_DATABASE:
333 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
334 case NOTMUCH_STATUS_OUT_OF_MEMORY:
335 fprintf (stderr, "Error: %s. Halting processing.\n",
336 notmuch_status_to_string (status));
340 case NOTMUCH_STATUS_FILE_ERROR:
341 case NOTMUCH_STATUS_NULL_POINTER:
342 case NOTMUCH_STATUS_TAG_TOO_LONG:
343 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
344 case NOTMUCH_STATUS_LAST_STATUS:
345 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
350 notmuch_message_destroy (message);
354 if (do_add_files_print_progress) {
355 do_add_files_print_progress = 0;
356 add_files_print_progress (state);
364 status = notmuch_directory_set_mtime (directory, fs_mtime);
365 if (status && ret == NOTMUCH_STATUS_SUCCESS)
379 notmuch_filenames_destroy (db_subdirs);
381 notmuch_filenames_destroy (db_files);
383 notmuch_directory_destroy (directory);
388 /* This is the top-level entry point for add_files. It does a couple
389 * of error checks, sets up the progress-printing timer and then calls
390 * into the recursive function. */
391 static notmuch_status_t
392 add_files (notmuch_database_t *notmuch,
394 add_files_state_t *state)
396 notmuch_status_t status;
397 struct sigaction action;
398 struct itimerval timerval;
399 notmuch_bool_t timer_is_active = FALSE;
401 if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
402 /* Setup our handler for SIGALRM */
403 memset (&action, 0, sizeof (struct sigaction));
404 action.sa_handler = handle_sigalrm;
405 sigemptyset (&action.sa_mask);
406 action.sa_flags = SA_RESTART;
407 sigaction (SIGALRM, &action, NULL);
409 /* Then start a timer to send SIGALRM once per second. */
410 timerval.it_interval.tv_sec = 1;
411 timerval.it_interval.tv_usec = 0;
412 timerval.it_value.tv_sec = 1;
413 timerval.it_value.tv_usec = 0;
414 setitimer (ITIMER_REAL, &timerval, NULL);
416 timer_is_active = TRUE;
419 status = add_files_recursive (notmuch, path, state);
421 if (timer_is_active) {
422 /* Now stop the timer. */
423 timerval.it_interval.tv_sec = 0;
424 timerval.it_interval.tv_usec = 0;
425 timerval.it_value.tv_sec = 0;
426 timerval.it_value.tv_usec = 0;
427 setitimer (ITIMER_REAL, &timerval, NULL);
429 /* And disable the signal handler. */
430 action.sa_handler = SIG_IGN;
431 sigaction (SIGALRM, &action, NULL);
437 /* XXX: This should be merged with the add_files function since it
438 * shares a lot of logic with it. */
439 /* Recursively count all regular files in path and all sub-directories
440 * of path. The result is added to *count (which should be
441 * initialized to zero by the top-level caller before calling
444 count_files (const char *path, int *count)
446 struct dirent *entry = NULL;
449 struct dirent **fs_entries = NULL;
450 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
453 if (num_fs_entries == -1) {
454 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
455 path, strerror (errno));
459 while (!interrupted) {
460 if (i == num_fs_entries)
463 entry = fs_entries[i++];
465 /* Ignore special directories to avoid infinite recursion.
466 * Also ignore the .notmuch directory.
468 /* XXX: Eventually we'll want more sophistication to let the
469 * user specify files to be ignored. */
470 if (strcmp (entry->d_name, ".") == 0 ||
471 strcmp (entry->d_name, "..") == 0 ||
472 strcmp (entry->d_name, ".notmuch") == 0)
477 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
479 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
480 path, entry->d_name);
486 if (S_ISREG (st.st_mode)) {
488 if (*count % 1000 == 0) {
489 printf ("Found %d files so far.\r", *count);
492 } else if (S_ISDIR (st.st_mode)) {
493 count_files (next, count);
507 notmuch_new_command (void *ctx, int argc, char *argv[])
509 notmuch_config_t *config;
510 notmuch_database_t *notmuch;
511 add_files_state_t add_files_state;
513 struct timeval tv_now;
517 char *dot_notmuch_path;
518 struct sigaction action;
521 add_files_state.verbose = 0;
522 add_files_state.output_is_a_tty = isatty (fileno (stdout));
524 for (i = 0; i < argc && argv[i][0] == '-'; i++) {
525 if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
526 add_files_state.verbose = 1;
528 fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
533 /* Setup our handler for SIGINT */
534 memset (&action, 0, sizeof (struct sigaction));
535 action.sa_handler = handle_sigint;
536 sigemptyset (&action.sa_mask);
537 action.sa_flags = SA_RESTART;
538 sigaction (SIGINT, &action, NULL);
540 config = notmuch_config_open (ctx, NULL, NULL);
544 db_path = notmuch_config_get_database_path (config);
546 dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
548 if (stat (dot_notmuch_path, &st)) {
552 count_files (db_path, &count);
556 printf ("Found %d total files (that's not much mail).\n", count);
557 notmuch = notmuch_database_create (db_path);
558 add_files_state.total_files = count;
560 notmuch = notmuch_database_open (db_path,
561 NOTMUCH_DATABASE_MODE_READ_WRITE);
562 add_files_state.total_files = 0;
568 talloc_free (dot_notmuch_path);
569 dot_notmuch_path = NULL;
571 add_files_state.processed_files = 0;
572 add_files_state.added_messages = 0;
573 gettimeofday (&add_files_state.tv_start, NULL);
575 ret = add_files (notmuch, db_path, &add_files_state);
577 gettimeofday (&tv_now, NULL);
578 elapsed = notmuch_time_elapsed (add_files_state.tv_start,
580 if (add_files_state.processed_files) {
581 printf ("Processed %d %s in ", add_files_state.processed_files,
582 add_files_state.processed_files == 1 ?
583 "file" : "total files");
584 notmuch_time_print_formatted_seconds (elapsed);
586 printf (" (%d files/sec.). \n",
587 (int) (add_files_state.processed_files / elapsed));
592 if (add_files_state.added_messages) {
593 printf ("Added %d new %s to the database.\n",
594 add_files_state.added_messages,
595 add_files_state.added_messages == 1 ?
596 "message" : "messages");
598 printf ("No new mail.\n");
602 printf ("\nNote: At least one error was encountered: %s\n",
603 notmuch_status_to_string (ret));
606 notmuch_database_close (notmuch);
608 return ret || interrupted;