]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
notmuch new: Detect deleted (renamed) files and directories.
[notmuch] / notmuch-new.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
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.
9  *
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.
14  *
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/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22
23 #include <unistd.h>
24
25 typedef struct {
26     int output_is_a_tty;
27     int verbose;
28
29     int total_files;
30     int processed_files;
31     int added_messages;
32     struct timeval tv_start;
33 } add_files_state_t;
34
35 static volatile sig_atomic_t do_add_files_print_progress = 0;
36
37 static void
38 handle_sigalrm (unused (int signal))
39 {
40     do_add_files_print_progress = 1;
41 }
42
43 static volatile sig_atomic_t interrupted;
44
45 static void
46 handle_sigint (unused (int sig))
47 {
48     ssize_t ignored;
49     static char msg[] = "Stopping...         \n";
50
51     ignored = write(2, msg, sizeof(msg)-1);
52     interrupted = 1;
53 }
54
55 static void
56 tag_inbox_and_unread (notmuch_message_t *message)
57 {
58     notmuch_message_add_tag (message, "inbox");
59     notmuch_message_add_tag (message, "unread");
60 }
61
62 static void
63 add_files_print_progress (add_files_state_t *state)
64 {
65     struct timeval tv_now;
66     double elapsed_overall, rate_overall;
67
68     gettimeofday (&tv_now, NULL);
69
70     elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
71     rate_overall = (state->processed_files) / elapsed_overall;
72
73     printf ("Processed %d", state->processed_files);
74
75     if (state->total_files) {
76         double time_remaining;
77
78         time_remaining = ((state->total_files - state->processed_files) /
79                           rate_overall);
80         printf (" of %d files (", state->total_files);
81         notmuch_time_print_formatted_seconds (time_remaining);
82         printf (" remaining).      \r");
83     } else {
84         printf (" files (%d files/sec.)    \r", (int) rate_overall);
85     }
86
87     fflush (stdout);
88 }
89
90 static int
91 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
92 {
93     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
94 }
95
96 static int
97 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
98 {
99     return strcmp ((*a)->d_name, (*b)->d_name);
100 }
101
102 /* Test if the directory looks like a Maildir directory.
103  *
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".
106  *
107  * Return 1 if the directory looks like a Maildir and 0 otherwise.
108  */
109 static int
110 _entries_resemble_maildir (struct dirent **entries, int count)
111 {
112     int i, found = 0;
113
114     for (i = 0; i < count; i++) {
115         if (entries[i]->d_type != DT_DIR)
116             continue;
117
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)
121         {
122             found++;
123             if (found == 3)
124                 return 1;
125         }
126     }
127
128     return 0;
129 }
130
131 /* Examine 'path' recursively as follows:
132  *
133  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
134  *   o Ask the database for its timestamp of 'path' (db_mtime)
135  *
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)
140  *
141  *   o Pass 1: For each directory in fs_entries, recursively call into
142  *     this same function.
143  *
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:
147  *
148  *         1. Regular file in fs_entries and not in db_files
149  *            This is a new file to add_message into the database.
150  *
151  *         2. Filename in db_files not in fs_entries.
152  *            This is a file that has been removed from the mail store.
153  *
154  *         3. Directory in db_subdirs not in fs_entries
155  *            This is a directory that has been removed from the mail store.
156  *
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).
163  *
164  *   o Tell the database to update its time of 'path' to 'fs_mtime'
165  */
166 static notmuch_status_t
167 add_files_recursive (notmuch_database_t *notmuch,
168                      const char *path,
169                      add_files_state_t *state)
170 {
171     DIR *dir = NULL;
172     struct dirent *entry = NULL;
173     char *next = 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;
182     struct stat st;
183     notmuch_bool_t is_maildir;
184
185     if (stat (path, &st)) {
186         fprintf (stderr, "Error reading directory %s: %s\n",
187                  path, strerror (errno));
188         return NOTMUCH_STATUS_FILE_ERROR;
189     }
190
191     if (! S_ISDIR (st.st_mode)) {
192         fprintf (stderr, "Error: %s is not a directory.\n", path);
193         return NOTMUCH_STATUS_FILE_ERROR;
194     }
195
196     fs_mtime = st.st_mtime;
197
198     directory = notmuch_database_get_directory (notmuch, path);
199     db_mtime = notmuch_directory_get_mtime (directory);
200
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,
205                               db_mtime ?
206                               dirent_sort_strcmp_name : dirent_sort_inode);
207
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;
212         goto DONE;
213     }
214
215     /* Pass 1: Recurse into all sub-directories. */
216     is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
217
218     for (i = 0; i < num_fs_entries; i++) {
219         if (interrupted)
220             break;
221
222         entry = fs_entries[i];
223
224         if (entry->d_type != DT_DIR)
225             continue;
226
227         /* Ignore special directories to avoid infinite recursion.
228          * Also ignore the .notmuch directory and any "tmp" directory
229          * that appears within a maildir.
230          */
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)
237         {
238             continue;
239         }
240
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)
244             ret = status;
245         talloc_free (next);
246         next = NULL;
247     }
248
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)
252         goto DONE;
253
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);
257
258     for (i = 0; i < num_fs_entries; i++)
259     {
260         if (interrupted)
261             break;
262
263         entry = fs_entries[i];
264
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)
269         {
270             printf ("Detected deleted file %s/%s\n", path,
271                     notmuch_filenames_get (db_files));
272
273             notmuch_filenames_advance (db_files);
274         }
275
276         while (notmuch_filenames_has_more (db_subdirs) &&
277                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
278         {
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));
282
283             notmuch_filenames_advance (db_subdirs);
284         }
285
286         if (entry->d_type != DT_REG)
287             continue;
288
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)
292         {
293             notmuch_filenames_advance (db_files);
294             continue;
295         }
296
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);
300
301         state->processed_files++;
302
303         if (state->verbose) {
304             if (state->output_is_a_tty)
305                 printf("\r\033[K");
306
307             printf ("%i/%i: %s",
308                     state->processed_files,
309                     state->total_files,
310                     next);
311
312             putchar((state->output_is_a_tty) ? '\r' : '\n');
313             fflush (stdout);
314         }
315
316         status = notmuch_database_add_message (notmuch, next, &message);
317         switch (status) {
318         /* success */
319         case NOTMUCH_STATUS_SUCCESS:
320             state->added_messages++;
321             tag_inbox_and_unread (message);
322             break;
323         /* Non-fatal issues (go on to next file) */
324         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
325             /* Stay silent on this one. */
326             break;
327         case NOTMUCH_STATUS_FILE_NOT_EMAIL:
328             fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
329                      next);
330             break;
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));
337             ret = status;
338             goto DONE;
339         default:
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);
346             goto DONE;
347         }
348
349         if (message) {
350             notmuch_message_destroy (message);
351             message = NULL;
352         }
353
354         if (do_add_files_print_progress) {
355             do_add_files_print_progress = 0;
356             add_files_print_progress (state);
357         }
358
359         talloc_free (next);
360         next = NULL;
361     }
362
363     if (! interrupted) {
364         status = notmuch_directory_set_mtime (directory, fs_mtime);
365         if (status && ret == NOTMUCH_STATUS_SUCCESS)
366             ret = status;
367     }
368
369   DONE:
370     if (next)
371         talloc_free (next);
372     if (entry)
373         free (entry);
374     if (dir)
375         closedir (dir);
376     if (fs_entries)
377         free (fs_entries);
378     if (db_subdirs)
379         notmuch_filenames_destroy (db_subdirs);
380     if (db_files)
381         notmuch_filenames_destroy (db_files);
382     if (directory)
383         notmuch_directory_destroy (directory);
384
385     return ret;
386 }
387
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,
393            const char *path,
394            add_files_state_t *state)
395 {
396     notmuch_status_t status;
397     struct sigaction action;
398     struct itimerval timerval;
399     notmuch_bool_t timer_is_active = FALSE;
400
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);
408
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);
415
416         timer_is_active = TRUE;
417     }
418
419     status = add_files_recursive (notmuch, path, state);
420
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);
428
429         /* And disable the signal handler. */
430         action.sa_handler = SIG_IGN;
431         sigaction (SIGALRM, &action, NULL);
432     }
433
434     return status;
435 }
436
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
442  * count_files). */
443 static void
444 count_files (const char *path, int *count)
445 {
446     struct dirent *entry = NULL;
447     char *next;
448     struct stat st;
449     struct dirent **fs_entries = NULL;
450     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
451     int i = 0;
452
453     if (num_fs_entries == -1) {
454         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
455                  path, strerror (errno));
456         goto DONE;
457     }
458
459     while (!interrupted) {
460         if (i == num_fs_entries)
461             break;
462
463         entry = fs_entries[i++];
464
465         /* Ignore special directories to avoid infinite recursion.
466          * Also ignore the .notmuch directory.
467          */
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)
473         {
474             continue;
475         }
476
477         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
478             next = NULL;
479             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
480                      path, entry->d_name);
481             continue;
482         }
483
484         stat (next, &st);
485
486         if (S_ISREG (st.st_mode)) {
487             *count = *count + 1;
488             if (*count % 1000 == 0) {
489                 printf ("Found %d files so far.\r", *count);
490                 fflush (stdout);
491             }
492         } else if (S_ISDIR (st.st_mode)) {
493             count_files (next, count);
494         }
495
496         free (next);
497     }
498
499   DONE:
500     if (entry)
501         free (entry);
502     if (fs_entries)
503         free (fs_entries);
504 }
505
506 int
507 notmuch_new_command (void *ctx, int argc, char *argv[])
508 {
509     notmuch_config_t *config;
510     notmuch_database_t *notmuch;
511     add_files_state_t add_files_state;
512     double elapsed;
513     struct timeval tv_now;
514     int ret = 0;
515     struct stat st;
516     const char *db_path;
517     char *dot_notmuch_path;
518     struct sigaction action;
519     int i;
520
521     add_files_state.verbose = 0;
522     add_files_state.output_is_a_tty = isatty (fileno (stdout));
523
524     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
525         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
526             add_files_state.verbose = 1;
527         } else {
528             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
529             return 1;
530         }
531     }
532
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);
539
540     config = notmuch_config_open (ctx, NULL, NULL);
541     if (config == NULL)
542         return 1;
543
544     db_path = notmuch_config_get_database_path (config);
545
546     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
547
548     if (stat (dot_notmuch_path, &st)) {
549         int count;
550
551         count = 0;
552         count_files (db_path, &count);
553         if (interrupted)
554             return 1;
555
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;
559     } else {
560         notmuch = notmuch_database_open (db_path,
561                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
562         add_files_state.total_files = 0;
563     }
564
565     if (notmuch == NULL)
566         return 1;
567
568     talloc_free (dot_notmuch_path);
569     dot_notmuch_path = NULL;
570
571     add_files_state.processed_files = 0;
572     add_files_state.added_messages = 0;
573     gettimeofday (&add_files_state.tv_start, NULL);
574
575     ret = add_files (notmuch, db_path, &add_files_state);
576
577     gettimeofday (&tv_now, NULL);
578     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
579                                     tv_now);
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);
585         if (elapsed > 1) {
586             printf (" (%d files/sec.).                 \n",
587                     (int) (add_files_state.processed_files / elapsed));
588         } else {
589             printf (".                    \n");
590         }
591     }
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");
597     } else {
598         printf ("No new mail.\n");
599     }
600
601     if (ret) {
602         printf ("\nNote: At least one error was encountered: %s\n",
603                 notmuch_status_to_string (ret));
604     }
605
606     notmuch_database_close (notmuch);
607
608     return ret || interrupted;
609 }