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