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