45e2b292fea355c434f209e333323d272e7204ea
[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             if (submajor)
225                 printf ("sorting by %s\n", subjsort);
226             else
227                 printf ("sorting by %s-major %s-minor\n", subjsort, datesw);
228         else
229             printf ("sorting by datefield %s\n", datesw);
230     }
231
232     /* first sort by date, or by subject-major, date-minor */
233     qsort ((char *) dlist, nmsgs, sizeof(*dlist),
234             (qsort_comp) (submajor && subjsort ? txtsort : dsort));
235
236     /*
237      * if we're sorting on subject, we need another list
238      * in subject order, then a merge pass to collate the
239      * two sorts.
240      */
241     if (!submajor && subjsort) {        /* already date sorted */
242         struct smsg **slist, **flist;
243         register struct smsg ***il, **fp, **dp;
244
245         slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
246         memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
247         qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
248
249         /*
250          * make an inversion list so we can quickly find
251          * the collection of messages with the same subj
252          * given a message number.
253          */
254         il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
255         if (! il)
256             adios (NULL, "couldn't allocate msg list");
257         for (i = 0; i < nmsgs; i++)
258             il[slist[i]->s_msg] = &slist[i];
259         /*
260          * make up the final list, chronological but with
261          * all the same subjects grouped together.
262          */
263         flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
264         fp = flist;
265         for (dp = dlist; *dp;) {
266             register struct smsg **s = il[(*dp++)->s_msg];
267
268             /* see if we already did this guy */
269             if (! s)
270                 continue;
271
272             *fp++ = *s++;
273             /*
274              * take the next message(s) if there is one,
275              * its subject isn't null and its subject
276              * is the same as this one and it's not too
277              * far away in time.
278              */
279             while (*s && (*s)->s_subj[0] &&
280                    strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
281                    (datelimit == 0 ||
282                    (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
283                 il[(*s)->s_msg] = 0;
284                 *fp++ = *s++;
285             }
286         }
287         *fp = 0;
288         free (slist);
289         free (dlist);
290         dlist = flist;
291     }
292
293     /*
294      * At this point, dlist is a sorted array of pointers to smsg structures,
295      * each of which contains a message number.
296      */
297
298     rename_msgs (mp, dlist);
299
300     context_replace (pfolder, folder);  /* update current folder         */
301     seq_save (mp);                      /* synchronize message sequences */
302     context_save ();                    /* save the context file         */
303     folder_free (mp);                   /* free folder/message structure */
304     done (0);
305     return 1;
306 }
307
308 static int
309 read_hdrs (struct msgs *mp, char *datesw)
310 {
311     int msgnum;
312     struct tws tb;
313     register struct smsg *s;
314
315     twscopy (&tb, dlocaltimenow ());
316
317     smsgs = (struct smsg *)
318         calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
319             sizeof(*smsgs));
320     if (smsgs == NULL)
321         adios (NULL, "unable to allocate sort storage");
322
323     s = smsgs;
324     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
325         if (is_selected(mp, msgnum)) {
326             if (get_fields (datesw, msgnum, s)) {
327                 s->s_msg = msgnum;
328                 s++;
329             }
330         }
331     }
332     s->s_msg = 0;
333     return(s - smsgs);
334 }
335
336
337 /*
338  * Parse the message and get the data or subject field,
339  * if needed.
340  */
341
342 static int
343 get_fields (char *datesw, int msg, struct smsg *smsg)
344 {
345     register int state;
346     int compnum;
347     char *msgnam, buf[BUFSIZ], nam[NAMESZ];
348     register struct tws *tw;
349     register char *datecomp = NULL, *subjcomp = NULL;
350     register FILE *in;
351
352     if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
353         admonish (msgnam, "unable to read message");
354         return (0);
355     }
356     for (compnum = 1, state = FLD;;) {
357         switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
358         case FLD:
359         case FLDEOF:
360         case FLDPLUS:
361             compnum++;
362             if (!mh_strcasecmp (nam, datesw)) {
363                 datecomp = add (buf, datecomp);
364                 while (state == FLDPLUS) {
365                     state = m_getfld (state, nam, buf, sizeof(buf), in);
366                     datecomp = add (buf, datecomp);
367                 }
368                 if (!subjsort || subjcomp)
369                     break;
370             } else if (subjsort && !mh_strcasecmp (nam, subjsort)) {
371                 subjcomp = add (buf, subjcomp);
372                 while (state == FLDPLUS) {
373                     state = m_getfld (state, nam, buf, sizeof(buf), in);
374                     subjcomp = add (buf, subjcomp);
375                 }
376                 if (datecomp)
377                     break;
378             } else {
379                 /* just flush this guy */
380                 while (state == FLDPLUS)
381                     state = m_getfld (state, nam, buf, sizeof(buf), in);
382             }
383             continue;
384
385         case BODY:
386         case BODYEOF:
387         case FILEEOF:
388             break;
389
390         case LENERR:
391         case FMTERR:
392             if (state == LENERR || state == FMTERR)
393                 admonish (NULL, "format error in message %d (header #%d)",
394                       msg, compnum);
395             if (datecomp)
396                 free (datecomp);
397             if (subjcomp)
398                 free (subjcomp);
399             fclose (in);
400             return (0);
401
402         default:
403             adios (NULL, "internal error -- you lose");
404         }
405         break;
406     }
407
408     /*
409      * If no date component, then use the modification
410      * time of the file as its date
411      */
412     if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
413         struct stat st;
414
415         admonish (NULL, "can't parse %s field in message %d", datesw, msg);
416         fstat (fileno (in), &st);
417         smsg->s_clock = st.st_mtime;
418     } else {
419         smsg->s_clock = dmktime (tw);
420     }
421
422     if (subjsort) {
423         if (subjcomp) {
424             /*
425              * try to make the subject "canonical": delete
426              * leading "re:", everything but letters & smash
427              * letters to lower case.
428              */
429             register char  *cp, *cp2;
430             register unsigned char c;
431
432             cp = subjcomp;
433             cp2 = subjcomp;
434             if (strcmp (subjsort, "subject") == 0) {
435                 while ((c = *cp)) {
436                     if (! isspace(c)) {
437                         if(uprf(cp, "re:"))
438                             cp += 2;
439                         else
440                             break;
441                     }
442                     cp++;
443                 }
444             }
445
446             while ((c = *cp++)) {
447                 if (isalnum(c))
448                     *cp2++ = isupper(c) ? tolower(c) : c;
449             }
450
451             *cp2 = '\0';
452         }
453         else
454             subjcomp = "";
455
456         smsg->s_subj = subjcomp;
457     }
458     fclose (in);
459     if (datecomp)
460         free (datecomp);
461
462     return (1);
463 }
464
465 /*
466  * sort on dates.
467  */
468 static int
469 dsort (struct smsg **a, struct smsg **b)
470 {
471     if ((*a)->s_clock < (*b)->s_clock)
472         return (-1);
473     else if ((*a)->s_clock > (*b)->s_clock)
474         return (1);
475     else if ((*a)->s_msg < (*b)->s_msg)
476         return (-1);
477     else
478         return (1);
479 }
480
481 /*
482  * sort on subjects.
483  */
484 static int
485 subsort (struct smsg **a, struct smsg **b)
486 {
487     register int i;
488
489     if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
490         return (i);
491
492     return (dsort (a, b));
493 }
494
495 static int
496 txtsort (struct smsg **a, struct smsg **b)
497 {
498     register int i;
499
500     if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
501         return (i);
502     else if ((*a)->s_msg < (*b)->s_msg)
503         return (-1);
504     else
505         return (1);
506 }
507
508 static void
509 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
510 {
511     int nxt, old, new;
512     char *newname, oldname[BUFSIZ];
513     char newbuf[PATH_MAX + 1];
514
515     for (;;) {
516         nxt = mlist[msg] - smsgs;       /* mlist[msg] is a ptr into smsgs */
517         mlist[msg] = (struct smsg *)0;
518         old = smsgs[nxt].s_msg;
519         new = smsgs[msg].s_msg;
520         strncpy (oldname, m_name (old), sizeof(oldname));
521         newname = m_name (new);
522         if (verbose)
523             printf ("message %d becomes message %d\n", old, new);
524
525         (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
526         (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
527         ext_hook("ref-hook", oldname, newbuf);
528
529         if (rename (oldname, newname) == NOTOK)
530             adios (newname, "unable to rename %s to", oldname);
531
532         copy_msg_flags (mp, new, old);
533         if (mp->curmsg == old)
534             seq_setcur (mp, new);
535
536         if (nxt == endmsg)
537             break;
538
539         msg = nxt;
540     }
541 /*      if (nxt != endmsg); */
542 /*      rename_chain (mp, mlist, nxt, endmsg); */
543 }
544
545 static void
546 rename_msgs (struct msgs *mp, struct smsg **mlist)
547 {
548     int i, j, old, new;
549     seqset_t tmpset;
550     char f1[BUFSIZ], tmpfil[BUFSIZ];
551     char newbuf[PATH_MAX + 1];
552     struct smsg *sp;
553
554     strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
555
556     for (i = 0; i < nmsgs; i++) {
557         if (! (sp = mlist[i]))
558             continue;   /* did this one */
559
560         j = sp - smsgs;
561         if (j == i)
562             continue;   /* this one doesn't move */
563
564         /*
565          * the guy that was msg j is about to become msg i.
566          * rename 'j' to make a hole, then recursively rename
567          * guys to fill up the hole.
568          */
569         old = smsgs[j].s_msg;
570         new = smsgs[i].s_msg;
571         strncpy (f1, m_name (old), sizeof(f1));
572
573         if (verbose)
574             printf ("renaming message chain from %d to %d\n", old, new);
575
576         /*
577          *      Run the external hook to refile the old message as the
578          *      temporary message number that is off of the end of the
579          *      messages in the folder.
580          */
581
582         (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
583         (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
584         ext_hook("ref-hook", f1, newbuf);
585
586         if (rename (f1, tmpfil) == NOTOK)
587             adios (tmpfil, "unable to rename %s to ", f1);
588
589         get_msg_flags (mp, &tmpset, old);
590
591         rename_chain (mp, mlist, j, i);
592
593         /*
594          *      Run the external hook to refile the temorary message number
595          *      to the real place.
596          */
597
598         (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
599         ext_hook("ref-hook", newbuf, f1);
600
601         if (rename (tmpfil, m_name(new)) == NOTOK)
602             adios (m_name(new), "unable to rename %s to", tmpfil);
603
604         set_msg_flags (mp, &tmpset, new);
605         mp->msgflags |= SEQMOD;
606     }
607 }