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 = (char *) 0; /* 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";
129 subjsort = (char *)0;
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 = pluspath(cp);
164 app_msgarg(&msgs, cp);
167 if (!context_find("path"))
168 free(path("./", TFOLDER));
170 app_msgarg(&msgs, "all");
174 folder = getfolder(1);
175 maildir = m_maildir(folder);
177 if (chdir(maildir) == NOTOK)
178 adios(maildir, "unable to change directory to");
180 /* read folder and create message structure */
181 if (!(mp = folder_read(folder)))
182 adios(NULL, "unable to read folder %s", folder);
184 /* check for empty folder */
186 adios(NULL, "no messages in %s", folder);
188 /* parse all the message ranges/sequences and set SELECTED */
189 for (msgnum = 0; msgnum < msgs.size; msgnum++)
190 if (!m_convert(mp, msgs.msgs[msgnum]))
192 seq_setprev(mp); /* set the previous sequence */
194 if ((nmsgs = read_hdrs(mp, datesw)) <= 0)
195 adios(NULL, "no messages to sort");
198 ** sort a list of pointers to our "messages to be sorted".
200 dlist = (struct smsg **) mh_xmalloc((nmsgs+1) * sizeof(*dlist));
201 for (i = 0; i < nmsgs; i++)
202 dlist[i] = &smsgs[i];
205 if (verbose) { /* announce what we're doing */
207 printf("sorting by %s-major %s-minor\n",
208 submajor ? subjsort : datesw,
209 submajor ? datesw : subjsort);
211 printf("sorting by datefield %s\n", datesw);
214 /* first sort by date, or by subject-major, date-minor */
215 qsort((char *) dlist, nmsgs, sizeof(*dlist),
216 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
219 ** if we're sorting on subject, we need another list
220 ** in subject order, then a merge pass to collate the
223 if (!submajor && subjsort) { /* already date sorted */
224 struct smsg **slist, **flist;
225 register struct smsg ***il, **fp, **dp;
227 slist = (struct smsg **)
228 mh_xmalloc((nmsgs+1) * sizeof(*slist));
229 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
230 qsort((char *)slist, nmsgs, sizeof(*slist),
231 (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 **)
248 mh_xmalloc((nmsgs+1) * sizeof(*flist));
250 for (dp = dlist; *dp;) {
251 register struct smsg **s = il[(*dp++)->s_msg];
253 /* see if we already did this guy */
259 ** take the next message(s) if there is one,
260 ** its subject isn't null and its subject
261 ** is the same as this one and it's not too
264 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)) {
276 ** At this point, dlist is a sorted array of pointers to smsg
277 ** structures, each of which contains a message number.
280 rename_msgs(mp, dlist);
282 context_replace(pfolder, folder); /* update current folder */
283 seq_save(mp); /* synchronize message sequences */
284 context_save(); /* save the context file */
285 folder_free(mp); /* free folder/message structure */
291 read_hdrs(struct msgs *mp, char *datesw)
295 register struct smsg *s;
297 twscopy(&tb, dlocaltimenow());
299 smsgs = (struct smsg *) calloc((size_t) (mp->hghsel - mp->lowsel + 2),
302 adios(NULL, "unable to allocate sort storage");
305 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
306 if (is_selected(mp, msgnum)) {
307 if (get_fields(datesw, msgnum, s)) {
319 ** Parse the message and get the data or subject field,
324 get_fields(char *datesw, int msg, struct smsg *smsg)
328 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
329 register struct tws *tw;
330 register char *datecomp = NULL, *subjcomp = NULL;
333 if ((in = fopen(msgnam = m_name(msg), "r")) == NULL) {
334 admonish(msgnam, "unable to read message");
337 for (compnum = 1, state = FLD;;) {
338 switch (state = m_getfld(state, nam, buf, sizeof(buf), in)) {
343 if (!mh_strcasecmp(nam, datesw)) {
344 datecomp = add(buf, datecomp);
345 while (state == FLDPLUS) {
346 state = m_getfld(state, nam, buf,
348 datecomp = add(buf, datecomp);
350 if (!subjsort || subjcomp)
352 } else if (subjsort && !mh_strcasecmp(nam, subjsort)) {
353 subjcomp = add(buf, subjcomp);
354 while (state == FLDPLUS) {
355 state = m_getfld(state, nam, buf,
357 subjcomp = add(buf, subjcomp);
362 /* just flush this guy */
363 while (state == FLDPLUS)
364 state = m_getfld(state, nam, buf,
376 if (state == LENERR || state == FMTERR)
377 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
386 adios(NULL, "internal error -- you lose");
392 ** If no date component, then use the modification
393 ** time of the file as its date
395 if (!datecomp || (tw = dparsetime(datecomp)) == NULL) {
398 admonish(NULL, "can't parse %s field in message %d",
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;
439 smsg->s_subj = subjcomp;
452 dsort(struct smsg **a, struct smsg **b)
454 if ((*a)->s_clock < (*b)->s_clock)
456 else if ((*a)->s_clock > (*b)->s_clock)
458 else if ((*a)->s_msg < (*b)->s_msg)
468 subsort(struct smsg **a, struct smsg **b)
472 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
475 return (dsort(a, b));
479 txtsort(struct smsg **a, struct smsg **b)
483 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
485 else if ((*a)->s_msg < (*b)->s_msg)
492 rename_chain(struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
495 char *newname, oldname[BUFSIZ];
496 char newbuf[MAXPATHLEN + 1];
499 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
500 mlist[msg] = (struct smsg *)0;
501 old = smsgs[nxt].s_msg;
502 new = smsgs[msg].s_msg;
503 strncpy(oldname, m_name(old), sizeof(oldname));
504 newname = m_name(new);
506 printf("message %d becomes message %d\n", old, new);
508 snprintf(oldname, sizeof (oldname), "%s/%d",
510 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)
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",
562 ** Run the external hook to refile the old message as the
563 ** temporary message number that is off of the end of the
564 ** messages in the folder.
567 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
568 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d",
569 mp->foldpath, mp->hghmsg + 1);
570 ext_hook("ref-hook", f1, newbuf);
572 if (rename(f1, tmpfil) == NOTOK)
573 adios(tmpfil, "unable to rename %s to ", f1);
575 get_msg_flags(mp, &tmpset, old);
577 rename_chain(mp, mlist, j, i);
580 ** Run the external hook to refile the temorary message number
581 ** to the real place.
584 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
585 ext_hook("ref-hook", newbuf, f1);
587 if (rename(tmpfil, m_name(new)) == NOTOK)
588 adios(m_name(new), "unable to rename %s to", tmpfil);
590 set_msg_flags(mp, &tmpset, new);
591 mp->msgflags |= SEQMOD;