]> git.notmuchmail.org Git - notmuch/blob - notmuch-search.c
lib: fix error handling
[notmuch] / notmuch-search.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 #include "sprinter.h"
23 #include "string-util.h"
24
25 typedef enum {
26     OUTPUT_SUMMARY,
27     OUTPUT_THREADS,
28     OUTPUT_MESSAGES,
29     OUTPUT_FILES,
30     OUTPUT_TAGS
31 } output_t;
32
33 static char *
34 sanitize_string (const void *ctx, const char *str)
35 {
36     char *out, *loop;
37
38     if (NULL == str)
39         return NULL;
40
41     loop = out = talloc_strdup (ctx, str);
42
43     for (; *loop; loop++) {
44         if ((unsigned char)(*loop) < 32)
45             *loop = '?';
46     }
47     return out;
48 }
49
50 /* Return two stable query strings that identify exactly the matched
51  * and unmatched messages currently in thread.  If there are no
52  * matched or unmatched messages, the returned buffers will be
53  * NULL. */
54 static int
55 get_thread_query (notmuch_thread_t *thread,
56                   char **matched_out, char **unmatched_out)
57 {
58     notmuch_messages_t *messages;
59     char *escaped = NULL;
60     size_t escaped_len = 0;
61
62     *matched_out = *unmatched_out = NULL;
63
64     for (messages = notmuch_thread_get_messages (thread);
65          notmuch_messages_valid (messages);
66          notmuch_messages_move_to_next (messages))
67     {
68         notmuch_message_t *message = notmuch_messages_get (messages);
69         const char *mid = notmuch_message_get_message_id (message);
70         /* Determine which query buffer to extend */
71         char **buf = notmuch_message_get_flag (
72             message, NOTMUCH_MESSAGE_FLAG_MATCH) ? matched_out : unmatched_out;
73         /* Add this message's id: query.  Since "id" is an exclusive
74          * prefix, it is implicitly 'or'd together, so we only need to
75          * join queries with a space. */
76         if (make_boolean_term (thread, "id", mid, &escaped, &escaped_len) < 0)
77             return -1;
78         if (*buf)
79             *buf = talloc_asprintf_append_buffer (*buf, " %s", escaped);
80         else
81             *buf = talloc_strdup (thread, escaped);
82         if (!*buf)
83             return -1;
84     }
85     talloc_free (escaped);
86     return 0;
87 }
88
89 static int
90 do_search_threads (sprinter_t *format,
91                    notmuch_query_t *query,
92                    notmuch_sort_t sort,
93                    output_t output,
94                    int offset,
95                    int limit)
96 {
97     notmuch_thread_t *thread;
98     notmuch_threads_t *threads;
99     notmuch_tags_t *tags;
100     time_t date;
101     int i;
102
103     if (offset < 0) {
104         offset += notmuch_query_count_threads (query);
105         if (offset < 0)
106             offset = 0;
107     }
108
109     threads = notmuch_query_search_threads (query);
110     if (threads == NULL)
111         return 1;
112
113     format->begin_list (format);
114
115     for (i = 0;
116          notmuch_threads_valid (threads) && (limit < 0 || i < offset + limit);
117          notmuch_threads_move_to_next (threads), i++)
118     {
119         thread = notmuch_threads_get (threads);
120
121         if (i < offset) {
122             notmuch_thread_destroy (thread);
123             continue;
124         }
125
126         if (output == OUTPUT_THREADS) {
127             format->set_prefix (format, "thread");
128             format->string (format,
129                             notmuch_thread_get_thread_id (thread));
130             format->separator (format);
131         } else { /* output == OUTPUT_SUMMARY */
132             void *ctx_quote = talloc_new (thread);
133             const char *authors = notmuch_thread_get_authors (thread);
134             const char *subject = notmuch_thread_get_subject (thread);
135             const char *thread_id = notmuch_thread_get_thread_id (thread);
136             int matched = notmuch_thread_get_matched_messages (thread);
137             int total = notmuch_thread_get_total_messages (thread);
138             const char *relative_date = NULL;
139             notmuch_bool_t first_tag = TRUE;
140
141             format->begin_map (format);
142
143             if (sort == NOTMUCH_SORT_OLDEST_FIRST)
144                 date = notmuch_thread_get_oldest_date (thread);
145             else
146                 date = notmuch_thread_get_newest_date (thread);
147
148             relative_date = notmuch_time_relative_date (ctx_quote, date);
149
150             if (format->is_text_printer) {
151                 /* Special case for the text formatter */
152                 printf ("thread:%s %12s [%d/%d] %s; %s (",
153                         thread_id,
154                         relative_date,
155                         matched,
156                         total,
157                         sanitize_string (ctx_quote, authors),
158                         sanitize_string (ctx_quote, subject));
159             } else { /* Structured Output */
160                 format->map_key (format, "thread");
161                 format->string (format, thread_id);
162                 format->map_key (format, "timestamp");
163                 format->integer (format, date);
164                 format->map_key (format, "date_relative");
165                 format->string (format, relative_date);
166                 format->map_key (format, "matched");
167                 format->integer (format, matched);
168                 format->map_key (format, "total");
169                 format->integer (format, total);
170                 format->map_key (format, "authors");
171                 format->string (format, authors);
172                 format->map_key (format, "subject");
173                 format->string (format, subject);
174                 if (notmuch_format_version >= 2) {
175                     char *matched_query, *unmatched_query;
176                     if (get_thread_query (thread, &matched_query,
177                                           &unmatched_query) < 0) {
178                         fprintf (stderr, "Out of memory\n");
179                         return 1;
180                     }
181                     format->map_key (format, "query");
182                     format->begin_list (format);
183                     if (matched_query)
184                         format->string (format, matched_query);
185                     else
186                         format->null (format);
187                     if (unmatched_query)
188                         format->string (format, unmatched_query);
189                     else
190                         format->null (format);
191                     format->end (format);
192                 }
193             }
194
195             talloc_free (ctx_quote);
196
197             format->map_key (format, "tags");
198             format->begin_list (format);
199
200             for (tags = notmuch_thread_get_tags (thread);
201                  notmuch_tags_valid (tags);
202                  notmuch_tags_move_to_next (tags))
203             {
204                 const char *tag = notmuch_tags_get (tags);
205
206                 if (format->is_text_printer) {
207                   /* Special case for the text formatter */
208                     if (first_tag)
209                         first_tag = FALSE;
210                     else
211                         fputc (' ', stdout);
212                     fputs (tag, stdout);
213                 } else { /* Structured Output */
214                     format->string (format, tag);
215                 }
216             }
217
218             if (format->is_text_printer)
219                 printf (")");
220
221             format->end (format);
222             format->end (format);
223             format->separator (format);
224         }
225
226         notmuch_thread_destroy (thread);
227     }
228
229     format->end (format);
230
231     return 0;
232 }
233
234 static int
235 do_search_messages (sprinter_t *format,
236                     notmuch_query_t *query,
237                     output_t output,
238                     int offset,
239                     int limit,
240                     int dupe)
241 {
242     notmuch_message_t *message;
243     notmuch_messages_t *messages;
244     notmuch_filenames_t *filenames;
245     int i;
246
247     if (offset < 0) {
248         offset += notmuch_query_count_messages (query);
249         if (offset < 0)
250             offset = 0;
251     }
252
253     messages = notmuch_query_search_messages (query);
254     if (messages == NULL)
255         return 1;
256
257     format->begin_list (format);
258
259     for (i = 0;
260          notmuch_messages_valid (messages) && (limit < 0 || i < offset + limit);
261          notmuch_messages_move_to_next (messages), i++)
262     {
263         if (i < offset)
264             continue;
265
266         message = notmuch_messages_get (messages);
267
268         if (output == OUTPUT_FILES) {
269             int j;
270             filenames = notmuch_message_get_filenames (message);
271
272             for (j = 1;
273                  notmuch_filenames_valid (filenames);
274                  notmuch_filenames_move_to_next (filenames), j++)
275             {
276                 if (dupe < 0 || dupe == j) {
277                     format->string (format, notmuch_filenames_get (filenames));
278                     format->separator (format);
279                 }
280             }
281             
282             notmuch_filenames_destroy( filenames );
283
284         } else { /* output == OUTPUT_MESSAGES */
285             format->set_prefix (format, "id");
286             format->string (format,
287                             notmuch_message_get_message_id (message));
288             format->separator (format);
289         }
290
291         notmuch_message_destroy (message);
292     }
293
294     notmuch_messages_destroy (messages);
295
296     format->end (format);
297
298     return 0;
299 }
300
301 static int
302 do_search_tags (notmuch_database_t *notmuch,
303                 sprinter_t *format,
304                 notmuch_query_t *query)
305 {
306     notmuch_messages_t *messages = NULL;
307     notmuch_tags_t *tags;
308     const char *tag;
309
310     /* should the following only special case if no excluded terms
311      * specified? */
312
313     /* Special-case query of "*" for better performance. */
314     if (strcmp (notmuch_query_get_query_string (query), "*") == 0) {
315         tags = notmuch_database_get_all_tags (notmuch);
316     } else {
317         messages = notmuch_query_search_messages (query);
318         if (messages == NULL)
319             return 1;
320
321         tags = notmuch_messages_collect_tags (messages);
322     }
323     if (tags == NULL)
324         return 1;
325
326     format->begin_list (format);
327
328     for (;
329          notmuch_tags_valid (tags);
330          notmuch_tags_move_to_next (tags))
331     {
332         tag = notmuch_tags_get (tags);
333
334         format->string (format, tag);
335         format->separator (format);
336
337     }
338
339     notmuch_tags_destroy (tags);
340
341     if (messages)
342         notmuch_messages_destroy (messages);
343
344     format->end (format);
345
346     return 0;
347 }
348
349 int
350 notmuch_search_command (notmuch_config_t *config, int argc, char *argv[])
351 {
352     notmuch_database_t *notmuch;
353     notmuch_query_t *query;
354     char *query_str;
355     notmuch_sort_t sort = NOTMUCH_SORT_NEWEST_FIRST;
356     sprinter_t *format = NULL;
357     int opt_index, ret;
358     output_t output = OUTPUT_SUMMARY;
359     int offset = 0;
360     int limit = -1; /* unlimited */
361     notmuch_exclude_t exclude = NOTMUCH_EXCLUDE_TRUE;
362     int dupe = -1;
363     unsigned int i;
364
365     enum {
366         NOTMUCH_FORMAT_JSON,
367         NOTMUCH_FORMAT_TEXT,
368         NOTMUCH_FORMAT_TEXT0,
369         NOTMUCH_FORMAT_SEXP
370     } format_sel = NOTMUCH_FORMAT_TEXT;
371
372     notmuch_opt_desc_t options[] = {
373         { NOTMUCH_OPT_KEYWORD, &sort, "sort", 's',
374           (notmuch_keyword_t []){ { "oldest-first", NOTMUCH_SORT_OLDEST_FIRST },
375                                   { "newest-first", NOTMUCH_SORT_NEWEST_FIRST },
376                                   { 0, 0 } } },
377         { NOTMUCH_OPT_KEYWORD, &format_sel, "format", 'f',
378           (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
379                                   { "sexp", NOTMUCH_FORMAT_SEXP },
380                                   { "text", NOTMUCH_FORMAT_TEXT },
381                                   { "text0", NOTMUCH_FORMAT_TEXT0 },
382                                   { 0, 0 } } },
383         { NOTMUCH_OPT_INT, &notmuch_format_version, "format-version", 0, 0 },
384         { NOTMUCH_OPT_KEYWORD, &output, "output", 'o',
385           (notmuch_keyword_t []){ { "summary", OUTPUT_SUMMARY },
386                                   { "threads", OUTPUT_THREADS },
387                                   { "messages", OUTPUT_MESSAGES },
388                                   { "files", OUTPUT_FILES },
389                                   { "tags", OUTPUT_TAGS },
390                                   { 0, 0 } } },
391         { NOTMUCH_OPT_KEYWORD, &exclude, "exclude", 'x',
392           (notmuch_keyword_t []){ { "true", NOTMUCH_EXCLUDE_TRUE },
393                                   { "false", NOTMUCH_EXCLUDE_FALSE },
394                                   { "flag", NOTMUCH_EXCLUDE_FLAG },
395                                   { "all", NOTMUCH_EXCLUDE_ALL },
396                                   { 0, 0 } } },
397         { NOTMUCH_OPT_INT, &offset, "offset", 'O', 0 },
398         { NOTMUCH_OPT_INT, &limit, "limit", 'L', 0  },
399         { NOTMUCH_OPT_INT, &dupe, "duplicate", 'D', 0  },
400         { 0, 0, 0, 0, 0 }
401     };
402
403     opt_index = parse_arguments (argc, argv, options, 1);
404     if (opt_index < 0)
405         return EXIT_FAILURE;
406
407     switch (format_sel) {
408     case NOTMUCH_FORMAT_TEXT:
409         format = sprinter_text_create (config, stdout);
410         break;
411     case NOTMUCH_FORMAT_TEXT0:
412         if (output == OUTPUT_SUMMARY) {
413             fprintf (stderr, "Error: --format=text0 is not compatible with --output=summary.\n");
414             return EXIT_FAILURE;
415         }
416         format = sprinter_text0_create (config, stdout);
417         break;
418     case NOTMUCH_FORMAT_JSON:
419         format = sprinter_json_create (config, stdout);
420         break;
421     case NOTMUCH_FORMAT_SEXP:
422         format = sprinter_sexp_create (config, stdout);
423         break;
424     default:
425         /* this should never happen */
426         INTERNAL_ERROR("no output format selected");
427     }
428
429     notmuch_exit_if_unsupported_format ();
430
431     if (notmuch_database_open (notmuch_config_get_database_path (config),
432                                NOTMUCH_DATABASE_MODE_READ_ONLY, &notmuch))
433         return EXIT_FAILURE;
434
435     query_str = query_string_from_args (notmuch, argc-opt_index, argv+opt_index);
436     if (query_str == NULL) {
437         fprintf (stderr, "Out of memory.\n");
438         return EXIT_FAILURE;
439     }
440     if (*query_str == '\0') {
441         fprintf (stderr, "Error: notmuch search requires at least one search term.\n");
442         return EXIT_FAILURE;
443     }
444
445     query = notmuch_query_create (notmuch, query_str);
446     if (query == NULL) {
447         fprintf (stderr, "Out of memory\n");
448         return EXIT_FAILURE;
449     }
450
451     notmuch_query_set_sort (query, sort);
452
453     if (exclude == NOTMUCH_EXCLUDE_FLAG && output != OUTPUT_SUMMARY) {
454         /* If we are not doing summary output there is nowhere to
455          * print the excluded flag so fall back on including the
456          * excluded messages. */
457         fprintf (stderr, "Warning: this output format cannot flag excluded messages.\n");
458         exclude = NOTMUCH_EXCLUDE_FALSE;
459     }
460
461     if (exclude != NOTMUCH_EXCLUDE_FALSE) {
462         const char **search_exclude_tags;
463         size_t search_exclude_tags_length;
464
465         search_exclude_tags = notmuch_config_get_search_exclude_tags
466             (config, &search_exclude_tags_length);
467         for (i = 0; i < search_exclude_tags_length; i++)
468             notmuch_query_add_tag_exclude (query, search_exclude_tags[i]);
469         notmuch_query_set_omit_excluded (query, exclude);
470     }
471
472     switch (output) {
473     default:
474     case OUTPUT_SUMMARY:
475     case OUTPUT_THREADS:
476         ret = do_search_threads (format, query, sort, output, offset, limit);
477         break;
478     case OUTPUT_MESSAGES:
479     case OUTPUT_FILES:
480         ret = do_search_messages (format, query, output, offset, limit, dupe);
481         break;
482     case OUTPUT_TAGS:
483         ret = do_search_tags (notmuch, format, query);
484         break;
485     }
486
487     notmuch_query_destroy (query);
488     notmuch_database_destroy (notmuch);
489
490     talloc_free (format);
491
492     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
493 }