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