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