]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
notmuch-new: Remove dead add_files_callback code.
[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' (path_mtime)
125  *
126  *   o Ask the database for its timestamp of 'path' (path_dbtime)
127  *
128  *   o If 'path_mtime' > 'path_dbtime'
129  *
130  *       o For each regular file in 'path' with mtime newer than the
131  *         'path_dbtime' 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 'path_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 path_mtime, path_dbtime;
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     path_mtime = st->st_mtime;
159
160     directory = notmuch_database_get_directory (notmuch, path);
161     path_dbtime = 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 (path_mtime <= path_dbtime && 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 (path_dbtime == 0 || st->st_mtime > path_dbtime) {
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     status = notmuch_directory_set_mtime (directory, path_mtime);
294     if (status && ret == NOTMUCH_STATUS_SUCCESS)
295         ret = status;
296
297   DONE:
298     if (next)
299         talloc_free (next);
300     if (entry)
301         free (entry);
302     if (dir)
303         closedir (dir);
304     if (namelist)
305         free (namelist);
306
307     return ret;
308 }
309
310 /* This is the top-level entry point for add_files. It does a couple
311  * of error checks, sets up the progress-printing timer and then calls
312  * into the recursive function. */
313 static notmuch_status_t
314 add_files (notmuch_database_t *notmuch,
315            const char *path,
316            add_files_state_t *state)
317 {
318     struct stat st;
319     notmuch_status_t status;
320     struct sigaction action;
321     struct itimerval timerval;
322     notmuch_bool_t timer_is_active = FALSE;
323
324     if (stat (path, &st)) {
325         fprintf (stderr, "Error reading directory %s: %s\n",
326                  path, strerror (errno));
327         return NOTMUCH_STATUS_FILE_ERROR;
328     }
329
330     if (! S_ISDIR (st.st_mode)) {
331         fprintf (stderr, "Error: %s is not a directory.\n", path);
332         return NOTMUCH_STATUS_FILE_ERROR;
333     }
334
335     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
336         /* Setup our handler for SIGALRM */
337         memset (&action, 0, sizeof (struct sigaction));
338         action.sa_handler = handle_sigalrm;
339         sigemptyset (&action.sa_mask);
340         action.sa_flags = SA_RESTART;
341         sigaction (SIGALRM, &action, NULL);
342
343         /* Then start a timer to send SIGALRM once per second. */
344         timerval.it_interval.tv_sec = 1;
345         timerval.it_interval.tv_usec = 0;
346         timerval.it_value.tv_sec = 1;
347         timerval.it_value.tv_usec = 0;
348         setitimer (ITIMER_REAL, &timerval, NULL);
349
350         timer_is_active = TRUE;
351     }
352
353     status = add_files_recursive (notmuch, path, &st, state);
354
355     if (timer_is_active) {
356         /* Now stop the timer. */
357         timerval.it_interval.tv_sec = 0;
358         timerval.it_interval.tv_usec = 0;
359         timerval.it_value.tv_sec = 0;
360         timerval.it_value.tv_usec = 0;
361         setitimer (ITIMER_REAL, &timerval, NULL);
362
363         /* And disable the signal handler. */
364         action.sa_handler = SIG_IGN;
365         sigaction (SIGALRM, &action, NULL);
366     }
367
368     return status;
369 }
370
371 /* XXX: This should be merged with the add_files function since it
372  * shares a lot of logic with it. */
373 /* Recursively count all regular files in path and all sub-directories
374  * of path.  The result is added to *count (which should be
375  * initialized to zero by the top-level caller before calling
376  * count_files). */
377 static void
378 count_files (const char *path, int *count)
379 {
380     struct dirent *entry = NULL;
381     char *next;
382     struct stat st;
383     struct dirent **namelist = NULL;
384     int n_entries = scandir (path, &namelist, 0, ino_cmp);
385     int i = 0;
386
387     if (n_entries == -1) {
388         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
389                  path, strerror (errno));
390         goto DONE;
391     }
392
393     while (!interrupted) {
394         if (i == n_entries)
395             break;
396
397         entry= namelist[i++];
398
399         /* Ignore special directories to avoid infinite recursion.
400          * Also ignore the .notmuch directory.
401          */
402         /* XXX: Eventually we'll want more sophistication to let the
403          * user specify files to be ignored. */
404         if (strcmp (entry->d_name, ".") == 0 ||
405             strcmp (entry->d_name, "..") == 0 ||
406             strcmp (entry->d_name, ".notmuch") == 0)
407         {
408             continue;
409         }
410
411         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
412             next = NULL;
413             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
414                      path, entry->d_name);
415             continue;
416         }
417
418         stat (next, &st);
419
420         if (S_ISREG (st.st_mode)) {
421             *count = *count + 1;
422             if (*count % 1000 == 0) {
423                 printf ("Found %d files so far.\r", *count);
424                 fflush (stdout);
425             }
426         } else if (S_ISDIR (st.st_mode)) {
427             count_files (next, count);
428         }
429
430         free (next);
431     }
432
433   DONE:
434     if (entry)
435         free (entry);
436     if (namelist)
437         free (namelist);
438 }
439
440 int
441 notmuch_new_command (void *ctx, int argc, char *argv[])
442 {
443     notmuch_config_t *config;
444     notmuch_database_t *notmuch;
445     add_files_state_t add_files_state;
446     double elapsed;
447     struct timeval tv_now;
448     int ret = 0;
449     struct stat st;
450     const char *db_path;
451     char *dot_notmuch_path;
452     struct sigaction action;
453     int i;
454
455     add_files_state.verbose = 0;
456     add_files_state.output_is_a_tty = isatty (fileno (stdout));
457
458     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
459         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
460             add_files_state.verbose = 1;
461         } else {
462             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
463             return 1;
464         }
465     }
466
467     /* Setup our handler for SIGINT */
468     memset (&action, 0, sizeof (struct sigaction));
469     action.sa_handler = handle_sigint;
470     sigemptyset (&action.sa_mask);
471     action.sa_flags = SA_RESTART;
472     sigaction (SIGINT, &action, NULL);
473
474     config = notmuch_config_open (ctx, NULL, NULL);
475     if (config == NULL)
476         return 1;
477
478     db_path = notmuch_config_get_database_path (config);
479
480     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
481
482     if (stat (dot_notmuch_path, &st)) {
483         int count;
484
485         count = 0;
486         count_files (db_path, &count);
487         if (interrupted)
488             return 1;
489
490         printf ("Found %d total files (that's not much mail).\n", count);
491         notmuch = notmuch_database_create (db_path);
492         add_files_state.total_files = count;
493     } else {
494         notmuch = notmuch_database_open (db_path,
495                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
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.processed_files = 0;
506     add_files_state.added_messages = 0;
507     gettimeofday (&add_files_state.tv_start, NULL);
508
509     ret = add_files (notmuch, db_path, &add_files_state);
510
511     gettimeofday (&tv_now, NULL);
512     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
513                                     tv_now);
514     if (add_files_state.processed_files) {
515         printf ("Processed %d %s in ", add_files_state.processed_files,
516                 add_files_state.processed_files == 1 ?
517                 "file" : "total files");
518         notmuch_time_print_formatted_seconds (elapsed);
519         if (elapsed > 1) {
520             printf (" (%d files/sec.).                 \n",
521                     (int) (add_files_state.processed_files / elapsed));
522         } else {
523             printf (".                    \n");
524         }
525     }
526     if (add_files_state.added_messages) {
527         printf ("Added %d new %s to the database.\n",
528                 add_files_state.added_messages,
529                 add_files_state.added_messages == 1 ?
530                 "message" : "messages");
531     } else {
532         printf ("No new mail.\n");
533     }
534
535     if (ret) {
536         printf ("\nNote: At least one error was encountered: %s\n",
537                 notmuch_status_to_string (ret));
538     }
539
540     notmuch_database_close (notmuch);
541
542     return ret || interrupted;
543 }