3 * sortm.c -- sort messages in a folder by date/time
7 * This code is Copyright (c) 2002, by the authors of nmh. See the
8 * COPYRIGHT file in the root directory of the nmh distribution for
9 * complete copyright information.
16 * We allocate space for messages (msgs array)
17 * this number of elements at a time.
22 static struct swit switches[] = {
24 { "datefield field", 0 },
26 { "textfield field", 0 },
30 { "subject", -3 }, /* backward-compatibility */
52 static struct smsg *smsgs;
55 char *subjsort = (char *) 0; /* sort on subject if != 0 */
56 unsigned long datelimit = 0;
57 int submajor = 0; /* if true, sort on subject-major */
60 /* This keeps compiler happy on calls to qsort */
61 typedef int (*qsort_comp) (const void *, const void *);
66 static int read_hdrs (struct msgs *, char *);
67 static int get_fields (char *, int, struct smsg *);
68 static int dsort (struct smsg **, struct smsg **);
69 static int subsort (struct smsg **, struct smsg **);
70 static int txtsort (struct smsg **, struct smsg **);
71 static void rename_chain (struct msgs *, struct smsg **, int, int);
72 static void rename_msgs (struct msgs *, struct smsg **);
76 main (int argc, char **argv)
78 int nummsgs, maxmsgs, i, msgnum;
79 char *cp, *maildir, *datesw = NULL;
80 char *folder = NULL, buf[BUFSIZ], **argp;
81 char **arguments, **msgs;
86 setlocale(LC_ALL, "");
88 invo_name = r1bindex (argv[0], '/');
90 /* read user profile/context */
93 arguments = getarguments (invo_name, argc, argv, 1);
97 * Allocate the initial space to record message
102 if (!(msgs = (char **) malloc ((size_t) (maxmsgs * sizeof(*msgs)))))
103 adios (NULL, "unable to allocate storage");
108 while ((cp = *argp++)) {
110 switch (smatch (++cp, switches)) {
112 ambigsw (cp, switches);
115 adios (NULL, "-%s unknown", cp);
118 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
120 print_help (buf, switches, 1);
123 print_version(invo_name);
128 adios (NULL, "only one date field at a time");
129 if (!(datesw = *argp++) || *datesw == '-')
130 adios (NULL, "missing argument to %s", argp[-2]);
135 adios (NULL, "only one text field at a time");
136 if (!(subjsort = *argp++) || *subjsort == '-')
137 adios (NULL, "missing argument to %s", argp[-2]);
141 subjsort = "subject";
144 subjsort = (char *)0;
148 if (!(cp = *argp++) || *cp == '-')
149 adios (NULL, "missing argument to %s", argp[-2]);
151 cp++; /* skip any leading zeros */
152 if (!*cp) { /* hit end of string */
153 submajor++; /* sort subject-major */
156 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
157 adios (NULL, "impossible limit %s", cp);
158 datelimit *= 60*60*24;
161 submajor = 0; /* use date-major, but */
162 datelimit = 0; /* use no limit */
173 if (*cp == '+' || *cp == '@') {
175 adios (NULL, "only one folder at a time!");
177 folder = path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
180 * Check if we need to allocate more space
181 * for message names/ranges.
183 if (nummsgs >= maxmsgs) {
185 if (!(msgs = (char **) realloc (msgs,
186 (size_t) (maxmsgs * sizeof(*msgs)))))
187 adios (NULL, "unable to reallocate msgs storage");
189 msgs[nummsgs++] = cp;
193 if (!context_find ("path"))
194 free (path ("./", TFOLDER));
196 msgs[nummsgs++] = "all";
200 folder = getfolder (1);
201 maildir = m_maildir (folder);
203 if (chdir (maildir) == NOTOK)
204 adios (maildir, "unable to change directory to");
206 /* read folder and create message structure */
207 if (!(mp = folder_read (folder)))
208 adios (NULL, "unable to read folder %s", folder);
210 /* check for empty folder */
212 adios (NULL, "no messages in %s", folder);
214 /* parse all the message ranges/sequences and set SELECTED */
215 for (msgnum = 0; msgnum < nummsgs; msgnum++)
216 if (!m_convert (mp, msgs[msgnum]))
218 seq_setprev (mp); /* set the previous sequence */
220 if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
221 adios (NULL, "no messages to sort");
224 * sort a list of pointers to our "messages to be sorted".
226 dlist = (struct smsg **) malloc ((nmsgs+1) * sizeof(*dlist));
228 adios (NULL, "couldn't allocate sort memory");
229 for (i = 0; i < nmsgs; i++)
230 dlist[i] = &smsgs[i];
233 if (verbose) { /* announce what we're doing */
235 printf ("sorting by %s-major %s-minor\n",
236 submajor ? subjsort : datesw,
237 submajor ? datesw : subjsort);
239 printf ("sorting by datefield %s\n", datesw);
242 /* first sort by date, or by subject-major, date-minor */
243 qsort ((char *) dlist, nmsgs, sizeof(*dlist),
244 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
247 * if we're sorting on subject, we need another list
248 * in subject order, then a merge pass to collate the
251 if (!submajor && subjsort) { /* already date sorted */
252 struct smsg **slist, **flist;
253 register struct smsg ***il, **fp, **dp;
255 slist = (struct smsg **) malloc ((nmsgs+1) * sizeof(*slist));
257 adios (NULL, "couldn't allocate sort memory");
258 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
259 qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
262 * make an inversion list so we can quickly find
263 * the collection of messages with the same subj
264 * given a message number.
266 il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
268 adios (NULL, "couldn't allocate msg list");
269 for (i = 0; i < nmsgs; i++)
270 il[slist[i]->s_msg] = &slist[i];
272 * make up the final list, chronological but with
273 * all the same subjects grouped together.
275 flist = (struct smsg **) malloc ((nmsgs+1) * sizeof(*flist));
277 adios (NULL, "couldn't allocate msg list");
279 for (dp = dlist; *dp;) {
280 register struct smsg **s = il[(*dp++)->s_msg];
282 /* see if we already did this guy */
288 * take the next message(s) if there is one,
289 * its subject isn't null and its subject
290 * is the same as this one and it's not too
293 while (*s && (*s)->s_subj[0] &&
294 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
296 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
308 * At this point, dlist is a sorted array of pointers to smsg structures,
309 * each of which contains a message number.
312 rename_msgs (mp, dlist);
314 context_replace (pfolder, folder); /* update current folder */
315 seq_save (mp); /* synchronize message sequences */
316 context_save (); /* save the context file */
317 folder_free (mp); /* free folder/message structure */
322 read_hdrs (struct msgs *mp, char *datesw)
326 register struct smsg *s;
328 twscopy (&tb, dlocaltimenow ());
330 smsgs = (struct smsg *)
331 calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
334 adios (NULL, "unable to allocate sort storage");
337 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
338 if (is_selected(mp, msgnum)) {
339 if (get_fields (datesw, msgnum, s)) {
351 * Parse the message and get the data or subject field,
356 get_fields (char *datesw, int msg, struct smsg *smsg)
360 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
361 register struct tws *tw;
362 register char *datecomp = NULL, *subjcomp = NULL;
365 if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
366 admonish (msgnam, "unable to read message");
369 for (compnum = 1, state = FLD;;) {
370 switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
375 if (!strcasecmp (nam, datesw)) {
376 datecomp = add (buf, datecomp);
377 while (state == FLDPLUS) {
378 state = m_getfld (state, nam, buf, sizeof(buf), in);
379 datecomp = add (buf, datecomp);
381 if (!subjsort || subjcomp)
383 } else if (subjsort && !strcasecmp (nam, subjsort)) {
384 subjcomp = add (buf, subjcomp);
385 while (state == FLDPLUS) {
386 state = m_getfld (state, nam, buf, sizeof(buf), in);
387 subjcomp = add (buf, subjcomp);
392 /* just flush this guy */
393 while (state == FLDPLUS)
394 state = m_getfld (state, nam, buf, sizeof(buf), in);
405 if (state == LENERR || state == FMTERR)
406 admonish (NULL, "format error in message %d (header #%d)",
416 adios (NULL, "internal error -- you lose");
422 * If no date component, then use the modification
423 * time of the file as its date
425 if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
428 admonish (NULL, "can't parse %s field in message %d", datesw, msg);
429 fstat (fileno (in), &st);
430 smsg->s_clock = st.st_mtime;
432 smsg->s_clock = dmktime (tw);
438 * try to make the subject "canonical": delete
439 * leading "re:", everything but letters & smash
440 * letters to lower case.
442 register char *cp, *cp2, c;
446 if (strcmp (subjsort, "subject") == 0) {
458 while ((c = *cp++)) {
460 *cp2++ = isupper(c) ? tolower(c) : c;
468 smsg->s_subj = subjcomp;
481 dsort (struct smsg **a, struct smsg **b)
483 if ((*a)->s_clock < (*b)->s_clock)
485 else if ((*a)->s_clock > (*b)->s_clock)
487 else if ((*a)->s_msg < (*b)->s_msg)
497 subsort (struct smsg **a, struct smsg **b)
501 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
504 return (dsort (a, b));
508 txtsort (struct smsg **a, struct smsg **b)
512 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
514 else if ((*a)->s_msg < (*b)->s_msg)
521 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
524 char *newname, oldname[BUFSIZ];
525 char newbuf[MAXPATHLEN + 1];
528 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
529 mlist[msg] = (struct smsg *)0;
530 old = smsgs[nxt].s_msg;
531 new = smsgs[msg].s_msg;
532 strncpy (oldname, m_name (old), sizeof(oldname));
533 newname = m_name (new);
535 printf ("message %d becomes message %d\n", old, new);
537 (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
538 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
539 ext_hook("ref-hook", oldname, newbuf);
541 if (rename (oldname, newname) == NOTOK)
542 adios (newname, "unable to rename %s to", oldname);
544 copy_msg_flags (mp, new, old);
545 if (mp->curmsg == old)
546 seq_setcur (mp, new);
553 /* if (nxt != endmsg); */
554 /* rename_chain (mp, mlist, nxt, endmsg); */
558 rename_msgs (struct msgs *mp, struct smsg **mlist)
562 char f1[BUFSIZ], tmpfil[BUFSIZ];
563 char newbuf[MAXPATHLEN + 1];
566 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
568 for (i = 0; i < nmsgs; i++) {
569 if (! (sp = mlist[i]))
570 continue; /* did this one */
574 continue; /* this one doesn't move */
577 * the guy that was msg j is about to become msg i.
578 * rename 'j' to make a hole, then recursively rename
579 * guys to fill up the hole.
581 old = smsgs[j].s_msg;
582 new = smsgs[i].s_msg;
583 strncpy (f1, m_name (old), sizeof(f1));
586 printf ("renaming message chain from %d to %d\n", old, new);
589 * Run the external hook to refile the old message as the
590 * temporary message number that is off of the end of the
591 * messages in the folder.
594 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
595 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
596 ext_hook("ref-hook", f1, newbuf);
598 if (rename (f1, tmpfil) == NOTOK)
599 adios (tmpfil, "unable to rename %s to ", f1);
601 get_msg_flags (mp, &tmpset, old);
603 rename_chain (mp, mlist, j, i);
606 * Run the external hook to refile the temorary message number
610 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
611 ext_hook("ref-hook", newbuf, f1);
613 if (rename (tmpfil, m_name(new)) == NOTOK)
614 adios (m_name(new), "unable to rename %s to", tmpfil);
616 set_msg_flags (mp, &tmpset, new);
617 mp->msgflags |= SEQMOD;