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