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 static struct swit switches[] = {
18 { "datefield field", 0 },
20 { "textfield field", 0 },
24 { "subject", -3 }, /* backward-compatibility */
46 static struct smsg *smsgs;
49 char *subjsort = (char *) 0; /* sort on subject if != 0 */
50 unsigned long datelimit = 0;
51 int submajor = 0; /* if true, sort on subject-major */
54 /* This keeps compiler happy on calls to qsort */
55 typedef int (*qsort_comp) (const void *, const void *);
60 static int read_hdrs (struct msgs *, char *);
61 static int get_fields (char *, int, struct smsg *);
62 static int dsort (struct smsg **, struct smsg **);
63 static int subsort (struct smsg **, struct smsg **);
64 static int txtsort (struct smsg **, struct smsg **);
65 static void rename_chain (struct msgs *, struct smsg **, int, int);
66 static void rename_msgs (struct msgs *, struct smsg **);
70 main (int argc, char **argv)
74 char *maildir, *datesw = NULL;
75 char *folder = NULL, buf[BUFSIZ], **argp;
77 struct msgs_array msgs = { 0, 0, NULL };
82 setlocale(LC_ALL, "");
84 invo_name = r1bindex (argv[0], '/');
86 /* read user profile/context */
89 arguments = getarguments (invo_name, argc, argv, 1);
95 while ((cp = *argp++)) {
97 switch (smatch (++cp, switches)) {
99 ambigsw (cp, switches);
102 adios (NULL, "-%s unknown", cp);
105 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
107 print_help (buf, switches, 1);
110 print_version(invo_name);
115 adios (NULL, "only one date field at a time");
116 if (!(datesw = *argp++) || *datesw == '-')
117 adios (NULL, "missing argument to %s", argp[-2]);
122 adios (NULL, "only one text field at a time");
123 if (!(subjsort = *argp++) || *subjsort == '-')
124 adios (NULL, "missing argument to %s", argp[-2]);
128 subjsort = "subject";
131 subjsort = (char *)0;
135 if (!(cp = *argp++) || *cp == '-')
136 adios (NULL, "missing argument to %s", argp[-2]);
138 cp++; /* skip any leading zeros */
139 if (!*cp) { /* hit end of string */
140 submajor++; /* sort subject-major */
143 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
144 adios (NULL, "impossible limit %s", cp);
145 datelimit *= 60*60*24;
148 submajor = 0; /* use date-major, but */
149 datelimit = 0; /* use no limit */
160 if (*cp == '+' || *cp == '@') {
162 adios (NULL, "only one folder at a time!");
164 folder = pluspath (cp);
166 app_msgarg(&msgs, cp);
169 if (!context_find ("path"))
170 free (path ("./", TFOLDER));
172 app_msgarg(&msgs, "all");
176 folder = getfolder (1);
177 maildir = m_maildir (folder);
179 if (chdir (maildir) == NOTOK)
180 adios (maildir, "unable to change directory to");
182 /* read folder and create message structure */
183 if (!(mp = folder_read (folder)))
184 adios (NULL, "unable to read folder %s", folder);
186 /* check for empty folder */
188 adios (NULL, "no messages in %s", folder);
190 /* parse all the message ranges/sequences and set SELECTED */
191 for (msgnum = 0; msgnum < msgs.size; msgnum++)
192 if (!m_convert (mp, msgs.msgs[msgnum]))
194 seq_setprev (mp); /* set the previous sequence */
196 if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
197 adios (NULL, "no messages to sort");
200 * sort a list of pointers to our "messages to be sorted".
202 dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
203 for (i = 0; i < nmsgs; i++)
204 dlist[i] = &smsgs[i];
207 if (verbose) { /* announce what we're doing */
209 printf ("sorting by %s-major %s-minor\n",
210 submajor ? subjsort : datesw,
211 submajor ? datesw : subjsort);
213 printf ("sorting by datefield %s\n", datesw);
216 /* first sort by date, or by subject-major, date-minor */
217 qsort ((char *) dlist, nmsgs, sizeof(*dlist),
218 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
221 * if we're sorting on subject, we need another list
222 * in subject order, then a merge pass to collate the
225 if (!submajor && subjsort) { /* already date sorted */
226 struct smsg **slist, **flist;
227 register struct smsg ***il, **fp, **dp;
229 slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
230 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
231 qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
234 * make an inversion list so we can quickly find
235 * the collection of messages with the same subj
236 * given a message number.
238 il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
240 adios (NULL, "couldn't allocate msg list");
241 for (i = 0; i < nmsgs; i++)
242 il[slist[i]->s_msg] = &slist[i];
244 * make up the final list, chronological but with
245 * all the same subjects grouped together.
247 flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
249 for (dp = dlist; *dp;) {
250 register struct smsg **s = il[(*dp++)->s_msg];
252 /* see if we already did this guy */
258 * take the next message(s) if there is one,
259 * its subject isn't null and its subject
260 * is the same as this one and it's not too
263 while (*s && (*s)->s_subj[0] &&
264 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
266 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
278 * At this point, dlist is a sorted array of pointers to smsg structures,
279 * each of which contains a message number.
282 rename_msgs (mp, dlist);
284 context_replace (pfolder, folder); /* update current folder */
285 seq_save (mp); /* synchronize message sequences */
286 context_save (); /* save the context file */
287 folder_free (mp); /* free folder/message structure */
293 read_hdrs (struct msgs *mp, char *datesw)
297 register struct smsg *s;
299 twscopy (&tb, dlocaltimenow ());
301 smsgs = (struct smsg *)
302 calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
305 adios (NULL, "unable to allocate sort storage");
308 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
309 if (is_selected(mp, msgnum)) {
310 if (get_fields (datesw, msgnum, s)) {
322 * Parse the message and get the data or subject field,
327 get_fields (char *datesw, int msg, struct smsg *smsg)
331 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
332 register struct tws *tw;
333 register char *datecomp = NULL, *subjcomp = NULL;
336 if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
337 admonish (msgnam, "unable to read message");
340 for (compnum = 1, state = FLD;;) {
341 switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
346 if (!mh_strcasecmp (nam, datesw)) {
347 datecomp = add (buf, datecomp);
348 while (state == FLDPLUS) {
349 state = m_getfld (state, nam, buf, sizeof(buf), in);
350 datecomp = add (buf, datecomp);
352 if (!subjsort || subjcomp)
354 } else if (subjsort && !mh_strcasecmp (nam, subjsort)) {
355 subjcomp = add (buf, subjcomp);
356 while (state == FLDPLUS) {
357 state = m_getfld (state, nam, buf, sizeof(buf), in);
358 subjcomp = add (buf, subjcomp);
363 /* just flush this guy */
364 while (state == FLDPLUS)
365 state = m_getfld (state, nam, buf, sizeof(buf), in);
376 if (state == LENERR || state == FMTERR)
377 admonish (NULL, "format error in message %d (header #%d)",
387 adios (NULL, "internal error -- you lose");
393 * If no date component, then use the modification
394 * time of the file as its date
396 if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
399 admonish (NULL, "can't parse %s field in message %d", datesw, msg);
400 fstat (fileno (in), &st);
401 smsg->s_clock = st.st_mtime;
403 smsg->s_clock = dmktime (tw);
409 * try to make the subject "canonical": delete
410 * leading "re:", everything but letters & smash
411 * letters to lower case.
413 register char *cp, *cp2;
414 register unsigned char c;
418 if (strcmp (subjsort, "subject") == 0) {
430 while ((c = *cp++)) {
432 *cp2++ = isupper(c) ? tolower(c) : c;
440 smsg->s_subj = subjcomp;
453 dsort (struct smsg **a, struct smsg **b)
455 if ((*a)->s_clock < (*b)->s_clock)
457 else if ((*a)->s_clock > (*b)->s_clock)
459 else if ((*a)->s_msg < (*b)->s_msg)
469 subsort (struct smsg **a, struct smsg **b)
473 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
476 return (dsort (a, b));
480 txtsort (struct smsg **a, struct smsg **b)
484 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
486 else if ((*a)->s_msg < (*b)->s_msg)
493 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
496 char *newname, oldname[BUFSIZ];
497 char newbuf[MAXPATHLEN + 1];
500 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
501 mlist[msg] = (struct smsg *)0;
502 old = smsgs[nxt].s_msg;
503 new = smsgs[msg].s_msg;
504 strncpy (oldname, m_name (old), sizeof(oldname));
505 newname = m_name (new);
507 printf ("message %d becomes message %d\n", old, new);
509 (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
510 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
511 ext_hook("ref-hook", oldname, newbuf);
513 if (rename (oldname, newname) == NOTOK)
514 adios (newname, "unable to rename %s to", oldname);
516 copy_msg_flags (mp, new, old);
517 if (mp->curmsg == old)
518 seq_setcur (mp, new);
525 /* if (nxt != endmsg); */
526 /* rename_chain (mp, mlist, nxt, endmsg); */
530 rename_msgs (struct msgs *mp, struct smsg **mlist)
534 char f1[BUFSIZ], tmpfil[BUFSIZ];
535 char newbuf[MAXPATHLEN + 1];
538 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
540 for (i = 0; i < nmsgs; i++) {
541 if (! (sp = mlist[i]))
542 continue; /* did this one */
546 continue; /* this one doesn't move */
549 * the guy that was msg j is about to become msg i.
550 * rename 'j' to make a hole, then recursively rename
551 * guys to fill up the hole.
553 old = smsgs[j].s_msg;
554 new = smsgs[i].s_msg;
555 strncpy (f1, m_name (old), sizeof(f1));
558 printf ("renaming message chain from %d to %d\n", old, new);
561 * Run the external hook to refile the old message as the
562 * temporary message number that is off of the end of the
563 * messages in the folder.
566 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
567 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
568 ext_hook("ref-hook", f1, newbuf);
570 if (rename (f1, tmpfil) == NOTOK)
571 adios (tmpfil, "unable to rename %s to ", f1);
573 get_msg_flags (mp, &tmpset, old);
575 rename_chain (mp, mlist, j, i);
578 * Run the external hook to refile the temorary message number
582 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
583 ext_hook("ref-hook", newbuf, f1);
585 if (rename (tmpfil, m_name(new)) == NOTOK)
586 adios (m_name(new), "unable to rename %s to", tmpfil);
588 set_msg_flags (mp, &tmpset, new);
589 mp->msgflags |= SEQMOD;