Replace done with exit at uip
[mmh] / uip / folder.c
1 /*
2 ** folder(s).c -- set/list the current message and/or folder
3 **             -- push/pop a folder onto/from the folder stack
4 **             -- list the folder stack
5 **
6 ** This code is Copyright (c) 2002, 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
11 #include <h/mh.h>
12 #include <h/crawl_folders.h>
13 #include <h/utils.h>
14 #include <errno.h>
15
16 static struct swit switches[] = {
17 #define ALLSW  0
18         { "all", 0 },
19 #define NALLSW  1
20         { "noall", 2 },
21 #define CREATSW  2
22         { "create", 0 },
23 #define NCREATSW  3
24         { "nocreate", 2 },
25 #define FASTSW  4
26         { "fast", 0 },
27 #define NFASTSW  5
28         { "nofast", 2 },
29 #define PACKSW  6
30         { "pack", 0 },
31 #define NPACKSW  7
32         { "nopack", 2 },
33 #define VERBSW  8
34         { "verbose", 0 },
35 #define NVERBSW  9
36         { "noverbose", 2 },
37 #define RECURSW  10
38         { "recurse", 0 },
39 #define NRECRSW  11
40         { "norecurse", 2 },
41 #define TOTALSW  12
42         { "total", 0 },
43 #define NTOTLSW  13
44         { "nototal", 2 },
45 #define LISTSW  14
46         { "list", 0 },
47 #define NLISTSW  15
48         { "nolist", 2 },
49 #define PRNTSW  16
50         { "print", 0 },
51 #define NPRNTSW  17
52         { "noprint", -4 },
53 #define PUSHSW  18
54         { "push", 0 },
55 #define POPSW  19
56         { "pop", 0 },
57 #define VERSIONSW  20
58         { "Version", 0 },
59 #define HELPSW  21
60         { "help", 0 },
61         { NULL, 0 }
62 };
63
64 static int fshort   = 0;  /* output only folder names */
65 static int fcreat   = 0;  /* should we ask to create new folders? */
66 static int fpack    = 0;  /* are we packing the folder? */
67 static int fverb    = 0;  /* print actions taken while packing folder */
68 static int frecurse = 0;  /* recurse through subfolders */
69 static int ftotal   = 0;  /* should we output the totals? */
70 static int all      = 0;  /* should we output all folders */
71
72 static int total_folders = 0;  /* total number of folders */
73
74 static char *nmhdir;
75 static char *stack = "Folder-Stack";
76 static char folder[BUFSIZ];
77
78 /*
79 ** Structure to hold information about
80 ** folders as we scan them.
81 */
82 struct FolderInfo {
83         char *name;
84         int nummsg;
85         int curmsg;
86         int lowmsg;
87         int hghmsg;
88         int others;  /* others == 1 if other files in folder */
89         int error;  /* error == 1 for unreadable folder */
90 };
91
92 /*
93 ** Dynamically allocated space to hold
94 ** all the folder information.
95 */
96 static struct FolderInfo *fi;
97 static int maxFolderInfo;
98
99 /*
100 ** static prototypes
101 */
102 static int get_folder_info(char *, char *);
103 static crawl_callback_t get_folder_info_callback;
104 static void print_folders(void);
105 static int sfold(struct msgs *, char *);
106 static void readonly_folders(void);
107 static int folder_pack(struct msgs **, int);
108
109
110 int
111 main(int argc, char **argv)
112 {
113         int printsw = 0, listsw = 0;
114         int pushsw = 0, popsw = 0;
115         char *cp, *dp, *msg = NULL, *argfolder = NULL;
116         char **ap, **argp, buf[BUFSIZ], **arguments;
117
118         setlocale(LC_ALL, "");
119         invo_name = mhbasename(argv[0]);
120
121         /* read user profile/context */
122         context_read();
123
124         /*
125         ** If program was invoked with name ending
126         ** in `s', then add switch `-all'.
127         */
128         if (argv[0][strlen(argv[0]) - 1] == 's')
129                 all = 1;
130
131         arguments = getarguments(invo_name, argc, argv, 1);
132         argp = arguments;
133
134         while ((cp = *argp++)) {
135                 if (*cp == '-') {
136                         switch (smatch(++cp, switches)) {
137                         case AMBIGSW:
138                                 ambigsw(cp, switches);
139                                 /*sysexits.h EX_USAGE*/
140                                 exit(1);
141                         case UNKWNSW:
142                                 adios(NULL, "-%s unknown", cp);
143
144                         case HELPSW:
145                                 snprintf(buf, sizeof(buf), "%s [+folder] [msg] [switches]", invo_name);
146                                 print_help(buf, switches, 1);
147                                 exit(0);
148                         case VERSIONSW:
149                                 print_version(invo_name);
150                                 exit(0);
151
152                         case ALLSW:
153                                 all = 1;
154                                 continue;
155
156                         case NALLSW:
157                                 all = 0;
158                                 continue;
159
160                         case CREATSW:
161                                 fcreat = 1;
162                                 continue;
163                         case NCREATSW:
164                                 fcreat = -1;
165                                 continue;
166
167                         case FASTSW:
168                                 fshort++;
169                                 continue;
170                         case NFASTSW:
171                                 fshort = 0;
172                                 continue;
173
174                         case PACKSW:
175                                 fpack++;
176                                 continue;
177                         case NPACKSW:
178                                 fpack = 0;
179                                 continue;
180
181                         case VERBSW:
182                                 fverb++;
183                                 continue;
184                         case NVERBSW:
185                                 fverb = 0;
186                                 continue;
187
188                         case RECURSW:
189                                 frecurse++;
190                                 continue;
191                         case NRECRSW:
192                                 frecurse = 0;
193                                 continue;
194
195                         case TOTALSW:
196                                 ftotal = 1;
197                                 continue;
198                         case NTOTLSW:
199                                 ftotal = -1;
200                                 continue;
201
202                         case PRNTSW:
203                                 printsw = 1;
204                                 continue;
205                         case NPRNTSW:
206                                 printsw = 0;
207                                 continue;
208
209                         case LISTSW:
210                                 listsw = 1;
211                                 continue;
212                         case NLISTSW:
213                                 listsw = 0;
214                                 continue;
215
216                         case PUSHSW:
217                                 pushsw = 1;
218                                 listsw = 1;
219                                 popsw  = 0;
220                                 continue;
221                         case POPSW:
222                                 popsw  = 1;
223                                 listsw = 1;
224                                 pushsw = 0;
225                                 continue;
226                         }
227                 }
228                 if (*cp == '+' || *cp == '@') {
229                         if (argfolder)
230                                 adios(NULL, "only one folder at a time!");
231                         else
232                                 argfolder = getcpy(expandfol(cp));
233                 } else {
234                         if (msg)
235                                 adios(NULL, "only one (current) message at a time!");
236                         else
237                                 msg = cp;
238                 }
239         }
240
241         nmhdir = concat(toabsdir("+"), "/", NULL);
242
243         /*
244         ** If we aren't working with the folder stack
245         ** (-push, -pop, -list) then the default is to print.
246         */
247         if (pushsw == 0 && popsw == 0 && listsw == 0)
248                 printsw++;
249
250         /* Pushing a folder onto the folder stack */
251         if (pushsw) {
252                 if (!argfolder) {
253                         /* If no folder is given, the current folder and */
254                         /* the top of the folder stack are swapped. */
255                         if ((cp = context_find(stack))) {
256                                 dp = getcpy(cp);
257                                 ap = brkstring(dp, " ", "\n");
258                                 argfolder = getcpy(*ap++);
259                         } else {
260                                 adios(NULL, "no other folder");
261                         }
262                         for (cp = getcpy(getcurfol()); *ap; ap++)
263                                 cp = add(*ap, add(" ", cp));
264                         free(dp);
265                         context_replace(stack, cp);  /* update folder stack */
266                 } else {
267                         /* update folder stack */
268                         context_replace(stack, (cp = context_find (stack)) ?
269                                         concat(getcurfol(), " ", cp, NULL) :
270                                         getcpy(getcurfol()));
271                 }
272         }
273
274         /* Popping a folder off of the folder stack */
275         if (popsw) {
276                 if (argfolder)
277                         adios(NULL, "sorry, no folders allowed with -pop");
278                 if ((cp = context_find(stack))) {
279                         dp = getcpy(cp);
280                         ap = brkstring(dp, " ", "\n");
281                         argfolder = getcpy(*ap++);
282                 } else {
283                         adios(NULL, "folder stack empty");
284                 }
285                 if (*ap) {
286                         /* if there's anything left in the stack */
287                         cp = getcpy(*ap++);
288                         for (; *ap; ap++)
289                                 cp = add(*ap, add(" ", cp));
290                         context_replace(stack, cp);  /* update folder stack */
291                 } else {
292                         /* delete folder stack entry from context */
293                         context_del(stack);
294                 }
295                 free(dp);
296         }
297         if (pushsw || popsw) {
298                 cp = toabsdir(argfolder);
299                 if (access(cp, F_OK) == NOTOK)
300                         adios(cp, "unable to find folder");
301                 /* update current folder   */
302                 context_replace(curfolder, argfolder);
303                 context_save();  /* save the context file   */
304                 argfolder = NULL;
305         }
306
307         /* Listing the folder stack */
308         if (listsw) {
309                 printf("%s", argfolder ? argfolder : getcurfol());
310                 if ((cp = context_find(stack))) {
311                         dp = getcpy(cp);
312                         for (ap = brkstring(dp, " ", "\n"); *ap; ap++)
313                                 printf(" %s", *ap);
314                         free(dp);
315                 }
316                 printf("\n");
317
318                 if (!printsw) {
319                         exit(0);
320                 }
321         }
322
323         /* Allocate initial space to record folder information */
324         maxFolderInfo = CRAWL_NUMFOLDERS;
325         fi = mh_xmalloc(maxFolderInfo * sizeof(*fi));
326
327         /*
328         ** Scan the folders
329         */
330         if (all || ftotal > 0) {
331                 /*
332                 ** If no folder is given, do them all
333                 */
334                 /*
335                 ** change directory to base of nmh directory for
336                 ** crawl_folders
337                 */
338                 if (chdir(nmhdir) == NOTOK)
339                         adios(nmhdir, "unable to change directory to");
340                 if (!argfolder) {
341                         if (msg)
342                                 admonish(NULL, "no folder given for message %s", msg);
343                         readonly_folders(); /* do any readonly folders */
344                         strncpy(folder, (cp = context_find(curfolder)) ?
345                                         cp : "", sizeof(folder));
346                         crawl_folders(".", get_folder_info_callback, NULL);
347                 } else {
348                         strncpy(folder, argfolder, sizeof(folder));
349                         if (get_folder_info(argfolder, msg)) {
350                                 /* update current folder */
351                                 context_replace(curfolder, argfolder);
352                                 context_save();
353                         }
354                         /*
355                         ** Since recurse wasn't done in get_folder_info(),
356                         ** we still need to list all level-1 sub-folders.
357                         */
358                         if (!frecurse)
359                                 crawl_folders(folder, get_folder_info_callback,
360                                                 NULL);
361                 }
362         } else {
363                 strncpy(folder, argfolder ? argfolder : getcurfol(),
364                                 sizeof(folder));
365
366                 /*
367                 ** Check if folder exists.  If not, then see if
368                 ** we should create it, or just exit.
369                 */
370                 create_folder(toabsdir(folder), fcreat, done);
371
372                 if (get_folder_info(folder, msg) && argfolder) {
373                         /* update current folder */
374                         context_replace(curfolder, argfolder);
375                         }
376         }
377
378         /*
379         ** Print out folder information
380         */
381         print_folders();
382
383         context_save();
384         return 0;
385 }
386
387 static int
388 get_folder_info_body(char *fold, char *msg, boolean *crawl_children)
389 {
390         int i, retval = 1;
391         struct msgs *mp = NULL;
392
393         i = total_folders++;
394
395         /*
396         ** if necessary, reallocate the space
397         ** for folder information
398         */
399         if (total_folders >= maxFolderInfo) {
400                 maxFolderInfo += CRAWL_NUMFOLDERS;
401                 fi = mh_xrealloc(fi, maxFolderInfo * sizeof(*fi));
402         }
403
404         fi[i].name   = fold;
405         fi[i].nummsg = 0;
406         fi[i].curmsg = 0;
407         fi[i].lowmsg = 0;
408         fi[i].hghmsg = 0;
409         fi[i].others = 0;
410         fi[i].error  = 0;
411
412         if ((ftotal > 0) || !fshort || msg || fpack) {
413                 /*
414                 ** create message structure and get folder info
415                 */
416                 if (!(mp = folder_read(fold))) {
417                         admonish(NULL, "unable to read folder %s", fold);
418                         return 0;
419                 }
420
421                 /* set the current message */
422                 if (msg && !sfold(mp, msg))
423                         retval = 0;
424
425                 if (fpack) {
426                         if (folder_pack(&mp, fverb) == -1) {
427                                 exit(0);
428                         }
429                         seq_save(mp);  /* synchronize the sequences */
430                         context_save();  /* save the context file */
431                 }
432
433                 /* record info for this folder */
434                 if ((ftotal > 0) || !fshort) {
435                         fi[i].nummsg = mp->nummsg;
436                         fi[i].curmsg = mp->curmsg;
437                         fi[i].lowmsg = mp->lowmsg;
438                         fi[i].hghmsg = mp->hghmsg;
439                         fi[i].others = other_files(mp);
440                 }
441
442                 folder_free(mp); /* free folder/message structure */
443         }
444
445         *crawl_children = (frecurse && (fshort || fi[i].others)
446                 && (fi[i].error == 0));
447         return retval;
448 }
449
450 static boolean
451 get_folder_info_callback(char *fold, void *baton)
452 {
453         boolean crawl_children;
454         get_folder_info_body(fold, NULL, &crawl_children);
455         fflush(stdout);
456         return crawl_children;
457 }
458
459 static int
460 get_folder_info(char *fold, char *msg)
461 {
462         boolean crawl_children;
463         int retval;
464
465         retval = get_folder_info_body(fold, msg, &crawl_children);
466
467         if (crawl_children) {
468                 crawl_folders(fold, get_folder_info_callback, NULL);
469         }
470 return retval;
471 }
472
473 /*
474 ** Print folder information
475 */
476
477 static void
478 print_folders(void)
479 {
480         int i, len, hasempty = 0, curprinted;
481         int maxlen = 0, maxnummsg = 0, maxlowmsg = 0;
482         int maxhghmsg = 0, maxcurmsg = 0, total_msgs = 0;
483         int nummsgdigits, lowmsgdigits;
484         int hghmsgdigits, curmsgdigits;
485         char tmpname[BUFSIZ];
486
487         /*
488         ** compute a few values needed to for
489         ** printing various fields
490         */
491         for (i = 0; i < total_folders; i++) {
492                 /* length of folder name */
493                 len = strlen(fi[i].name);
494                 if (len > maxlen)
495                         maxlen = len;
496
497                 /* If folder has error, skip the rest */
498                 if (fi[i].error)
499                         continue;
500
501                 /* calculate total number of messages */
502                 total_msgs += fi[i].nummsg;
503
504                 /* maximum number of messages */
505                 if (fi[i].nummsg > maxnummsg)
506                         maxnummsg = fi[i].nummsg;
507
508                 /* maximum low message */
509                 if (fi[i].lowmsg > maxlowmsg)
510                         maxlowmsg = fi[i].lowmsg;
511
512                 /* maximum high message */
513                 if (fi[i].hghmsg > maxhghmsg)
514                         maxhghmsg = fi[i].hghmsg;
515
516                 /* maximum current message */
517                 if (fi[i].curmsg >= fi[i].lowmsg &&
518                         fi[i].curmsg <= fi[i].hghmsg &&
519                         fi[i].curmsg > maxcurmsg)
520                         maxcurmsg = fi[i].curmsg;
521
522                 /* check for empty folders */
523                 if (fi[i].nummsg == 0)
524                         hasempty = 1;
525         }
526         nummsgdigits = num_digits(maxnummsg);
527         lowmsgdigits = num_digits(maxlowmsg);
528         hghmsgdigits = num_digits(maxhghmsg);
529         curmsgdigits = num_digits(maxcurmsg);
530
531         if (hasempty && nummsgdigits < 2)
532                 nummsgdigits = 2;
533
534         /*
535         ** Print folder information
536         */
537         if (all || fshort || ftotal < 1) {
538                 for (i = 0; i < total_folders; i++) {
539                         if (fshort) {
540                                 printf("%s\n", fi[i].name);
541                                 continue;
542                         }
543
544                         /* Add `+' to end of name, if folder is current */
545                         if (strcmp(folder, fi[i].name)!=0)
546                                 snprintf(tmpname, sizeof(tmpname), "%s",
547                                                 fi[i].name);
548                         else
549                                 snprintf(tmpname, sizeof(tmpname), "%s+",
550                                                 fi[i].name);
551
552                         if (fi[i].error) {
553                                 printf("%-*s is unreadable\n", maxlen+1,
554                                                 tmpname);
555                                 continue;
556                         }
557
558                         printf("%-*s ", maxlen+1, tmpname);
559
560                         curprinted = 0; /* remember if we print cur */
561                         if (fi[i].nummsg == 0) {
562                                 printf("has %*s messages%*s", nummsgdigits, "no", fi[i].others ? lowmsgdigits + hghmsgdigits + 5 : 0, "");
563                         } else {
564                                 printf("has %*d message%s  (%*d-%*d)",
565                                                 nummsgdigits, fi[i].nummsg,
566                                                 (fi[i].nummsg == 1) ?
567                                                 " " : "s",
568                                                 lowmsgdigits, fi[i].lowmsg,
569                                                 hghmsgdigits, fi[i].hghmsg);
570                                 if (fi[i].curmsg >= fi[i].lowmsg && fi[i].curmsg <= fi[i].hghmsg) {
571                                         curprinted = 1;
572                                         printf("; cur=%*d", curmsgdigits,
573                                                         fi[i].curmsg);
574                                 }
575                         }
576
577                         if (fi[i].others)
578                                 printf(";%*s (others)", curprinted ?
579                                                 0 : curmsgdigits + 6, "");
580                         printf("\n");
581                 }
582         }
583
584         /*
585         ** Print folder/message totals
586         */
587         if (ftotal > 0 || (all && !fshort && ftotal >= 0)) {
588                 if (all)
589                         printf("\n");
590                 printf("TOTAL = %d message%c in %d folder%s\n",
591                                 total_msgs, total_msgs != 1 ? 's' : ' ',
592                                 total_folders, total_folders != 1 ? "s" : "");
593         }
594
595         fflush(stdout);
596 }
597
598 /*
599 ** Set the current message and sychronize sequences
600 */
601
602 static int
603 sfold(struct msgs *mp, char *msg)
604 {
605         /* parse the message range/sequence/name and set SELECTED */
606         if (!m_convert(mp, msg))
607                 return 0;
608
609         if (mp->numsel > 1) {
610                 admonish(NULL, "only one message at a time!");
611                 return 0;
612         }
613         seq_setprev(mp);  /* set the previous-sequence */
614         seq_setcur(mp, mp->lowsel);  /* set current message */
615         seq_save(mp);  /* synchronize message sequences */
616         context_save();  /* save the context file */
617
618         return 1;
619 }
620
621
622 /*
623 ** Do the read only folders
624 */
625
626 static void
627 readonly_folders(void)
628 {
629         int atrlen;
630         char atrcur[BUFSIZ];
631         register struct node *np;
632
633         snprintf(atrcur, sizeof(atrcur), "atr-%s-", seq_cur);
634         atrlen = strlen(atrcur);
635
636         for (np = m_defs; np; np = np->n_next)
637                 if (strncmp(np->n_name, atrcur, atrlen)==0 &&
638                                 strncmp(np->n_name+atrlen, nmhdir, strlen(nmhdir))!=0)
639                         /* Why do we exclude absolute path names? --meillo */
640                         get_folder_info(np->n_name + atrlen, NULL);
641 }
642
643
644 /*
645 ** pack (renumber) the messages in a folder
646 ** into a contiguous range from 1 to n.
647 ** Return -1 if error, else return 0.
648 */
649 static int
650 folder_pack(struct msgs **mpp, int verbose)
651 {
652         int hole, msgnum, newcurrent = 0;
653         char newmsg[BUFSIZ], oldmsg[BUFSIZ];
654         struct msgs *mp;
655
656         mp = *mpp;
657
658         /*
659         ** Just return if folder is empty.
660         */
661         if (mp->nummsg == 0)
662                 return 0;
663
664         /*
665         ** Make sure we have message status space allocated
666         ** for all numbers from 1 to current high message.
667         */
668         if (mp->lowoff > 1) {
669                 if ((mp = folder_realloc(mp, 1, mp->hghmsg)))
670                         *mpp = mp;
671                 else {
672                         advise(NULL, "unable to allocate folder storage");
673                         return -1;
674                 }
675         }
676
677         for (msgnum = mp->lowmsg, hole = 1; msgnum <= mp->hghmsg; msgnum++) {
678                 if (does_exist(mp, msgnum)) {
679                         if (msgnum != hole) {
680                                 strncpy(newmsg, m_name(hole), sizeof(newmsg));
681                                 strncpy(oldmsg, m_name(msgnum), sizeof(oldmsg));
682                                 if (verbose)
683                                         printf("message %s becomes %s\n", oldmsg, newmsg);
684
685                                 /*
686                                 ** Invoke the external refile hook for each
687                                 ** message being renamed.  This is done
688                                 ** before the file is renamed so that the
689                                 ** old message file is around for the hook.
690                                 */
691
692                                 snprintf(oldmsg, sizeof (oldmsg), "%s/%d",
693                                                 mp->foldpath, msgnum);
694                                 snprintf(newmsg, sizeof (newmsg), "%s/%d",
695                                                 mp->foldpath, hole);
696                                 ext_hook("ref-hook", oldmsg, newmsg);
697
698                                 /* move the message file */
699                                 if (rename(oldmsg, newmsg) == -1) {
700                                         advise(newmsg, "unable to rename %s to", oldmsg);
701                                         return -1;
702                                 }
703
704                                 /* check if this is the current message */
705                                 if (msgnum == mp->curmsg)
706                                         newcurrent = hole;
707
708                                 /* copy the attribute flags for this message */
709                                 copy_msg_flags(mp, hole, msgnum);
710
711                                 if (msgnum == mp->lowsel)
712                                         mp->lowsel = hole;
713                                 if (msgnum == mp->hghsel)
714                                         mp->hghsel = hole;
715
716                                 /*
717                                 ** mark that sequence information has
718                                 ** been modified
719                                 */
720                                 mp->msgflags |= SEQMOD;
721                         }
722                         hole++;
723                 }
724         }
725
726         /* record the new number for the high/low message */
727         mp->lowmsg = 1;
728         mp->hghmsg = hole - 1;
729
730         if (newcurrent)
731                 seq_setcur(mp, newcurrent);
732
733         return 0;
734 }