]> git.notmuchmail.org Git - notmuch/blob - notmuch-restore.c
lib: add versions of n_q_count_{message,threads} with status return
[notmuch] / notmuch-restore.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 "hex-escape.h"
23 #include "tag-util.h"
24 #include "string-util.h"
25 #include "zlib-extra.h"
26
27 static regex_t regex;
28
29 /* Non-zero return indicates an error in retrieving the message,
30  * or in applying the tags.  Missing messages are reported, but not
31  * considered errors.
32  */
33 static int
34 tag_message (unused (void *ctx),
35              notmuch_database_t *notmuch,
36              const char *message_id,
37              tag_op_list_t *tag_ops,
38              tag_op_flag_t flags)
39 {
40     notmuch_status_t status;
41     notmuch_message_t *message = NULL;
42     int ret = 0;
43
44     status = notmuch_database_find_message (notmuch, message_id, &message);
45     if (status) {
46         fprintf (stderr, "Error applying tags to message %s: %s\n",
47                  message_id, notmuch_status_to_string (status));
48         return 1;
49     }
50     if (message == NULL) {
51         fprintf (stderr, "Warning: cannot apply tags to missing message: %s\n",
52                  message_id);
53         /* We consider this a non-fatal error. */
54         return 0;
55     }
56
57     /* In order to detect missing messages, this check/optimization is
58      * intentionally done *after* first finding the message. */
59     if ((flags & TAG_FLAG_REMOVE_ALL) || tag_op_list_size (tag_ops))
60         ret = tag_op_list_apply (message, tag_ops, flags);
61
62     notmuch_message_destroy (message);
63
64     return ret;
65 }
66
67 /* Sup dump output is one line per message. We match a sequence of
68  * non-space characters for the message-id, then one or more
69  * spaces, then a list of space-separated tags as a sequence of
70  * characters within literal '(' and ')'. */
71
72 static int
73 parse_sup_line (void *ctx, char *line,
74                 char **query_str, tag_op_list_t *tag_ops)
75 {
76
77     regmatch_t match[3];
78     char *file_tags;
79     int rerr;
80
81     tag_op_list_reset (tag_ops);
82
83     chomp_newline (line);
84
85     /* Silently ignore blank lines */
86     if (line[0] == '\0') {
87         return 1;
88     }
89
90     rerr = xregexec (&regex, line, 3, match, 0);
91     if (rerr == REG_NOMATCH) {
92         fprintf (stderr, "Warning: Ignoring invalid sup format line: %s\n",
93                  line);
94         return 1;
95     }
96
97     *query_str = talloc_strndup_debug (ctx, line + match[1].rm_so,
98                                        match[1].rm_eo - match[1].rm_so);
99
100     file_tags = talloc_strndup_debug (ctx, line + match[2].rm_so,
101                                       match[2].rm_eo - match[2].rm_so);
102
103     char *tok = file_tags;
104     size_t tok_len = 0;
105
106     tag_op_list_reset (tag_ops);
107
108     while ((tok = strtok_len (tok + tok_len, " ", &tok_len)) != NULL) {
109
110         if (*(tok + tok_len) != '\0') {
111             *(tok + tok_len) = '\0';
112             tok_len++;
113         }
114
115         if (tag_op_list_append (tag_ops, tok, FALSE))
116             return -1;
117     }
118
119     return 0;
120
121 }
122
123 int
124 notmuch_restore_command (notmuch_config_t *config, int argc, char *argv[])
125 {
126     notmuch_database_t *notmuch;
127     notmuch_bool_t accumulate = FALSE;
128     tag_op_flag_t flags = 0;
129     tag_op_list_t *tag_ops;
130
131     char *input_file_name = NULL;
132     const char *name_for_error = NULL;
133     gzFile input = NULL;
134     char *line = NULL;
135     void *line_ctx = NULL;
136     ssize_t line_len;
137
138     int ret = 0;
139     int opt_index;
140     int input_format = DUMP_FORMAT_AUTO;
141
142     if (notmuch_database_open (notmuch_config_get_database_path (config),
143                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
144         return EXIT_FAILURE;
145
146     if (notmuch_config_get_maildir_synchronize_flags (config))
147         flags |= TAG_FLAG_MAILDIR_SYNC;
148
149     notmuch_opt_desc_t options[] = {
150         { NOTMUCH_OPT_KEYWORD, &input_format, "format", 'f',
151           (notmuch_keyword_t []){ { "auto", DUMP_FORMAT_AUTO },
152                                   { "batch-tag", DUMP_FORMAT_BATCH_TAG },
153                                   { "sup", DUMP_FORMAT_SUP },
154                                   { 0, 0 } } },
155         { NOTMUCH_OPT_STRING, &input_file_name, "input", 'i', 0 },
156         { NOTMUCH_OPT_BOOLEAN,  &accumulate, "accumulate", 'a', 0 },
157         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
158         { 0, 0, 0, 0, 0 }
159     };
160
161     opt_index = parse_arguments (argc, argv, options, 1);
162     if (opt_index < 0) {
163         ret = EXIT_FAILURE;
164         goto DONE;
165     }
166
167     notmuch_process_shared_options (argv[0]);
168     notmuch_exit_if_unmatched_db_uuid (notmuch);
169
170     name_for_error = input_file_name ? input_file_name : "stdin";
171
172     if (! accumulate)
173         flags |= TAG_FLAG_REMOVE_ALL;
174
175     errno = 0;
176     if (input_file_name)
177         input = gzopen (input_file_name, "r");
178     else {
179         int infd = dup (STDIN_FILENO);
180         if (infd < 0) {
181             fprintf (stderr, "Error duping stdin: %s\n",
182                      strerror (errno));
183             ret = EXIT_FAILURE;
184             goto DONE;
185         }
186         input = gzdopen (infd, "r");
187         if (! input)
188             close (infd);
189     }
190
191     if (input == NULL) {
192         fprintf (stderr, "Error opening %s for (gzip) reading: %s\n",
193                  name_for_error, strerror (errno));
194         ret = EXIT_FAILURE;
195         goto DONE;
196     }
197
198     if (opt_index < argc) {
199         fprintf (stderr, "Unused positional parameter: %s\n", argv[opt_index]);
200         ret = EXIT_FAILURE;
201         goto DONE;
202     }
203
204     tag_ops = tag_op_list_create (config);
205     if (tag_ops == NULL) {
206         fprintf (stderr, "Out of memory.\n");
207         ret = EXIT_FAILURE;
208         goto DONE;
209     }
210
211     do {
212         util_status_t status;
213
214         status = gz_getline (line_ctx, &line, &line_len, input);
215
216         /* empty input file not considered an error */
217         if (status == UTIL_EOF) {
218             ret = EXIT_SUCCESS;
219             goto DONE;
220         }
221
222         if (status) {
223             fprintf (stderr, "Error reading (gzipped) input: %s\n",
224                      gz_error_string(status, input));
225             ret = EXIT_FAILURE;
226             goto DONE;
227         }
228     } while ((line_len == 0) ||
229              (line[0] == '#') ||
230              /* the cast is safe because we checked about for line_len < 0 */
231              (strspn (line, " \t\n") == (unsigned)line_len));
232
233     char *p;
234     for (p = line; (input_format == DUMP_FORMAT_AUTO) && *p; p++) {
235         if (*p == '(')
236             input_format = DUMP_FORMAT_SUP;
237     }
238
239     if (input_format == DUMP_FORMAT_AUTO)
240         input_format = DUMP_FORMAT_BATCH_TAG;
241
242     if (input_format == DUMP_FORMAT_SUP)
243         if ( xregcomp (&regex,
244                        "^([^ ]+) \\(([^)]*)\\)$",
245                        REG_EXTENDED) )
246             INTERNAL_ERROR ("compile time constant regex failed.");
247
248     do {
249         char *query_string, *prefix, *term;
250
251         if (line_ctx != NULL)
252             talloc_free (line_ctx);
253
254         line_ctx = talloc_new (config);
255         if (input_format == DUMP_FORMAT_SUP) {
256             ret = parse_sup_line (line_ctx, line, &query_string, tag_ops);
257         } else {
258             ret = parse_tag_line (line_ctx, line, TAG_FLAG_BE_GENEROUS,
259                                   &query_string, tag_ops);
260
261             if (ret == 0) {
262                 ret = parse_boolean_term (line_ctx, query_string,
263                                           &prefix, &term);
264                 if (ret && errno == EINVAL) {
265                     fprintf (stderr, "Warning: cannot parse query: %s (skipping)\n", query_string);
266                     continue;
267                 } else if (ret) {
268                     /* This is more fatal (e.g., out of memory) */
269                     fprintf (stderr, "Error parsing query: %s\n",
270                              strerror (errno));
271                     ret = 1;
272                     break;
273                 } else if (strcmp ("id", prefix) != 0) {
274                     fprintf (stderr, "Warning: not an id query: %s (skipping)\n", query_string);
275                     continue;
276                 }
277                 query_string = term;
278             }
279         }
280
281         if (ret > 0)
282             continue;
283
284         if (ret < 0)
285             break;
286
287         ret = tag_message (line_ctx, notmuch, query_string,
288                            tag_ops, flags);
289         if (ret)
290             break;
291
292     }  while (! (ret = gz_getline (line_ctx, &line, &line_len, input)));
293     
294
295     /* EOF is normal loop termination condition, UTIL_SUCCESS is
296      * impossible here */
297     if (ret == UTIL_EOF) {
298         ret = EXIT_SUCCESS;
299     } else {
300         fprintf (stderr, "Error reading (gzipped) input: %s\n",
301                  gz_error_string (ret, input));
302         ret = EXIT_FAILURE;
303     }
304
305     /* currently this should not be after DONE: since we don't 
306      * know if the xregcomp was reached
307      */
308
309     if (input_format == DUMP_FORMAT_SUP)
310         regfree (&regex);
311
312  DONE:
313     if (line_ctx != NULL)
314         talloc_free (line_ctx);
315
316     if (notmuch)
317         notmuch_database_destroy (notmuch);
318
319     if (input && gzclose_r (input)) {
320         fprintf (stderr, "Error closing %s: %s\n",
321                  name_for_error, gzerror (input, NULL));
322         ret = EXIT_FAILURE;
323     }
324
325     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
326 }