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