Use sysexits.h for better exit-codes
[mmh] / uip / new.c
1 /*
2 ** new.c -- as new,    list all folders with unseen messages
3 **       -- as fnext,  move to next folder with unseen messages
4 **       -- as fprev,  move to previous folder with unseen messages
5 **       -- as unseen, scan all unseen messages
6 ** This code is Copyright (c) 2008, by the authors of nmh.  See the
7 ** COPYRIGHT file in the root directory of the nmh distribution for
8 ** complete copyright information.
9 **
10 ** Inspired by Luke Mewburn's new: http://www.mewburn.net/luke/src/new
11 */
12
13 #include <h/mh.h>
14 #include <h/crawl_folders.h>
15 #include <h/utils.h>
16 #include <sys/types.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <locale.h>
22 #include <sysexits.h>
23
24 static struct swit switches[] = {
25 #define MODESW 0
26         { "mode", 0 },
27 #define FOLDERSSW 1
28         { "folders", 0 },
29 #define VERSIONSW 2
30         { "Version", 0 },
31 #define HELPSW 3
32         { "help", 0 },
33         { NULL, 0 }
34 };
35
36 static enum { NEW, FNEXT, FPREV, UNSEEN } run_mode = NEW;
37
38 /*
39 ** check_folders uses this to maintain state with both .folders list of
40 ** folders and with crawl_folders.
41 */
42 struct list_state {
43         struct node **first, **cur_node;
44         size_t *maxlen;
45         char *cur;
46         char **sequences;
47         struct node *node;
48 };
49
50 /* Return the number of messages in a string list of message numbers. */
51 static int
52 count_messages(char *field)
53 {
54         int total = 0;
55         int j, k;
56         char *cp, **ap;
57
58         field = getcpy(field);
59
60         /* copied from seq_read.c:seq_init */
61         for (ap = brkstring(field, " ", "\n"); *ap; ap++) {
62                 if ((cp = strchr(*ap, '-')))
63                         *cp++ = '\0';
64                 if ((j = m_atoi(*ap)) > 0) {
65                         k = cp ? m_atoi(cp) : j;
66
67                         total += k - j + 1;
68                 }
69         }
70
71         free(field);
72
73         return total;
74 }
75
76 /* Return TRUE if the sequence 'name' is in 'sequences'. */
77 static boolean
78 seq_in_list(char *name, char *sequences[])
79 {
80         int i;
81
82         for (i = 0; sequences[i] != NULL; i++) {
83                 if (strcmp(name, sequences[i]) == 0) {
84                         return TRUE;
85                 }
86         }
87
88         return FALSE;
89 }
90
91 /*
92 ** Return the string list of message numbers from the sequences file,
93 ** or NULL if none.
94 */
95 static char *
96 get_msgnums(char *folder, char *sequences[])
97 {
98         char *seqfile = concat(toabsdir(folder), "/", mh_seq, (void *)NULL);
99         FILE *fp = fopen(seqfile, "r");
100         int state;
101         char name[NAMESZ], field[BUFSIZ];
102         char *cp;
103         char *msgnums = NULL, *this_msgnums, *old_msgnums;
104
105         /* no sequences file -> no messages */
106         if (fp == NULL) {
107                 return NULL;
108         }
109
110         /* copied from seq_read.c:seq_public */
111         for (state = FLD;;) {
112                 switch (state = m_getfld(state, name, field, sizeof(field),
113                                 fp)) {
114                 case FLD:
115                 case FLDPLUS:
116                 case FLDEOF:
117                         if (state == FLDPLUS) {
118                                 cp = getcpy(field);
119                                 while (state == FLDPLUS) {
120                                         state = m_getfld(state, name, field,
121                                                         sizeof(field), fp);
122                                         cp = add(field, cp);
123                                 }
124
125                                 /*
126                                 ** Here's where we differ from
127                                 ** seq_public: if it's in a
128                                 ** sequence we want, save the list
129                                 ** of messages.
130                                 */
131                                 if (seq_in_list(name, sequences)) {
132                                         this_msgnums = trimcpy(cp);
133                                         if (msgnums == NULL) {
134                                                 msgnums = this_msgnums;
135                                         } else {
136                                                 old_msgnums = msgnums;
137                                                 msgnums = concat(old_msgnums, " ", this_msgnums, (void *)NULL);
138                                                 free(old_msgnums);
139                                                 free(this_msgnums);
140                                         }
141                                 }
142                                 free(cp);
143                         } else {
144                                 /* and here */
145                                 if (seq_in_list(name, sequences)) {
146                                         this_msgnums = trimcpy(field);
147                                         if (msgnums == NULL) {
148                                                 msgnums = this_msgnums;
149                                         } else {
150                                                 old_msgnums = msgnums;
151                                                 msgnums = concat(old_msgnums, " ", this_msgnums, (void *)NULL);
152                                                 free(old_msgnums);
153                                                 free(this_msgnums);
154                                         }
155                                 }
156                         }
157
158                         if (state == FLDEOF)
159                                 break;
160                         continue;
161
162                 case BODY:
163                 case BODYEOF:
164                         adios(EX_DATAERR, NULL, "no blank lines are permitted in %s",
165                                         seqfile);
166                         /* fall */
167
168                 case FILEEOF:
169                         break;
170
171                 default:
172                         adios(EX_SOFTWARE, NULL, "%s is poorly formatted", seqfile);
173                 }
174                 break;  /* break from for loop */
175         }
176
177         fclose(fp);
178
179         return msgnums;
180 }
181
182 /*
183 ** Check `folder' (of length `len') for interesting messages,
184 ** filling in the list in `b'.
185 */
186 static void
187 check_folder(char *folder, size_t len, struct list_state *b)
188 {
189         char *msgnums = get_msgnums(folder, b->sequences);
190         int is_cur = strcmp(folder, b->cur) == 0;
191
192         if (is_cur || msgnums != NULL) {
193                 if (*b->first == NULL) {
194                         *b->first = b->node = mh_xmalloc(sizeof(*b->node));
195                 } else {
196                         b->node->n_next = mh_xmalloc(sizeof(*b->node));
197                         b->node = b->node->n_next;
198                 }
199                 b->node->n_name = folder;
200                 b->node->n_field = msgnums;
201
202                 if (*b->maxlen < len) {
203                         *b->maxlen = len;
204                 }
205         }
206
207         /* Save the node for the current folder, so we can fall back to it. */
208         if (is_cur) {
209                 *b->cur_node = b->node;
210         }
211 }
212
213 static boolean
214 crawl_callback(char *folder, void *baton)
215 {
216         check_folder(folder, strlen(folder), baton);
217         return TRUE;
218 }
219
220 /*
221 ** Scan folders, returning:
222 ** first        -- list of nodes for all folders which have desired messages;
223 **                 if the current folder is listed in .folders, it is also in
224 **                 the list regardless of whether it has any desired messages
225 ** last         -- last node in list
226 ** cur_node     -- node of current folder, if listed in .folders
227 ** maxlen       -- length of longest folder name
228 **
229 ** `cur' points to the name of the current folder, `folders' points to the
230 ** name of a .folder (if NULL, crawl all folders), and `sequences' points to
231 ** the array of sequences for which to look.
232 **
233 ** An empty list is returned as first=last=NULL.
234 */
235 static void
236 check_folders(struct node **first, struct node **last,
237         struct node **cur_node, size_t *maxlen,
238         char *cur, char *folders, char *sequences[])
239 {
240         struct list_state b;
241         FILE *fp;
242         char *line;
243         size_t len;
244
245         *first = *last = *cur_node = NULL;
246         *maxlen = 0;
247
248         b.first = first;
249         b.cur_node = cur_node;
250         b.maxlen = maxlen;
251         b.cur = cur;
252         b.sequences = sequences;
253
254         if (folders == NULL) {
255                 chdir(toabsdir("+"));
256                 crawl_folders(".", crawl_callback, &b);
257         } else {
258                 fp = fopen(folders, "r");
259                 if (fp  == NULL) {
260                         adios(EX_IOERR, NULL, "failed to read %s", folders);
261                 }
262                 while (vfgets(fp, &line) == OK) {
263                         len = strlen(line) - 1;
264                         line[len] = '\0';
265                         check_folder(getcpy(line), len, &b);
266                 }
267                 fclose(fp);
268         }
269
270         if (*first != NULL) {
271                 b.node->n_next = NULL;
272                 *last = b.node;
273         }
274 }
275
276 /* Return a single string of the `sequences' joined by a space (' '). */
277 static char *
278 join_sequences(char *sequences[])
279 {
280         int i;
281         size_t len = 0;
282         char *result, *cp;
283
284         for (i = 0; sequences[i] != NULL; i++) {
285                 len += strlen(sequences[i]) + 1;
286         }
287         result = mh_xmalloc(len + 1);
288
289         for (i = 0, cp = result; sequences[i] != NULL; i++, cp += len + 1) {
290                 len = strlen(sequences[i]);
291                 memcpy(cp, sequences[i], len);
292                 cp[len] = ' ';
293         }
294         /* -1 to overwrite the last delimiter */
295         *--cp = '\0';
296
297         return result;
298 }
299
300 /*
301 ** Return a struct node for the folder to change to.  This is the next
302 ** (previous, if FPREV mode) folder with desired messages, or the current
303 ** folder if no folders have desired.  If NEW or UNSEEN mode, print the
304 ** output but don't change folders.
305 **
306 ** n_name is the folder to change to, and n_field is the string list of
307 ** desired message numbers.
308 */
309 static struct node *
310 doit(char *cur, char *folders, char *sequences[])
311 {
312         struct node *first, *cur_node, *node, *last = NULL, *prev;
313         size_t folder_len;
314         int count, total = 0;
315         char *sequences_s = NULL;
316         int argc = 0;
317         char *argv[MAXARGS];
318         char **seqp;
319         char buf[BUFSIZ];
320
321         if (cur == NULL || cur[0] == '\0') {
322                 cur = "inbox";
323         }
324
325         check_folders(&first, &last, &cur_node, &folder_len, cur,
326                         folders, sequences);
327
328         if (run_mode == FNEXT || run_mode == FPREV) {
329                 if (first == NULL) {
330                         /* No folders at all... */
331                         return NULL;
332                 } else if (first->n_next == NULL) {
333                         /*
334                         ** We have only one node; any desired messages in it?
335                         */
336                         if (first->n_field == NULL) {
337                                 return NULL;
338                         } else {
339                                 return first;
340                         }
341                 } else if (cur_node == NULL) {
342                         /*
343                         ** Current folder is not listed in .folders,
344                         ** return first.
345                         */
346                         return first;
347                 }
348         } else if (run_mode == UNSEEN) {
349                 sequences_s = join_sequences(sequences);
350         }
351
352         for (node = first, prev = NULL;
353                  node != NULL;
354                  prev = node, node = node->n_next) {
355                 if (run_mode == FNEXT) {
356                         /*
357                         ** If we have a previous node and it is the current
358                         ** folder, return this node.
359                         */
360                         if (prev != NULL && strcmp(prev->n_name, cur) == 0) {
361                                 return node;
362                         }
363                 } else if (run_mode == FPREV) {
364                         if (strcmp(node->n_name, cur) == 0) {
365                                 /*
366                                 ** Found current folder in fprev mode;
367                                 ** if we have a previous node in the list,
368                                 ** return it; else return the last node.
369                                 */
370                                 if (prev == NULL) {
371                                         return last;
372                                 }
373                                 return prev;
374                         }
375                 } else if (run_mode == UNSEEN) {
376                         if (node->n_field == NULL) {
377                                 continue;
378                         }
379
380                         printf("\n%d %s messages in %s",
381                                    count_messages(node->n_field),
382                                    sequences_s,
383                                    node->n_name);
384                         if (strcmp(node->n_name, cur) == 0) {
385                                 puts(" (*: current folder)");
386                         } else {
387                                 puts("");
388                         }
389                         fflush(stdout);
390
391                         argc = 0;
392                         argv[argc++] = "scan";
393                         snprintf(buf, sizeof buf, "+%s", node->n_name);
394                         argv[argc++] = buf;
395                         for (seqp=sequences; *seqp; seqp++) {
396                                 argv[argc++] = *seqp;
397                         }
398                         argv[argc] = (char *)NULL;
399                         execprog(*argv, argv);
400                 } else {
401                         if (node->n_field == NULL) {
402                                 continue;
403                         }
404
405                         count = count_messages(node->n_field);
406                         total += count;
407
408                         printf("%-*s %6d.%c %s\n", (int) folder_len,
409                                 node->n_name, count,
410                                 (strcmp(node->n_name, cur) == 0 ? '*' : ' '),
411                                 node->n_field);
412                 }
413         }
414
415         /*
416         ** If we're fnext, we haven't checked the last node yet.  If it's the
417         ** current folder, return the first node.
418         */
419         if (run_mode == FNEXT && strcmp(last->n_name, cur) == 0) {
420                 return first;
421         }
422
423         if (run_mode == NEW) {
424                 printf("%-*s %6d.\n", (int) folder_len, " total", total);
425         }
426
427         return cur_node;
428 }
429
430 int
431 main(int argc, char **argv)
432 {
433         char **ap, *cp, **argp, **arguments;
434         char help[BUFSIZ];
435         char *folders = NULL;
436         char *sequences[NUMATTRS + 1];
437         int i = 0;
438         char *unseen;
439         struct node *folder;
440
441         sequences[0] = NULL;
442         sequences[1] = NULL;
443
444         setlocale(LC_ALL, "");
445         invo_name = mhbasename(argv[0]);
446
447         /* read user profile/context */
448         context_read();
449
450         arguments = getarguments(invo_name, argc, argv, 1);
451         argp = arguments;
452
453         /*
454         ** Parse arguments
455         */
456         while ((cp = *argp++)) {
457                 if (*cp == '-') {
458                         switch (smatch(++cp, switches)) {
459                         case AMBIGSW:
460                                 ambigsw(cp, switches);
461                                 exit(EX_USAGE);
462                         case UNKWNSW:
463                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
464
465                         case HELPSW:
466                                 snprintf(help, sizeof(help),
467                                                 "%s [switches] [sequences]",
468                                                 invo_name);
469                                 print_help(help, switches, 1);
470                                 exit(argc == 2 ? EX_OK : EX_USAGE);
471                         case VERSIONSW:
472                                 print_version(invo_name);
473                                 exit(argc == 2 ? EX_OK : EX_USAGE);
474
475                         case FOLDERSSW:
476                                 if (!(folders = *argp++) || *folders == '-')
477                                         adios(EX_USAGE, NULL, "missing argument to %s",
478                                                         argp[-2]);
479                                 continue;
480                         case MODESW:
481                                 if (!(invo_name = *argp++) || *invo_name == '-')
482                                         adios(EX_USAGE, NULL, "missing argument to %s",
483                                                         argp[-2]);
484                                 invo_name = mhbasename(invo_name);
485                                 continue;
486                         }
487                 }
488                 /* have a sequence argument */
489                 if (!seq_in_list(cp, sequences)) {
490                         sequences[i++] = cp;
491                         sequences[i] = NULL;
492                 }
493         }
494
495         if (strcmp(invo_name, "fnext") == 0) {
496                 run_mode = FNEXT;
497         } else if (strcmp(invo_name, "fprev") == 0) {
498                 run_mode = FPREV;
499         } else if (strcmp(invo_name, "unseen") == 0) {
500                 run_mode = UNSEEN;
501         }
502
503         if (folders == NULL) {
504                 /* will flists */
505         } else {
506                 if (folders[0] != '/') {
507                         folders = toabsdir(folders);
508                 }
509         }
510
511         if (i == 0) {
512                 char *dp;
513                 /* no sequence arguments; use unseen */
514                 if ((unseen = context_find(usequence))) {
515                         if (!*unseen) {
516                                 adios(EX_CONFIG, NULL, "profile entry %s set, but empty, and no sequences given", usequence);
517                         }
518                 } else {
519                         unseen = seq_unseen;  /* use default */
520                 }
521                 dp = getcpy(unseen);
522                 for (ap = brkstring(dp, " ", "\n"); *ap; ap++) {
523                         sequences[i++] = *ap;
524                 }
525         }
526         sequences[i] = NULL;
527
528         folder = doit(context_find(curfolder), folders, sequences);
529         if (folder == NULL) {
530                 exit(EX_OK);
531                 return 1;
532         }
533
534         if (run_mode == UNSEEN) {
535                 /*
536                 ** All the scan(1)s it runs change the current folder, so we
537                 ** need to put it back.  Unfortunately, context_replace lamely
538                 ** ignores the new value you give it if it is the same one it
539                 ** has in memory.  So, we'll be lame, too.  I'm not sure if i
540                 ** should just change context_replace...
541                 */
542                 context_replace(curfolder, "defeat_context_replace_optimization");
543         }
544
545         /* update current folder */
546         context_replace(curfolder, folder->n_name);
547
548         if (run_mode == FNEXT || run_mode == FPREV) {
549                 printf("%s  %s\n", folder->n_name, folder->n_field);
550         }
551
552         context_save();
553
554         return 0;
555 }