]> git.notmuchmail.org Git - notmuch/blob - notmuch-search.c
cli: search: Add --output={sender,recipients}
[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      = 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     sprinter_t *format = opt->format;
238     InternetAddress *ia = internet_address_mailbox_new (name, addr);
239     char *name_addr;
240
241     /* name_addr has the name part quoted if necessary. Compare
242      * 'John Doe <john@doe.com>' vs. '"Doe, John" <john@doe.com>' */
243     name_addr = internet_address_to_string (ia, FALSE);
244
245     if (format->is_text_printer) {
246         format->string (format, name_addr);
247         format->separator (format);
248     } else {
249         format->begin_map (format);
250         format->map_key (format, "name");
251         format->string (format, name);
252         format->map_key (format, "address");
253         format->string (format, addr);
254         format->map_key (format, "name-addr");
255         format->string (format, name_addr);
256         format->end (format);
257         format->separator (format);
258     }
259
260     g_object_unref (ia);
261     g_free (name_addr);
262 }
263
264 /* Print addresses from InternetAddressList.  */
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 /* Print addresses from a message header.  */
296 static void
297 process_address_header (const search_options_t *opt, const char *value)
298 {
299     InternetAddressList *list;
300
301     if (value == NULL)
302         return;
303
304     list = internet_address_list_parse_string (value);
305     if (list == NULL)
306         return;
307
308     process_address_list (opt, list);
309
310     g_object_unref (list);
311 }
312
313 static int
314 do_search_messages (search_options_t *opt)
315 {
316     notmuch_message_t *message;
317     notmuch_messages_t *messages;
318     notmuch_filenames_t *filenames;
319     sprinter_t *format = opt->format;
320     int i;
321
322     if (opt->offset < 0) {
323         opt->offset += notmuch_query_count_messages (opt->query);
324         if (opt->offset < 0)
325             opt->offset = 0;
326     }
327
328     messages = notmuch_query_search_messages (opt->query);
329     if (messages == NULL)
330         return 1;
331
332     format->begin_list (format);
333
334     for (i = 0;
335          notmuch_messages_valid (messages) && (opt->limit < 0 || i < opt->offset + opt->limit);
336          notmuch_messages_move_to_next (messages), i++)
337     {
338         if (i < opt->offset)
339             continue;
340
341         message = notmuch_messages_get (messages);
342
343         if (opt->output == OUTPUT_FILES) {
344             int j;
345             filenames = notmuch_message_get_filenames (message);
346
347             for (j = 1;
348                  notmuch_filenames_valid (filenames);
349                  notmuch_filenames_move_to_next (filenames), j++)
350             {
351                 if (opt->dupe < 0 || opt->dupe == j) {
352                     format->string (format, notmuch_filenames_get (filenames));
353                     format->separator (format);
354                 }
355             }
356             
357             notmuch_filenames_destroy( filenames );
358
359         } else if (opt->output == OUTPUT_MESSAGES) {
360             format->set_prefix (format, "id");
361             format->string (format,
362                             notmuch_message_get_message_id (message));
363             format->separator (format);
364         } else {
365             if (opt->output & OUTPUT_SENDER) {
366                 const char *addrs;
367
368                 addrs = notmuch_message_get_header (message, "from");
369                 process_address_header (opt, addrs);
370             }
371
372             if (opt->output & OUTPUT_RECIPIENTS) {
373                 const char *hdrs[] = { "to", "cc", "bcc" };
374                 const char *addrs;
375                 size_t j;
376
377                 for (j = 0; j < ARRAY_SIZE (hdrs); j++) {
378                     addrs = notmuch_message_get_header (message, hdrs[j]);
379                     process_address_header (opt, addrs);
380                 }
381             }
382         }
383
384         notmuch_message_destroy (message);
385     }
386
387     notmuch_messages_destroy (messages);
388
389     format->end (format);
390
391     return 0;
392 }
393
394 static int
395 do_search_tags (notmuch_database_t *notmuch,
396                 const search_options_t *opt)
397 {
398     notmuch_messages_t *messages = NULL;
399     notmuch_tags_t *tags;
400     const char *tag;
401     sprinter_t *format = opt->format;
402     notmuch_query_t *query = opt->query;
403
404     /* should the following only special case if no excluded terms
405      * specified? */
406
407     /* Special-case query of "*" for better performance. */
408     if (strcmp (notmuch_query_get_query_string (query), "*") == 0) {
409         tags = notmuch_database_get_all_tags (notmuch);
410     } else {
411         messages = notmuch_query_search_messages (query);
412         if (messages == NULL)
413             return 1;
414
415         tags = notmuch_messages_collect_tags (messages);
416     }
417     if (tags == NULL)
418         return 1;
419
420     format->begin_list (format);
421
422     for (;
423          notmuch_tags_valid (tags);
424          notmuch_tags_move_to_next (tags))
425     {
426         tag = notmuch_tags_get (tags);
427
428         format->string (format, tag);
429         format->separator (format);
430
431     }
432
433     notmuch_tags_destroy (tags);
434
435     if (messages)
436         notmuch_messages_destroy (messages);
437
438     format->end (format);
439
440     return 0;
441 }
442
443 int
444 notmuch_search_command (notmuch_config_t *config, int argc, char *argv[])
445 {
446     notmuch_database_t *notmuch;
447     search_options_t opt = {
448         .sort = NOTMUCH_SORT_NEWEST_FIRST,
449         .output = 0,
450         .offset = 0,
451         .limit = -1, /* unlimited */
452         .dupe = -1,
453     };
454     char *query_str;
455     int opt_index, ret;
456     notmuch_exclude_t exclude = NOTMUCH_EXCLUDE_TRUE;
457     unsigned int i;
458
459     enum {
460         NOTMUCH_FORMAT_JSON,
461         NOTMUCH_FORMAT_TEXT,
462         NOTMUCH_FORMAT_TEXT0,
463         NOTMUCH_FORMAT_SEXP
464     } format_sel = NOTMUCH_FORMAT_TEXT;
465
466     notmuch_opt_desc_t options[] = {
467         { NOTMUCH_OPT_KEYWORD, &opt.sort, "sort", 's',
468           (notmuch_keyword_t []){ { "oldest-first", NOTMUCH_SORT_OLDEST_FIRST },
469                                   { "newest-first", NOTMUCH_SORT_NEWEST_FIRST },
470                                   { 0, 0 } } },
471         { NOTMUCH_OPT_KEYWORD, &format_sel, "format", 'f',
472           (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
473                                   { "sexp", NOTMUCH_FORMAT_SEXP },
474                                   { "text", NOTMUCH_FORMAT_TEXT },
475                                   { "text0", NOTMUCH_FORMAT_TEXT0 },
476                                   { 0, 0 } } },
477         { NOTMUCH_OPT_INT, &notmuch_format_version, "format-version", 0, 0 },
478         { NOTMUCH_OPT_KEYWORD_FLAGS, &opt.output, "output", 'o',
479           (notmuch_keyword_t []){ { "summary", OUTPUT_SUMMARY },
480                                   { "threads", OUTPUT_THREADS },
481                                   { "messages", OUTPUT_MESSAGES },
482                                   { "sender", OUTPUT_SENDER },
483                                   { "recipients", OUTPUT_RECIPIENTS },
484                                   { "files", OUTPUT_FILES },
485                                   { "tags", OUTPUT_TAGS },
486                                   { 0, 0 } } },
487         { NOTMUCH_OPT_KEYWORD, &exclude, "exclude", 'x',
488           (notmuch_keyword_t []){ { "true", NOTMUCH_EXCLUDE_TRUE },
489                                   { "false", NOTMUCH_EXCLUDE_FALSE },
490                                   { "flag", NOTMUCH_EXCLUDE_FLAG },
491                                   { "all", NOTMUCH_EXCLUDE_ALL },
492                                   { 0, 0 } } },
493         { NOTMUCH_OPT_INT, &opt.offset, "offset", 'O', 0 },
494         { NOTMUCH_OPT_INT, &opt.limit, "limit", 'L', 0  },
495         { NOTMUCH_OPT_INT, &opt.dupe, "duplicate", 'D', 0  },
496         { 0, 0, 0, 0, 0 }
497     };
498
499     opt_index = parse_arguments (argc, argv, options, 1);
500     if (opt_index < 0)
501         return EXIT_FAILURE;
502
503     if (! opt.output)
504         opt.output = OUTPUT_SUMMARY;
505
506     switch (format_sel) {
507     case NOTMUCH_FORMAT_TEXT:
508         opt.format = sprinter_text_create (config, stdout);
509         break;
510     case NOTMUCH_FORMAT_TEXT0:
511         if (opt.output == OUTPUT_SUMMARY) {
512             fprintf (stderr, "Error: --format=text0 is not compatible with --output=summary.\n");
513             return EXIT_FAILURE;
514         }
515         opt.format = sprinter_text0_create (config, stdout);
516         break;
517     case NOTMUCH_FORMAT_JSON:
518         opt.format = sprinter_json_create (config, stdout);
519         break;
520     case NOTMUCH_FORMAT_SEXP:
521         opt.format = sprinter_sexp_create (config, stdout);
522         break;
523     default:
524         /* this should never happen */
525         INTERNAL_ERROR("no output format selected");
526     }
527
528     notmuch_exit_if_unsupported_format ();
529
530     if (notmuch_database_open (notmuch_config_get_database_path (config),
531                                NOTMUCH_DATABASE_MODE_READ_ONLY, &notmuch))
532         return EXIT_FAILURE;
533
534     query_str = query_string_from_args (notmuch, argc-opt_index, argv+opt_index);
535     if (query_str == NULL) {
536         fprintf (stderr, "Out of memory.\n");
537         return EXIT_FAILURE;
538     }
539     if (*query_str == '\0') {
540         fprintf (stderr, "Error: notmuch search requires at least one search term.\n");
541         return EXIT_FAILURE;
542     }
543
544     opt.query = notmuch_query_create (notmuch, query_str);
545     if (opt.query == NULL) {
546         fprintf (stderr, "Out of memory\n");
547         return EXIT_FAILURE;
548     }
549
550     notmuch_query_set_sort (opt.query, opt.sort);
551
552     if (exclude == NOTMUCH_EXCLUDE_FLAG && opt.output != OUTPUT_SUMMARY) {
553         /* If we are not doing summary output there is nowhere to
554          * print the excluded flag so fall back on including the
555          * excluded messages. */
556         fprintf (stderr, "Warning: this output format cannot flag excluded messages.\n");
557         exclude = NOTMUCH_EXCLUDE_FALSE;
558     }
559
560     if (exclude != NOTMUCH_EXCLUDE_FALSE) {
561         const char **search_exclude_tags;
562         size_t search_exclude_tags_length;
563
564         search_exclude_tags = notmuch_config_get_search_exclude_tags
565             (config, &search_exclude_tags_length);
566         for (i = 0; i < search_exclude_tags_length; i++)
567             notmuch_query_add_tag_exclude (opt.query, search_exclude_tags[i]);
568         notmuch_query_set_omit_excluded (opt.query, exclude);
569     }
570
571     if (opt.output == OUTPUT_SUMMARY ||
572         opt.output == OUTPUT_THREADS)
573         ret = do_search_threads (&opt);
574     else if (opt.output == OUTPUT_MESSAGES ||
575              opt.output == OUTPUT_FILES ||
576              (opt.output & OUTPUT_ADDRESS_FLAGS && !(opt.output & ~OUTPUT_ADDRESS_FLAGS)))
577         ret = do_search_messages (&opt);
578     else if (opt.output == OUTPUT_TAGS)
579         ret = do_search_tags (notmuch, &opt);
580     else {
581         fprintf (stderr, "Error: the combination of outputs is not supported.\n");
582         ret = 1;
583     }
584
585     notmuch_query_destroy (opt.query);
586     notmuch_database_destroy (notmuch);
587
588     talloc_free (opt.format);
589
590     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
591 }