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