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