2 ** sortm.c -- sort messages in a folder by date/time
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.
13 static struct swit switches[] = {
15 { "datefield field", 0 },
17 { "textfield field", 0 },
21 { "subject", -3 }, /* backward-compatibility */
43 static struct smsg *smsgs;
46 char *subjsort = NULL; /* sort on subject if != 0 */
47 unsigned long datelimit = 0;
48 int submajor = 0; /* if true, sort on subject-major */
51 /* This keeps compiler happy on calls to qsort */
52 typedef int (*qsort_comp) (const void *, const void *);
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 **);
67 main(int argc, char **argv)
71 char *maildir, *datesw = NULL;
72 char *folder = NULL, buf[BUFSIZ], **argp;
74 struct msgs_array msgs = { 0, 0, NULL };
79 setlocale(LC_ALL, "");
81 invo_name = mhbasename(argv[0]);
83 /* read user profile/context */
86 arguments = getarguments(invo_name, argc, argv, 1);
92 while ((cp = *argp++)) {
94 switch (smatch(++cp, switches)) {
96 ambigsw(cp, switches);
99 adios(NULL, "-%s unknown", cp);
102 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
103 print_help(buf, switches, 1);
106 print_version(invo_name);
111 adios(NULL, "only one date field at a time");
112 if (!(datesw = *argp++) || *datesw == '-')
113 adios(NULL, "missing argument to %s",
119 adios(NULL, "only one text field at a time");
120 if (!(subjsort = *argp++) || *subjsort == '-')
121 adios(NULL, "missing argument to %s",
126 subjsort = "subject";
133 if (!(cp = *argp++) || *cp == '-')
134 adios(NULL, "missing argument to %s", argp[-2]);
136 cp++; /* skip any leading zeros */
137 if (!*cp) { /* hit end of string */
138 submajor++; /* sort subject-major */
141 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
142 adios(NULL, "impossible limit %s", cp);
143 datelimit *= 60*60*24;
146 submajor = 0; /* use date-major, but */
147 datelimit = 0; /* use no limit */
158 if (*cp == '+' || *cp == '@') {
160 adios(NULL, "only one folder at a time!");
162 folder = getcpy(expandfol(cp));
164 app_msgarg(&msgs, cp);
168 app_msgarg(&msgs, seq_all);
172 folder = getcurfol();
173 maildir = toabsdir(folder);
175 if (chdir(maildir) == NOTOK)
176 adios(maildir, "unable to change directory to");
178 /* read folder and create message structure */
179 if (!(mp = folder_read(folder)))
180 adios(NULL, "unable to read folder %s", folder);
182 /* check for empty folder */
184 adios(NULL, "no messages in %s", folder);
186 /* parse all the message ranges/sequences and set SELECTED */
187 for (msgnum = 0; msgnum < msgs.size; msgnum++)
188 if (!m_convert(mp, msgs.msgs[msgnum]))
190 seq_setprev(mp); /* set the previous sequence */
192 if ((nmsgs = read_hdrs(mp, datesw)) <= 0)
193 adios(NULL, "no messages to sort");
196 ** sort a list of pointers to our "messages to be sorted".
198 dlist = (struct smsg **) mh_xmalloc((nmsgs+1) * sizeof(*dlist));
199 for (i = 0; i < nmsgs; i++)
200 dlist[i] = &smsgs[i];
203 if (verbose) { /* announce what we're doing */
205 printf("sorting by %s-major %s-minor\n",
206 submajor ? subjsort : datesw,
207 submajor ? datesw : subjsort);
209 printf("sorting by datefield %s\n", datesw);
212 /* first sort by date, or by subject-major, date-minor */
213 qsort((char *) dlist, nmsgs, sizeof(*dlist),
214 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
217 ** if we're sorting on subject, we need another list
218 ** in subject order, then a merge pass to collate the
221 if (!submajor && subjsort) { /* already date sorted */
222 struct smsg **slist, **flist;
223 register struct smsg ***il, **fp, **dp;
225 slist = (struct smsg **)
226 mh_xmalloc((nmsgs+1) * sizeof(*slist));
227 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
228 qsort((char *)slist, nmsgs, sizeof(*slist),
229 (qsort_comp) subsort);
232 ** make an inversion list so we can quickly find
233 ** the collection of messages with the same subj
234 ** given a message number.
236 il = (struct smsg ***) calloc(mp->hghsel+1, sizeof(*il));
238 adios(NULL, "couldn't allocate msg list");
239 for (i = 0; i < nmsgs; i++)
240 il[slist[i]->s_msg] = &slist[i];
242 ** make up the final list, chronological but with
243 ** all the same subjects grouped together.
245 flist = (struct smsg **)
246 mh_xmalloc((nmsgs+1) * sizeof(*flist));
248 for (dp = dlist; *dp;) {
249 register struct smsg **s = il[(*dp++)->s_msg];
251 /* see if we already did this guy */
257 ** take the next message(s) if there is one,
258 ** its subject isn't null and its subject
259 ** is the same as this one and it's not too
262 while (*s && (*s)->s_subj[0] && strcmp((*s)->s_subj, s[-1]->s_subj) == 0 && (datelimit == 0 || (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
274 ** At this point, dlist is a sorted array of pointers to smsg
275 ** structures, each of which contains a message number.
278 rename_msgs(mp, dlist);
280 context_replace(curfolder, folder); /* update current folder */
281 seq_save(mp); /* synchronize message sequences */
282 context_save(); /* save the context file */
283 folder_free(mp); /* free folder/message structure */
289 read_hdrs(struct msgs *mp, char *datesw)
293 register struct smsg *s;
295 twscopy(&tb, dlocaltimenow());
297 smsgs = (struct smsg *) calloc((size_t) (mp->hghsel - mp->lowsel + 2),
300 adios(NULL, "unable to allocate sort storage");
303 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
304 if (is_selected(mp, msgnum)) {
305 if (get_fields(datesw, msgnum, s)) {
317 ** Parse the message and get the data or subject field,
322 get_fields(char *datesw, int msg, struct smsg *smsg)
326 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
327 register struct tws *tw;
328 register char *datecomp = NULL, *subjcomp = NULL;
331 if ((in = fopen(msgnam = m_name(msg), "r")) == NULL) {
332 admonish(msgnam, "unable to read message");
335 for (compnum = 1, state = FLD;;) {
336 switch (state = m_getfld(state, nam, buf, sizeof(buf), in)) {
341 if (!mh_strcasecmp(nam, datesw)) {
342 datecomp = add(buf, datecomp);
343 while (state == FLDPLUS) {
344 state = m_getfld(state, nam, buf,
346 datecomp = add(buf, datecomp);
348 if (!subjsort || subjcomp)
350 } else if (subjsort && !mh_strcasecmp(nam, subjsort)) {
351 subjcomp = add(buf, subjcomp);
352 while (state == FLDPLUS) {
353 state = m_getfld(state, nam, buf,
355 subjcomp = add(buf, subjcomp);
360 /* just flush this guy */
361 while (state == FLDPLUS)
362 state = m_getfld(state, nam, buf,
374 if (state == LENERR || state == FMTERR)
375 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
384 adios(NULL, "internal error -- you lose");
390 ** If no date component, then use the modification
391 ** time of the file as its date
393 if (!datecomp || (tw = dparsetime(datecomp)) == NULL) {
396 admonish(NULL, "can't parse %s field in message %d",
398 fstat(fileno(in), &st);
399 smsg->s_clock = st.st_mtime;
401 smsg->s_clock = dmktime(tw);
407 ** try to make the subject "canonical": delete
408 ** leading "re:", everything but letters & smash
409 ** letters to lower case.
411 register char *cp, *cp2;
412 register unsigned char c;
416 if (strcmp(subjsort, "subject") == 0) {
428 while ((c = *cp++)) {
430 *cp2++ = isupper(c) ? tolower(c) : c;
437 smsg->s_subj = subjcomp;
450 dsort(struct smsg **a, struct smsg **b)
452 if ((*a)->s_clock < (*b)->s_clock)
454 else if ((*a)->s_clock > (*b)->s_clock)
456 else if ((*a)->s_msg < (*b)->s_msg)
466 subsort(struct smsg **a, struct smsg **b)
470 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
473 return (dsort(a, b));
477 txtsort(struct smsg **a, struct smsg **b)
481 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
483 else if ((*a)->s_msg < (*b)->s_msg)
490 rename_chain(struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
493 char *newname, oldname[BUFSIZ];
494 char newbuf[MAXPATHLEN + 1];
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);
504 printf("message %d becomes message %d\n", old, new);
506 snprintf(oldname, sizeof (oldname), "%s/%d",
508 snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
509 ext_hook("ref-hook", oldname, newbuf);
511 if (rename(oldname, newname) == NOTOK)
512 adios(newname, "unable to rename %s to", oldname);
514 copy_msg_flags(mp, new, old);
515 if (mp->curmsg == old)
523 /* if (nxt != endmsg); */
524 /* rename_chain(mp, mlist, nxt, endmsg); */
528 rename_msgs(struct msgs *mp, struct smsg **mlist)
532 char f1[BUFSIZ], tmpfil[BUFSIZ];
533 char newbuf[MAXPATHLEN + 1];
536 strncpy(tmpfil, m_name(mp->hghmsg + 1), sizeof(tmpfil));
538 for (i = 0; i < nmsgs; i++) {
539 if (! (sp = mlist[i]))
540 continue; /* did this one */
544 continue; /* this one doesn't move */
547 ** the guy that was msg j is about to become msg i.
548 ** rename 'j' to make a hole, then recursively rename
549 ** guys to fill up the hole.
551 old = smsgs[j].s_msg;
552 new = smsgs[i].s_msg;
553 strncpy(f1, m_name(old), sizeof(f1));
556 printf("renaming message chain from %d to %d\n",
560 ** Run the external hook to refile the old message as the
561 ** temporary message number that is off of the end of the
562 ** messages in the folder.
565 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
566 snprintf(newbuf, sizeof (newbuf), "%s/%d",
567 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
579 ** to the real place.
582 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;