3 * sortm.c -- sort messages in a folder by date/time
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.
14 static struct swit switches[] = {
16 { "datefield field", 0 },
18 { "textfield field", 0 },
22 { "subject", -3 }, /* backward-compatibility */
48 static struct smsg *smsgs;
51 char *subjsort = (char *) 0; /* sort on subject if != 0 */
53 int submajor = 0; /* if true, sort on subject-major */
57 /* This keeps compiler happy on calls to qsort */
58 typedef int (*qsort_comp) (const void *, const void *);
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 **);
73 main (int argc, char **argv)
77 char *maildir, *datesw = NULL;
78 char *folder = NULL, buf[BUFSIZ], **argp;
80 struct msgs_array msgs = { 0, 0, NULL };
85 setlocale(LC_ALL, "");
87 invo_name = r1bindex (argv[0], '/');
89 /* read user profile/context */
92 arguments = getarguments (invo_name, argc, argv, 1);
98 while ((cp = *argp++)) {
100 switch (smatch (++cp, switches)) {
102 ambigsw (cp, switches);
105 adios (NULL, "-%s unknown", cp);
108 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
110 print_help (buf, switches, 1);
113 print_version(invo_name);
118 adios (NULL, "only one date field at a time");
119 if (!(datesw = *argp++) || *datesw == '-')
120 adios (NULL, "missing argument to %s", argp[-2]);
125 adios (NULL, "only one text field at a time");
126 if (!(subjsort = *argp++) || *subjsort == '-')
127 adios (NULL, "missing argument to %s", argp[-2]);
131 subjsort = "subject";
134 subjsort = (char *)0;
138 if (!(cp = *argp++) || *cp == '-')
139 adios (NULL, "missing argument to %s", argp[-2]);
141 cp++; /* skip any leading zeros */
142 if (!*cp) { /* hit end of string */
143 submajor++; /* sort subject-major */
146 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
147 adios (NULL, "impossible limit %s", cp);
148 datelimit *= 60*60*24;
151 submajor = 0; /* use date-major, but */
152 datelimit = 0; /* use no limit */
170 if (*cp == '+' || *cp == '@') {
172 adios (NULL, "only one folder at a time!");
174 folder = pluspath (cp);
176 app_msgarg(&msgs, cp);
179 if (!context_find ("path"))
180 free (path ("./", TFOLDER));
183 app_msgarg(&msgs, "all");
185 adios (NULL, "must specify messages to sort with -noall");
191 folder = getfolder (1);
192 maildir = m_maildir (folder);
194 if (chdir (maildir) == NOTOK)
195 adios (maildir, "unable to change directory to");
197 /* read folder and create message structure */
198 if (!(mp = folder_read (folder)))
199 adios (NULL, "unable to read folder %s", folder);
201 /* check for empty folder */
203 adios (NULL, "no messages in %s", folder);
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]))
209 seq_setprev (mp); /* set the previous sequence */
211 if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
212 adios (NULL, "no messages to sort");
215 * sort a list of pointers to our "messages to be sorted".
217 dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
218 for (i = 0; i < nmsgs; i++)
219 dlist[i] = &smsgs[i];
222 if (verbose) { /* announce what we're doing */
224 printf ("sorting by %s-major %s-minor\n",
225 submajor ? subjsort : datesw,
226 submajor ? datesw : subjsort);
228 printf ("sorting by datefield %s\n", datesw);
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));
236 * if we're sorting on subject, we need another list
237 * in subject order, then a merge pass to collate the
240 if (!submajor && subjsort) { /* already date sorted */
241 struct smsg **slist, **flist;
242 register struct smsg ***il, **fp, **dp;
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);
249 * make an inversion list so we can quickly find
250 * the collection of messages with the same subj
251 * given a message number.
253 il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
255 adios (NULL, "couldn't allocate msg list");
256 for (i = 0; i < nmsgs; i++)
257 il[slist[i]->s_msg] = &slist[i];
259 * make up the final list, chronological but with
260 * all the same subjects grouped together.
262 flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
264 for (dp = dlist; *dp;) {
265 register struct smsg **s = il[(*dp++)->s_msg];
267 /* see if we already did this guy */
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
278 while (*s && (*s)->s_subj[0] &&
279 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
281 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
293 * At this point, dlist is a sorted array of pointers to smsg structures,
294 * each of which contains a message number.
297 rename_msgs (mp, dlist);
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 */
308 read_hdrs (struct msgs *mp, char *datesw)
312 register struct smsg *s;
314 twscopy (&tb, dlocaltimenow ());
316 smsgs = (struct smsg *)
317 calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
320 adios (NULL, "unable to allocate sort storage");
323 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
324 if (is_selected(mp, msgnum)) {
325 if (get_fields (datesw, msgnum, s)) {
337 * Parse the message and get the data or subject field,
342 get_fields (char *datesw, int msg, struct smsg *smsg)
346 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
347 register struct tws *tw;
348 register char *datecomp = NULL, *subjcomp = NULL;
351 if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
352 admonish (msgnam, "unable to read message");
355 for (compnum = 1, state = FLD;;) {
356 switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
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);
367 if (!subjsort || subjcomp)
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);
378 /* just flush this guy */
379 while (state == FLDPLUS)
380 state = m_getfld (state, nam, buf, sizeof(buf), in);
391 if (state == LENERR || state == FMTERR)
392 admonish (NULL, "format error in message %d (header #%d)",
402 adios (NULL, "internal error -- you lose");
408 * If no date component, then use the modification
409 * time of the file as its date
411 if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
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;
418 smsg->s_clock = dmktime (tw);
424 * try to make the subject "canonical": delete
425 * leading "re:", everything but letters & smash
426 * letters to lower case.
428 register char *cp, *cp2;
429 register unsigned char c;
433 if (strcmp (subjsort, "subject") == 0) {
445 while ((c = *cp++)) {
447 *cp2++ = isupper(c) ? tolower(c) : c;
455 smsg->s_subj = subjcomp;
468 dsort (struct smsg **a, struct smsg **b)
470 if ((*a)->s_clock < (*b)->s_clock)
472 else if ((*a)->s_clock > (*b)->s_clock)
474 else if ((*a)->s_msg < (*b)->s_msg)
484 subsort (struct smsg **a, struct smsg **b)
488 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
491 return (dsort (a, b));
495 txtsort (struct smsg **a, struct smsg **b)
499 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
501 else if ((*a)->s_msg < (*b)->s_msg)
508 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
511 char *newname, oldname[BUFSIZ];
512 char newbuf[PATH_MAX + 1];
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);
522 printf ("message %d becomes message %d\n", old, new);
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);
528 if (rename (oldname, newname) == NOTOK)
529 adios (newname, "unable to rename %s to", oldname);
531 copy_msg_flags (mp, new, old);
532 if (mp->curmsg == old)
533 seq_setcur (mp, new);
540 /* if (nxt != endmsg); */
541 /* rename_chain (mp, mlist, nxt, endmsg); */
545 rename_msgs (struct msgs *mp, struct smsg **mlist)
549 char f1[BUFSIZ], tmpfil[BUFSIZ];
550 char newbuf[PATH_MAX + 1];
553 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
555 for (i = 0; i < nmsgs; i++) {
556 if (! (sp = mlist[i]))
557 continue; /* did this one */
561 continue; /* this one doesn't move */
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.
568 old = smsgs[j].s_msg;
569 new = smsgs[i].s_msg;
570 strncpy (f1, m_name (old), sizeof(f1));
573 printf ("renaming message chain from %d to %d\n", old, new);
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.
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);
585 if (rename (f1, tmpfil) == NOTOK)
586 adios (tmpfil, "unable to rename %s to ", f1);
588 get_msg_flags (mp, &tmpset, old);
590 rename_chain (mp, mlist, j, i);
593 * Run the external hook to refile the temorary message number
597 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
598 ext_hook("ref-hook", newbuf, f1);
600 if (rename (tmpfil, m_name(new)) == NOTOK)
601 adios (m_name(new), "unable to rename %s to", tmpfil);
603 set_msg_flags (mp, &tmpset, new);
604 mp->msgflags |= SEQMOD;