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