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