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