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