]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
notmuch new: Eliminate the check on the mtime of regular files before adding.
[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 ino_cmp(const struct dirent **a, const struct dirent **b)
91 {
92     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
93 }
94
95 /* Test if the directory looks like a Maildir directory.
96  *
97  * Search through the array of directory entries to see if we can find all
98  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
99  *
100  * Return 1 if the directory looks like a Maildir and 0 otherwise.
101  */
102 static int
103 is_maildir (struct dirent **entries, int count)
104 {
105     int i, found = 0;
106
107     for (i = 0; i < count; i++) {
108         if (entries[i]->d_type != DT_DIR) continue;
109         if (strcmp(entries[i]->d_name, "new") == 0 ||
110             strcmp(entries[i]->d_name, "cur") == 0 ||
111             strcmp(entries[i]->d_name, "tmp") == 0)
112         {
113             found++;
114             if (found == 3)
115                 return 1;
116         }
117     }
118
119     return 0;
120 }
121
122 /* Examine 'path' recursively as follows:
123  *
124  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
125  *
126  *   o Ask the database for its timestamp of 'path' (db_mtime)
127  *
128  *   o If 'fs_mtime' > 'db_mtime'
129  *
130  *       o For each regular file directly within 'path', call
131  *         add_message to add the file to the database.
132  *
133  *   o For each sub-directory of path, recursively call into this
134  *     same function.
135  *
136  *   o Tell the database to update its time of 'path' to 'fs_mtime'
137  *
138  * The 'struct stat *st' must point to a structure that has already
139  * been initialized for 'path' by calling stat().
140  */
141 static notmuch_status_t
142 add_files_recursive (notmuch_database_t *notmuch,
143                      const char *path,
144                      struct stat *st,
145                      add_files_state_t *state)
146 {
147     DIR *dir = NULL;
148     struct dirent *entry = NULL;
149     char *next = NULL;
150     time_t fs_mtime, db_mtime;
151     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
152     notmuch_message_t *message = NULL;
153     struct dirent **namelist = NULL;
154     int num_entries;
155     notmuch_directory_t *directory;
156
157     fs_mtime = st->st_mtime;
158
159     directory = notmuch_database_get_directory (notmuch, path);
160     db_mtime = notmuch_directory_get_mtime (directory);
161
162     num_entries = scandir (path, &namelist, 0, ino_cmp);
163
164     if (num_entries == -1) {
165         fprintf (stderr, "Error opening directory %s: %s\n",
166                  path, strerror (errno));
167         ret = NOTMUCH_STATUS_FILE_ERROR;
168         goto DONE;
169     }
170
171     int i=0;
172
173     while (!interrupted) {
174         if (i == num_entries)
175             break;
176
177         entry= namelist[i++];
178
179         /* If this directory hasn't been modified since the last
180          * add_files, then we only need to look further for
181          * sub-directories. */
182         if (fs_mtime <= db_mtime && entry->d_type == DT_REG)
183             continue;
184
185         /* Ignore special directories to avoid infinite recursion.
186          * Also ignore the .notmuch directory.
187          */
188         /* XXX: Eventually we'll want more sophistication to let the
189          * user specify files to be ignored. */
190         if (strcmp (entry->d_name, ".") == 0 ||
191             strcmp (entry->d_name, "..") == 0 ||
192             (entry->d_type == DT_DIR &&
193              (strcmp (entry->d_name, "tmp") == 0) &&
194              is_maildir (namelist, num_entries)) ||
195             strcmp (entry->d_name, ".notmuch") ==0)
196         {
197             continue;
198         }
199
200         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
201
202         if (stat (next, st)) {
203             int err = errno;
204
205             switch (err) {
206             case ENOENT:
207                 /* The file was removed between scandir and now... */
208             case EPERM:
209             case EACCES:
210                 /* We can't read this file so don't add it to the cache. */
211                 continue;
212             }
213
214             fprintf (stderr, "Error reading %s: %s\n",
215                      next, strerror (errno));
216             ret = NOTMUCH_STATUS_FILE_ERROR;
217             goto DONE;
218         }
219
220         if (S_ISREG (st->st_mode)) {
221             state->processed_files++;
222
223             if (state->verbose) {
224                 if (state->output_is_a_tty)
225                     printf("\r\033[K");
226
227                 printf ("%i/%i: %s",
228                         state->processed_files,
229                         state->total_files,
230                         next);
231
232                 putchar((state->output_is_a_tty) ? '\r' : '\n');
233                 fflush (stdout);
234             }
235
236             status = notmuch_database_add_message (notmuch, next, &message);
237             switch (status) {
238             /* success */
239             case NOTMUCH_STATUS_SUCCESS:
240                 state->added_messages++;
241                 tag_inbox_and_unread (message);
242                 break;
243             /* Non-fatal issues (go on to next file) */
244             case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
245                 /* Stay silent on this one. */
246                 break;
247             case NOTMUCH_STATUS_FILE_NOT_EMAIL:
248                 fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
249                          next);
250                 break;
251             /* Fatal issues. Don't process anymore. */
252             case NOTMUCH_STATUS_READONLY_DATABASE:
253             case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
254             case NOTMUCH_STATUS_OUT_OF_MEMORY:
255                 fprintf (stderr, "Error: %s. Halting processing.\n",
256                          notmuch_status_to_string (status));
257                 ret = status;
258                 goto DONE;
259             default:
260             case NOTMUCH_STATUS_FILE_ERROR:
261             case NOTMUCH_STATUS_NULL_POINTER:
262             case NOTMUCH_STATUS_TAG_TOO_LONG:
263             case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
264             case NOTMUCH_STATUS_LAST_STATUS:
265                 INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
266                 goto DONE;
267             }
268
269             if (message) {
270                 notmuch_message_destroy (message);
271                 message = NULL;
272             }
273
274             if (do_add_files_print_progress) {
275                 do_add_files_print_progress = 0;
276                 add_files_print_progress (state);
277             }
278         } else if (S_ISDIR (st->st_mode)) {
279             status = add_files_recursive (notmuch, next, st, state);
280             if (status && ret == NOTMUCH_STATUS_SUCCESS)
281                 ret = status;
282         }
283
284         talloc_free (next);
285         next = NULL;
286     }
287
288     if (! interrupted) {
289         status = notmuch_directory_set_mtime (directory, fs_mtime);
290         if (status && ret == NOTMUCH_STATUS_SUCCESS)
291             ret = status;
292     }
293
294   DONE:
295     if (next)
296         talloc_free (next);
297     if (entry)
298         free (entry);
299     if (dir)
300         closedir (dir);
301     if (namelist)
302         free (namelist);
303
304     return ret;
305 }
306
307 /* This is the top-level entry point for add_files. It does a couple
308  * of error checks, sets up the progress-printing timer and then calls
309  * into the recursive function. */
310 static notmuch_status_t
311 add_files (notmuch_database_t *notmuch,
312            const char *path,
313            add_files_state_t *state)
314 {
315     struct stat st;
316     notmuch_status_t status;
317     struct sigaction action;
318     struct itimerval timerval;
319     notmuch_bool_t timer_is_active = FALSE;
320
321     if (stat (path, &st)) {
322         fprintf (stderr, "Error reading directory %s: %s\n",
323                  path, strerror (errno));
324         return NOTMUCH_STATUS_FILE_ERROR;
325     }
326
327     if (! S_ISDIR (st.st_mode)) {
328         fprintf (stderr, "Error: %s is not a directory.\n", path);
329         return NOTMUCH_STATUS_FILE_ERROR;
330     }
331
332     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
333         /* Setup our handler for SIGALRM */
334         memset (&action, 0, sizeof (struct sigaction));
335         action.sa_handler = handle_sigalrm;
336         sigemptyset (&action.sa_mask);
337         action.sa_flags = SA_RESTART;
338         sigaction (SIGALRM, &action, NULL);
339
340         /* Then start a timer to send SIGALRM once per second. */
341         timerval.it_interval.tv_sec = 1;
342         timerval.it_interval.tv_usec = 0;
343         timerval.it_value.tv_sec = 1;
344         timerval.it_value.tv_usec = 0;
345         setitimer (ITIMER_REAL, &timerval, NULL);
346
347         timer_is_active = TRUE;
348     }
349
350     status = add_files_recursive (notmuch, path, &st, state);
351
352     if (timer_is_active) {
353         /* Now stop the timer. */
354         timerval.it_interval.tv_sec = 0;
355         timerval.it_interval.tv_usec = 0;
356         timerval.it_value.tv_sec = 0;
357         timerval.it_value.tv_usec = 0;
358         setitimer (ITIMER_REAL, &timerval, NULL);
359
360         /* And disable the signal handler. */
361         action.sa_handler = SIG_IGN;
362         sigaction (SIGALRM, &action, NULL);
363     }
364
365     return status;
366 }
367
368 /* XXX: This should be merged with the add_files function since it
369  * shares a lot of logic with it. */
370 /* Recursively count all regular files in path and all sub-directories
371  * of path.  The result is added to *count (which should be
372  * initialized to zero by the top-level caller before calling
373  * count_files). */
374 static void
375 count_files (const char *path, int *count)
376 {
377     struct dirent *entry = NULL;
378     char *next;
379     struct stat st;
380     struct dirent **namelist = NULL;
381     int n_entries = scandir (path, &namelist, 0, ino_cmp);
382     int i = 0;
383
384     if (n_entries == -1) {
385         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
386                  path, strerror (errno));
387         goto DONE;
388     }
389
390     while (!interrupted) {
391         if (i == n_entries)
392             break;
393
394         entry= namelist[i++];
395
396         /* Ignore special directories to avoid infinite recursion.
397          * Also ignore the .notmuch directory.
398          */
399         /* XXX: Eventually we'll want more sophistication to let the
400          * user specify files to be ignored. */
401         if (strcmp (entry->d_name, ".") == 0 ||
402             strcmp (entry->d_name, "..") == 0 ||
403             strcmp (entry->d_name, ".notmuch") == 0)
404         {
405             continue;
406         }
407
408         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
409             next = NULL;
410             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
411                      path, entry->d_name);
412             continue;
413         }
414
415         stat (next, &st);
416
417         if (S_ISREG (st.st_mode)) {
418             *count = *count + 1;
419             if (*count % 1000 == 0) {
420                 printf ("Found %d files so far.\r", *count);
421                 fflush (stdout);
422             }
423         } else if (S_ISDIR (st.st_mode)) {
424             count_files (next, count);
425         }
426
427         free (next);
428     }
429
430   DONE:
431     if (entry)
432         free (entry);
433     if (namelist)
434         free (namelist);
435 }
436
437 int
438 notmuch_new_command (void *ctx, int argc, char *argv[])
439 {
440     notmuch_config_t *config;
441     notmuch_database_t *notmuch;
442     add_files_state_t add_files_state;
443     double elapsed;
444     struct timeval tv_now;
445     int ret = 0;
446     struct stat st;
447     const char *db_path;
448     char *dot_notmuch_path;
449     struct sigaction action;
450     int i;
451
452     add_files_state.verbose = 0;
453     add_files_state.output_is_a_tty = isatty (fileno (stdout));
454
455     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
456         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
457             add_files_state.verbose = 1;
458         } else {
459             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
460             return 1;
461         }
462     }
463
464     /* Setup our handler for SIGINT */
465     memset (&action, 0, sizeof (struct sigaction));
466     action.sa_handler = handle_sigint;
467     sigemptyset (&action.sa_mask);
468     action.sa_flags = SA_RESTART;
469     sigaction (SIGINT, &action, NULL);
470
471     config = notmuch_config_open (ctx, NULL, NULL);
472     if (config == NULL)
473         return 1;
474
475     db_path = notmuch_config_get_database_path (config);
476
477     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
478
479     if (stat (dot_notmuch_path, &st)) {
480         int count;
481
482         count = 0;
483         count_files (db_path, &count);
484         if (interrupted)
485             return 1;
486
487         printf ("Found %d total files (that's not much mail).\n", count);
488         notmuch = notmuch_database_create (db_path);
489         add_files_state.total_files = count;
490     } else {
491         notmuch = notmuch_database_open (db_path,
492                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
493         add_files_state.total_files = 0;
494     }
495
496     if (notmuch == NULL)
497         return 1;
498
499     talloc_free (dot_notmuch_path);
500     dot_notmuch_path = NULL;
501
502     add_files_state.processed_files = 0;
503     add_files_state.added_messages = 0;
504     gettimeofday (&add_files_state.tv_start, NULL);
505
506     ret = add_files (notmuch, db_path, &add_files_state);
507
508     gettimeofday (&tv_now, NULL);
509     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
510                                     tv_now);
511     if (add_files_state.processed_files) {
512         printf ("Processed %d %s in ", add_files_state.processed_files,
513                 add_files_state.processed_files == 1 ?
514                 "file" : "total files");
515         notmuch_time_print_formatted_seconds (elapsed);
516         if (elapsed > 1) {
517             printf (" (%d files/sec.).                 \n",
518                     (int) (add_files_state.processed_files / elapsed));
519         } else {
520             printf (".                    \n");
521         }
522     }
523     if (add_files_state.added_messages) {
524         printf ("Added %d new %s to the database.\n",
525                 add_files_state.added_messages,
526                 add_files_state.added_messages == 1 ?
527                 "message" : "messages");
528     } else {
529         printf ("No new mail.\n");
530     }
531
532     if (ret) {
533         printf ("\nNote: At least one error was encountered: %s\n",
534                 notmuch_status_to_string (ret));
535     }
536
537     notmuch_database_close (notmuch);
538
539     return ret || interrupted;
540 }