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 */
225 printf ("sorting by %s\n", subjsort);
227 printf ("sorting by %s-major %s-minor\n", subjsort, datesw);
229 printf ("sorting by datefield %s\n", datesw);
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));
237 * if we're sorting on subject, we need another list
238 * in subject order, then a merge pass to collate the
241 if (!submajor && subjsort) { /* already date sorted */
242 struct smsg **slist, **flist;
243 register struct smsg ***il, **fp, **dp;
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);
250 * make an inversion list so we can quickly find
251 * the collection of messages with the same subj
252 * given a message number.
254 il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
256 adios (NULL, "couldn't allocate msg list");
257 for (i = 0; i < nmsgs; i++)
258 il[slist[i]->s_msg] = &slist[i];
260 * make up the final list, chronological but with
261 * all the same subjects grouped together.
263 flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
265 for (dp = dlist; *dp;) {
266 register struct smsg **s = il[(*dp++)->s_msg];
268 /* see if we already did this guy */
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
279 while (*s && (*s)->s_subj[0] &&
280 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
282 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
294 * At this point, dlist is a sorted array of pointers to smsg structures,
295 * each of which contains a message number.
298 rename_msgs (mp, dlist);
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 */
309 read_hdrs (struct msgs *mp, char *datesw)
313 register struct smsg *s;
315 twscopy (&tb, dlocaltimenow ());
317 smsgs = (struct smsg *)
318 calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
321 adios (NULL, "unable to allocate sort storage");
324 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
325 if (is_selected(mp, msgnum)) {
326 if (get_fields (datesw, msgnum, s)) {
338 * Parse the message and get the data or subject field,
343 get_fields (char *datesw, int msg, struct smsg *smsg)
347 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
348 register struct tws *tw;
349 register char *datecomp = NULL, *subjcomp = NULL;
352 if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
353 admonish (msgnam, "unable to read message");
356 for (compnum = 1, state = FLD;;) {
357 switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
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);
368 if (!subjsort || subjcomp)
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);
379 /* just flush this guy */
380 while (state == FLDPLUS)
381 state = m_getfld (state, nam, buf, sizeof(buf), in);
392 if (state == LENERR || state == FMTERR)
393 admonish (NULL, "format error in message %d (header #%d)",
403 adios (NULL, "internal error -- you lose");
409 * If no date component, then use the modification
410 * time of the file as its date
412 if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
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;
419 smsg->s_clock = dmktime (tw);
425 * try to make the subject "canonical": delete
426 * leading "re:", everything but letters & smash
427 * letters to lower case.
429 register char *cp, *cp2;
430 register unsigned char c;
434 if (strcmp (subjsort, "subject") == 0) {
446 while ((c = *cp++)) {
448 *cp2++ = isupper(c) ? tolower(c) : c;
456 smsg->s_subj = subjcomp;
469 dsort (struct smsg **a, struct smsg **b)
471 if ((*a)->s_clock < (*b)->s_clock)
473 else if ((*a)->s_clock > (*b)->s_clock)
475 else if ((*a)->s_msg < (*b)->s_msg)
485 subsort (struct smsg **a, struct smsg **b)
489 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
492 return (dsort (a, b));
496 txtsort (struct smsg **a, struct smsg **b)
500 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
502 else if ((*a)->s_msg < (*b)->s_msg)
509 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
512 char *newname, oldname[BUFSIZ];
513 char newbuf[PATH_MAX + 1];
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);
523 printf ("message %d becomes message %d\n", old, new);
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);
529 if (rename (oldname, newname) == NOTOK)
530 adios (newname, "unable to rename %s to", oldname);
532 copy_msg_flags (mp, new, old);
533 if (mp->curmsg == old)
534 seq_setcur (mp, new);
541 /* if (nxt != endmsg); */
542 /* rename_chain (mp, mlist, nxt, endmsg); */
546 rename_msgs (struct msgs *mp, struct smsg **mlist)
550 char f1[BUFSIZ], tmpfil[BUFSIZ];
551 char newbuf[PATH_MAX + 1];
554 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
556 for (i = 0; i < nmsgs; i++) {
557 if (! (sp = mlist[i]))
558 continue; /* did this one */
562 continue; /* this one doesn't move */
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.
569 old = smsgs[j].s_msg;
570 new = smsgs[i].s_msg;
571 strncpy (f1, m_name (old), sizeof(f1));
574 printf ("renaming message chain from %d to %d\n", old, new);
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.
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);
586 if (rename (f1, tmpfil) == NOTOK)
587 adios (tmpfil, "unable to rename %s to ", f1);
589 get_msg_flags (mp, &tmpset, old);
591 rename_chain (mp, mlist, j, i);
594 * Run the external hook to refile the temorary message number
598 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
599 ext_hook("ref-hook", newbuf, f1);
601 if (rename (tmpfil, m_name(new)) == NOTOK)
602 adios (m_name(new), "unable to rename %s to", tmpfil);
604 set_msg_flags (mp, &tmpset, new);
605 mp->msgflags |= SEQMOD;