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