Added -noall/-all switches to sortm(1).
[mmh] / uip / sortm.c
1
2 /*
3  * sortm.c -- sort messages in a folder by date/time
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #include <h/mh.h>
11 #include <h/tws.h>
12 #include <h/utils.h>
13
14 static struct swit switches[] = {
15 #define DATESW                 0
16      { "datefield field", 0 },
17 #define TEXTSW                 1
18      { "textfield field", 0 },
19 #define NSUBJSW                2
20      { "notextfield", 0 },
21 #define SUBJSW                 3
22      { "subject", -3 },            /* backward-compatibility */
23 #define LIMSW                  4
24      { "limit days", 0 },
25 #define NLIMSW                 5
26      { "nolimit", 0 },
27 #define VERBSW                 6
28      { "verbose", 0 },
29 #define NVERBSW                7
30      { "noverbose", 0 },
31 #define ALLMSGS                8
32      { "all", 0 },
33 #define NALLMSGS               9
34      { "noall", 0 },
35 #define VERSIONSW             10
36      { "version", 0 },
37 #define HELPSW                11
38      { "help", 0 },
39      { NULL, 0 }
40 };
41
42 struct smsg {
43     int s_msg;
44     time_t s_clock;
45     char *s_subj;
46 };
47
48 static struct smsg *smsgs;
49 int nmsgs;
50
51 char *subjsort = (char *) 0;    /* sort on subject if != 0 */
52 time_t datelimit = 0;
53 int submajor = 0;               /* if true, sort on subject-major */
54 int verbose;
55 int allmsgs = 1;
56
57 /* This keeps compiler happy on calls to qsort */
58 typedef int (*qsort_comp) (const void *, const void *);
59
60 /*
61  * static prototypes
62  */
63 static int read_hdrs (struct msgs *, char *);
64 static int get_fields (char *, int, struct smsg *);
65 static int dsort (struct smsg **, struct smsg **);
66 static int subsort (struct smsg **, struct smsg **);
67 static int txtsort (struct smsg **, struct smsg **);
68 static void rename_chain (struct msgs *, struct smsg **, int, int);
69 static void rename_msgs (struct msgs *, struct smsg **);
70
71
72 int
73 main (int argc, char **argv)
74 {
75     int i, msgnum;
76     unsigned char *cp;
77     char *maildir, *datesw = NULL;
78     char *folder = NULL, buf[BUFSIZ], **argp;
79     char **arguments;
80     struct msgs_array msgs = { 0, 0, NULL };
81     struct msgs *mp;
82     struct smsg **dlist;
83
84 #ifdef LOCALE
85     setlocale(LC_ALL, "");
86 #endif
87     invo_name = r1bindex (argv[0], '/');
88
89     /* read user profile/context */
90     context_read();
91
92     arguments = getarguments (invo_name, argc, argv, 1);
93     argp = arguments;
94
95     /*
96      * Parse arguments
97      */
98     while ((cp = *argp++)) {
99         if (*cp == '-') {
100             switch (smatch (++cp, switches)) {
101             case AMBIGSW:
102                 ambigsw (cp, switches);
103                 done (1);
104             case UNKWNSW:
105                 adios (NULL, "-%s unknown", cp);
106
107             case HELPSW:
108                 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
109                         invo_name);
110                 print_help (buf, switches, 1);
111                 done (0);
112             case VERSIONSW:
113                 print_version(invo_name);
114                 done (0);
115
116             case DATESW:
117                 if (datesw)
118                     adios (NULL, "only one date field at a time");
119                 if (!(datesw = *argp++) || *datesw == '-')
120                     adios (NULL, "missing argument to %s", argp[-2]);
121                 continue;
122
123             case TEXTSW:
124                 if (subjsort)
125                     adios (NULL, "only one text field at a time");
126                 if (!(subjsort = *argp++) || *subjsort == '-')
127                     adios (NULL, "missing argument to %s", argp[-2]);
128                 continue;
129
130             case SUBJSW:
131                 subjsort = "subject";
132                 continue;
133             case NSUBJSW:
134                 subjsort = (char *)0;
135                 continue;
136
137             case LIMSW:
138                 if (!(cp = *argp++) || *cp == '-')
139                         adios (NULL, "missing argument to %s", argp[-2]);
140                 while (*cp == '0')
141                     cp++;               /* skip any leading zeros */
142                 if (!*cp) {             /* hit end of string */
143                     submajor++;         /* sort subject-major */
144                     continue;
145                 }
146                 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
147                     adios (NULL, "impossible limit %s", cp);
148                 datelimit *= 60*60*24;
149                 continue;
150             case NLIMSW:
151                 submajor = 0;   /* use date-major, but */
152                 datelimit = 0;  /* use no limit */
153                 continue;
154
155             case VERBSW:
156                 verbose++;
157                 continue;
158             case NVERBSW:
159                 verbose = 0;
160                 continue;
161
162             case ALLMSGS:
163                 allmsgs = 1;
164                 continue;
165             case NALLMSGS:
166                 allmsgs = 0;
167                 continue;
168             }
169         }
170         if (*cp == '+' || *cp == '@') {
171             if (folder)
172                 adios (NULL, "only one folder at a time!");
173             else
174                 folder = pluspath (cp);
175         } else
176                 app_msgarg(&msgs, cp);
177     }
178
179     if (!context_find ("path"))
180         free (path ("./", TFOLDER));
181     if (!msgs.size) {
182         if (allmsgs) {
183             app_msgarg(&msgs, "all");
184         } else {
185             adios (NULL, "must specify messages to sort with -noall");
186         }
187     }
188     if (!datesw)
189         datesw = "date";
190     if (!folder)
191         folder = getfolder (1);
192     maildir = m_maildir (folder);
193
194     if (chdir (maildir) == NOTOK)
195         adios (maildir, "unable to change directory to");
196
197     /* read folder and create message structure */
198     if (!(mp = folder_read (folder)))
199         adios (NULL, "unable to read folder %s", folder);
200
201     /* check for empty folder */
202     if (mp->nummsg == 0)
203         adios (NULL, "no messages in %s", folder);
204
205     /* parse all the message ranges/sequences and set SELECTED */
206     for (msgnum = 0; msgnum < msgs.size; msgnum++)
207         if (!m_convert (mp, msgs.msgs[msgnum]))
208             done (1);
209     seq_setprev (mp);   /* set the previous sequence */
210
211     if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
212         adios (NULL, "no messages to sort");
213
214     /*
215      * sort a list of pointers to our "messages to be sorted".
216      */
217     dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
218     for (i = 0; i < nmsgs; i++)
219         dlist[i] = &smsgs[i];
220     dlist[nmsgs] = 0;
221
222     if (verbose) {      /* announce what we're doing */
223         if (subjsort)
224             printf ("sorting by %s-major %s-minor\n",
225                 submajor ? subjsort : datesw,
226                 submajor ? datesw : subjsort);
227         else
228             printf ("sorting by datefield %s\n", datesw);
229     }
230
231     /* first sort by date, or by subject-major, date-minor */
232     qsort ((char *) dlist, nmsgs, sizeof(*dlist),
233             (qsort_comp) (submajor && subjsort ? txtsort : dsort));
234
235     /*
236      * if we're sorting on subject, we need another list
237      * in subject order, then a merge pass to collate the
238      * two sorts.
239      */
240     if (!submajor && subjsort) {        /* already date sorted */
241         struct smsg **slist, **flist;
242         register struct smsg ***il, **fp, **dp;
243
244         slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
245         memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
246         qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
247
248         /*
249          * make an inversion list so we can quickly find
250          * the collection of messages with the same subj
251          * given a message number.
252          */
253         il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
254         if (! il)
255             adios (NULL, "couldn't allocate msg list");
256         for (i = 0; i < nmsgs; i++)
257             il[slist[i]->s_msg] = &slist[i];
258         /*
259          * make up the final list, chronological but with
260          * all the same subjects grouped together.
261          */
262         flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
263         fp = flist;
264         for (dp = dlist; *dp;) {
265             register struct smsg **s = il[(*dp++)->s_msg];
266
267             /* see if we already did this guy */
268             if (! s)
269                 continue;
270
271             *fp++ = *s++;
272             /*
273              * take the next message(s) if there is one,
274              * its subject isn't null and its subject
275              * is the same as this one and it's not too
276              * far away in time.
277              */
278             while (*s && (*s)->s_subj[0] &&
279                    strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
280                    (datelimit == 0 ||
281                    (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
282                 il[(*s)->s_msg] = 0;
283                 *fp++ = *s++;
284             }
285         }
286         *fp = 0;
287         free (slist);
288         free (dlist);
289         dlist = flist;
290     }
291
292     /*
293      * At this point, dlist is a sorted array of pointers to smsg structures,
294      * each of which contains a message number.
295      */
296
297     rename_msgs (mp, dlist);
298
299     context_replace (pfolder, folder);  /* update current folder         */
300     seq_save (mp);                      /* synchronize message sequences */
301     context_save ();                    /* save the context file         */
302     folder_free (mp);                   /* free folder/message structure */
303     done (0);
304     return 1;
305 }
306
307 static int
308 read_hdrs (struct msgs *mp, char *datesw)
309 {
310     int msgnum;
311     struct tws tb;
312     register struct smsg *s;
313
314     twscopy (&tb, dlocaltimenow ());
315
316     smsgs = (struct smsg *)
317         calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
318             sizeof(*smsgs));
319     if (smsgs == NULL)
320         adios (NULL, "unable to allocate sort storage");
321
322     s = smsgs;
323     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
324         if (is_selected(mp, msgnum)) {
325             if (get_fields (datesw, msgnum, s)) {
326                 s->s_msg = msgnum;
327                 s++;
328             }
329         }
330     }
331     s->s_msg = 0;
332     return(s - smsgs);
333 }
334
335
336 /*
337  * Parse the message and get the data or subject field,
338  * if needed.
339  */
340
341 static int
342 get_fields (char *datesw, int msg, struct smsg *smsg)
343 {
344     register int state;
345     int compnum;
346     char *msgnam, buf[BUFSIZ], nam[NAMESZ];
347     register struct tws *tw;
348     register char *datecomp = NULL, *subjcomp = NULL;
349     register FILE *in;
350
351     if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
352         admonish (msgnam, "unable to read message");
353         return (0);
354     }
355     for (compnum = 1, state = FLD;;) {
356         switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
357         case FLD:
358         case FLDEOF:
359         case FLDPLUS:
360             compnum++;
361             if (!mh_strcasecmp (nam, datesw)) {
362                 datecomp = add (buf, datecomp);
363                 while (state == FLDPLUS) {
364                     state = m_getfld (state, nam, buf, sizeof(buf), in);
365                     datecomp = add (buf, datecomp);
366                 }
367                 if (!subjsort || subjcomp)
368                     break;
369             } else if (subjsort && !mh_strcasecmp (nam, subjsort)) {
370                 subjcomp = add (buf, subjcomp);
371                 while (state == FLDPLUS) {
372                     state = m_getfld (state, nam, buf, sizeof(buf), in);
373                     subjcomp = add (buf, subjcomp);
374                 }
375                 if (datecomp)
376                     break;
377             } else {
378                 /* just flush this guy */
379                 while (state == FLDPLUS)
380                     state = m_getfld (state, nam, buf, sizeof(buf), in);
381             }
382             continue;
383
384         case BODY:
385         case BODYEOF:
386         case FILEEOF:
387             break;
388
389         case LENERR:
390         case FMTERR:
391             if (state == LENERR || state == FMTERR)
392                 admonish (NULL, "format error in message %d (header #%d)",
393                       msg, compnum);
394             if (datecomp)
395                 free (datecomp);
396             if (subjcomp)
397                 free (subjcomp);
398             fclose (in);
399             return (0);
400
401         default:
402             adios (NULL, "internal error -- you lose");
403         }
404         break;
405     }
406
407     /*
408      * If no date component, then use the modification
409      * time of the file as its date
410      */
411     if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
412         struct stat st;
413
414         admonish (NULL, "can't parse %s field in message %d", datesw, msg);
415         fstat (fileno (in), &st);
416         smsg->s_clock = st.st_mtime;
417     } else {
418         smsg->s_clock = dmktime (tw);
419     }
420
421     if (subjsort) {
422         if (subjcomp) {
423             /*
424              * try to make the subject "canonical": delete
425              * leading "re:", everything but letters & smash
426              * letters to lower case.
427              */
428             register char  *cp, *cp2;
429             register unsigned char c;
430
431             cp = subjcomp;
432             cp2 = subjcomp;
433             if (strcmp (subjsort, "subject") == 0) {
434                 while ((c = *cp)) {
435                     if (! isspace(c)) {
436                         if(uprf(cp, "re:"))
437                             cp += 2;
438                         else
439                             break;
440                     }
441                     cp++;
442                 }
443             }
444
445             while ((c = *cp++)) {
446                 if (isalnum(c))
447                     *cp2++ = isupper(c) ? tolower(c) : c;
448             }
449
450             *cp2 = '\0';
451         }
452         else
453             subjcomp = "";
454
455         smsg->s_subj = subjcomp;
456     }
457     fclose (in);
458     if (datecomp)
459         free (datecomp);
460
461     return (1);
462 }
463
464 /*
465  * sort on dates.
466  */
467 static int
468 dsort (struct smsg **a, struct smsg **b)
469 {
470     if ((*a)->s_clock < (*b)->s_clock)
471         return (-1);
472     else if ((*a)->s_clock > (*b)->s_clock)
473         return (1);
474     else if ((*a)->s_msg < (*b)->s_msg)
475         return (-1);
476     else
477         return (1);
478 }
479
480 /*
481  * sort on subjects.
482  */
483 static int
484 subsort (struct smsg **a, struct smsg **b)
485 {
486     register int i;
487
488     if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
489         return (i);
490
491     return (dsort (a, b));
492 }
493
494 static int
495 txtsort (struct smsg **a, struct smsg **b)
496 {
497     register int i;
498
499     if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
500         return (i);
501     else if ((*a)->s_msg < (*b)->s_msg)
502         return (-1);
503     else
504         return (1);
505 }
506
507 static void
508 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
509 {
510     int nxt, old, new;
511     char *newname, oldname[BUFSIZ];
512     char newbuf[PATH_MAX + 1];
513
514     for (;;) {
515         nxt = mlist[msg] - smsgs;       /* mlist[msg] is a ptr into smsgs */
516         mlist[msg] = (struct smsg *)0;
517         old = smsgs[nxt].s_msg;
518         new = smsgs[msg].s_msg;
519         strncpy (oldname, m_name (old), sizeof(oldname));
520         newname = m_name (new);
521         if (verbose)
522             printf ("message %d becomes message %d\n", old, new);
523
524         (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
525         (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
526         ext_hook("ref-hook", oldname, newbuf);
527
528         if (rename (oldname, newname) == NOTOK)
529             adios (newname, "unable to rename %s to", oldname);
530
531         copy_msg_flags (mp, new, old);
532         if (mp->curmsg == old)
533             seq_setcur (mp, new);
534
535         if (nxt == endmsg)
536             break;
537
538         msg = nxt;
539     }
540 /*      if (nxt != endmsg); */
541 /*      rename_chain (mp, mlist, nxt, endmsg); */
542 }
543
544 static void
545 rename_msgs (struct msgs *mp, struct smsg **mlist)
546 {
547     int i, j, old, new;
548     seqset_t tmpset;
549     char f1[BUFSIZ], tmpfil[BUFSIZ];
550     char newbuf[PATH_MAX + 1];
551     struct smsg *sp;
552
553     strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
554
555     for (i = 0; i < nmsgs; i++) {
556         if (! (sp = mlist[i]))
557             continue;   /* did this one */
558
559         j = sp - smsgs;
560         if (j == i)
561             continue;   /* this one doesn't move */
562
563         /*
564          * the guy that was msg j is about to become msg i.
565          * rename 'j' to make a hole, then recursively rename
566          * guys to fill up the hole.
567          */
568         old = smsgs[j].s_msg;
569         new = smsgs[i].s_msg;
570         strncpy (f1, m_name (old), sizeof(f1));
571
572         if (verbose)
573             printf ("renaming message chain from %d to %d\n", old, new);
574
575         /*
576          *      Run the external hook to refile the old message as the
577          *      temporary message number that is off of the end of the
578          *      messages in the folder.
579          */
580
581         (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
582         (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
583         ext_hook("ref-hook", f1, newbuf);
584
585         if (rename (f1, tmpfil) == NOTOK)
586             adios (tmpfil, "unable to rename %s to ", f1);
587
588         get_msg_flags (mp, &tmpset, old);
589
590         rename_chain (mp, mlist, j, i);
591
592         /*
593          *      Run the external hook to refile the temorary message number
594          *      to the real place.
595          */
596
597         (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
598         ext_hook("ref-hook", newbuf, f1);
599
600         if (rename (tmpfil, m_name(new)) == NOTOK)
601             adios (m_name(new), "unable to rename %s to", tmpfil);
602
603         set_msg_flags (mp, &tmpset, new);
604         mp->msgflags |= SEQMOD;
605     }
606 }