]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
notmuch.el: Add documentation for notmuch-search-show-thread.
[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             int err = errno;
201
202             switch (err) {
203             case ENOENT:
204                 /* The file was removed between scandir and now... */
205             case EPERM:
206             case EACCES:
207                 /* We can't read this file so don't add it to the cache. */
208                 continue;
209             }
210
211             fprintf (stderr, "Error reading %s: %s\n",
212                      next, strerror (errno));
213             ret = NOTMUCH_STATUS_FILE_ERROR;
214             goto DONE;
215         }
216
217         if (S_ISREG (st->st_mode)) {
218             /* If the file hasn't been modified since the last
219              * add_files, then we need not look at it. */
220             if (path_dbtime == 0 || st->st_mtime > path_dbtime) {
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             }
279         } else if (S_ISDIR (st->st_mode)) {
280             status = add_files_recursive (notmuch, next, st, state);
281             if (status && ret == NOTMUCH_STATUS_SUCCESS)
282                 ret = status;
283         }
284
285         talloc_free (next);
286         next = NULL;
287     }
288
289     status = notmuch_database_set_timestamp (notmuch, path, path_mtime);
290     if (status && ret == NOTMUCH_STATUS_SUCCESS)
291         ret = status;
292
293   DONE:
294     if (next)
295         talloc_free (next);
296     if (entry)
297         free (entry);
298     if (dir)
299         closedir (dir);
300     if (namelist)
301         free (namelist);
302
303     return ret;
304 }
305
306 /* This is the top-level entry point for add_files. It does a couple
307  * of error checks, sets up the progress-printing timer and then calls
308  * into the recursive function. */
309 notmuch_status_t
310 add_files (notmuch_database_t *notmuch,
311            const char *path,
312            add_files_state_t *state)
313 {
314     struct stat st;
315     notmuch_status_t status;
316     struct sigaction action;
317     struct itimerval timerval;
318     notmuch_bool_t timer_is_active = FALSE;
319
320     if (stat (path, &st)) {
321         fprintf (stderr, "Error reading directory %s: %s\n",
322                  path, strerror (errno));
323         return NOTMUCH_STATUS_FILE_ERROR;
324     }
325
326     if (! S_ISDIR (st.st_mode)) {
327         fprintf (stderr, "Error: %s is not a directory.\n", path);
328         return NOTMUCH_STATUS_FILE_ERROR;
329     }
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, &st, 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 **namelist = NULL;
380     int n_entries = scandir (path, &namelist, 0, ino_cmp);
381     int i = 0;
382
383     if (n_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 == n_entries)
391             break;
392
393         entry= namelist[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 (namelist)
433         free (namelist);
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.     \n", count);
487         notmuch = notmuch_database_create (db_path);
488         add_files_state.ignore_read_only_directories = FALSE;
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.ignore_read_only_directories = TRUE;
494         add_files_state.total_files = 0;
495     }
496
497     if (notmuch == NULL)
498         return 1;
499
500     talloc_free (dot_notmuch_path);
501     dot_notmuch_path = NULL;
502
503     add_files_state.saw_read_only_directory = FALSE;
504     add_files_state.processed_files = 0;
505     add_files_state.added_messages = 0;
506     gettimeofday (&add_files_state.tv_start, NULL);
507
508     ret = add_files (notmuch, db_path, &add_files_state);
509
510     gettimeofday (&tv_now, NULL);
511     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
512                                     tv_now);
513     if (add_files_state.processed_files) {
514         printf ("Processed %d %s in ", add_files_state.processed_files,
515                 add_files_state.processed_files == 1 ?
516                 "file" : "total files");
517         notmuch_time_print_formatted_seconds (elapsed);
518         if (elapsed > 1) {
519             printf (" (%d files/sec.).                 \n",
520                     (int) (add_files_state.processed_files / elapsed));
521         } else {
522             printf (".                    \n");
523         }
524     }
525     if (add_files_state.added_messages) {
526         printf ("Added %d new %s to the database (not much, really).\n",
527                 add_files_state.added_messages,
528                 add_files_state.added_messages == 1 ?
529                 "message" : "messages");
530     } else {
531         printf ("No new mail---and that's not much.\n");
532     }
533
534     if (elapsed > 1 && ! add_files_state.saw_read_only_directory) {
535         printf ("\nTip: If you have any sub-directories that are archives (that is,\n"
536                 "they will never receive new mail), marking these directories as\n"
537                 "read-only (chmod u-w /path/to/dir) will make \"notmuch new\"\n"
538                 "much more efficient (it won't even look in those directories).\n");
539     }
540
541     if (ret) {
542         printf ("\nNote: At least one error was encountered: %s\n",
543                 notmuch_status_to_string (ret));
544     }
545
546     notmuch_database_close (notmuch);
547
548     return ret || interrupted;
549 }