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.
18 #ifdef HAVE_SYS_PARAM_H
19 # include <sys/param.h>
22 static struct swit switches[] = {
24 { "datefield field", 0 },
26 { "textfield field", 0 },
50 static struct smsg *smsgs;
53 char *subjsort = NULL; /* sort on subject if != 0 */
55 int submajor = 0; /* if true, sort on subject-major */
58 /* This keeps compiler happy on calls to qsort */
59 typedef int (*qsort_comp) (const void *, const void *);
64 static int read_hdrs(struct msgs *, char *);
65 static int get_fields(char *, int, struct smsg *);
66 static int dsort(struct smsg **, struct smsg **);
67 static int subsort(struct smsg **, struct smsg **);
68 static int txtsort(struct smsg **, struct smsg **);
69 static void rename_chain(struct msgs *, struct smsg **, int, int);
70 static void rename_msgs(struct msgs *, struct smsg **);
74 main(int argc, char **argv)
78 char *maildir, *datesw = NULL;
79 char *folder = NULL, buf[BUFSIZ], **argp;
81 struct msgs_array msgs = { 0, 0, NULL };
85 setlocale(LC_ALL, "");
86 invo_name = mhbasename(argv[0]);
88 /* read user profile/context */
91 arguments = getarguments(invo_name, argc, argv, 1);
97 while ((cp = *argp++)) {
99 switch (smatch(++cp, switches)) {
101 ambigsw(cp, switches);
104 adios(EX_USAGE, NULL, "-%s unknown", cp);
107 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
108 print_help(buf, switches, 1);
109 exit(argc == 2 ? EX_OK : EX_USAGE);
111 print_version(invo_name);
112 exit(argc == 2 ? EX_OK : EX_USAGE);
116 adios(EX_USAGE, NULL, "only one date field at a time");
117 if (!(datesw = *argp++) || *datesw == '-')
118 adios(EX_USAGE, NULL, "missing argument to %s",
124 adios(EX_USAGE, NULL, "only one text field at a time");
125 if (!(subjsort = *argp++) || *subjsort == '-')
126 adios(EX_USAGE, NULL, "missing argument to %s",
135 if (!(cp = *argp++) || *cp == '-')
136 adios(EX_USAGE, 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(EX_USAGE, 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(EX_USAGE, NULL, "only one folder at a time!");
164 folder = mh_xstrdup(expandfol(cp));
166 app_msgarg(&msgs, cp);
170 app_msgarg(&msgs, seq_all);
174 folder = getcurfol();
175 maildir = toabsdir(folder);
177 if (chdir(maildir) == NOTOK)
178 adios(EX_OSERR, maildir, "unable to change directory to");
180 /* read folder and create message structure */
181 if (!(mp = folder_read(folder)))
182 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
184 /* check for empty folder */
186 adios(EX_DATAERR, 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(EX_DATAERR, NULL, "no messages to sort");
198 ** sort a list of pointers to our "messages to be sorted".
200 dlist = mh_xcalloc(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 struct smsg ***il, **fp, **dp;
227 slist = mh_xcalloc(nmsgs+1, sizeof(*slist));
228 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
229 qsort((char *)slist, nmsgs, sizeof(*slist),
230 (qsort_comp) subsort);
233 ** make an inversion list so we can quickly find
234 ** the collection of messages with the same subj
235 ** given a message number.
237 il = mh_xcalloc(mp->hghsel+1, sizeof(*il));
239 adios(EX_OSERR, NULL, "couldn't allocate msg list");
240 for (i = 0; i < nmsgs; i++)
241 il[slist[i]->s_msg] = &slist[i];
243 ** make up the final list, chronological but with
244 ** all the same subjects grouped together.
246 flist = mh_xcalloc(nmsgs+1, sizeof(*flist));
248 for (dp = dlist; *dp;) {
249 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 */
288 read_hdrs(struct msgs *mp, char *datesw)
294 twscopy(&tb, dlocaltimenow());
296 smsgs = mh_xcalloc(mp->hghsel - mp->lowsel + 2, sizeof(*smsgs));
299 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
300 if (is_selected(mp, msgnum)) {
301 if (get_fields(datesw, msgnum, s)) {
313 ** Parse the message and get the data or subject field,
318 get_fields(char *datesw, int msg, struct smsg *smsg)
321 struct field f = {{0}};
325 char *datecomp = NULL, *subjcomp = NULL;
328 if ((in = fopen(msgnam = m_name(msg), "r")) == NULL) {
329 admonish(msgnam, "unable to read message");
332 for (compnum = 1, state = FLD2;; compnum++) {
333 switch (state = m_getfld2(state, &f, in)) {
338 if (mh_strcasecmp(f.name, datesw)==0) {
339 datecomp = mh_xstrdup(f.value);
340 if (!subjsort || subjcomp) {
343 } else if (subjsort && mh_strcasecmp(f.name,
345 subjcomp = mh_xstrdup(f.value);
357 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
362 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
373 adios(EX_SOFTWARE, NULL, "internal error -- you lose");
379 ** If no date component, then use the modification
380 ** time of the file as its date
382 if (!datecomp || (tw = dparsetime(datecomp)) == NULL) {
385 admonish(NULL, "can't parse %s field in message %d",
387 fstat(fileno(in), &st);
388 smsg->s_clock = st.st_mtime;
390 smsg->s_clock = dmktime(tw);
396 ** try to make the subject "canonical": delete
397 ** leading "re:", everything but letters & smash
398 ** letters to lower case.
405 if (strcmp(subjsort, "subject") == 0) {
417 while ((c = *cp++)) {
419 *cp2++ = isupper(c) ? tolower(c) : c;
426 smsg->s_subj = subjcomp;
439 dsort(struct smsg **a, struct smsg **b)
441 if ((*a)->s_clock < (*b)->s_clock)
443 else if ((*a)->s_clock > (*b)->s_clock)
445 else if ((*a)->s_msg < (*b)->s_msg)
455 subsort(struct smsg **a, struct smsg **b)
459 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
462 return (dsort(a, b));
466 txtsort(struct smsg **a, struct smsg **b)
470 if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
472 else if ((*a)->s_msg < (*b)->s_msg)
479 rename_chain(struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
482 char *newname, oldname[BUFSIZ];
483 char newbuf[MAXPATHLEN + 1];
486 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
487 mlist[msg] = (struct smsg *)0;
488 old = smsgs[nxt].s_msg;
489 new = smsgs[msg].s_msg;
490 strncpy(oldname, m_name(old), sizeof(oldname));
491 newname = m_name(new);
493 printf("message %d becomes message %d\n", old, new);
495 snprintf(oldname, sizeof (oldname), "%s/%d",
497 snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
498 ext_hook("ref-hook", oldname, newbuf);
500 if (rename(oldname, newname) == NOTOK)
501 adios(EX_IOERR, newname, "unable to rename %s to", oldname);
503 copy_msg_flags(mp, new, old);
504 if (mp->curmsg == old)
512 /* if (nxt != endmsg); */
513 /* rename_chain(mp, mlist, nxt, endmsg); */
517 rename_msgs(struct msgs *mp, struct smsg **mlist)
521 char f1[BUFSIZ], tmpfil[BUFSIZ];
522 char newbuf[MAXPATHLEN + 1];
525 strncpy(tmpfil, m_name(mp->hghmsg + 1), sizeof(tmpfil));
527 for (i = 0; i < nmsgs; i++) {
528 if (! (sp = mlist[i]))
529 continue; /* did this one */
533 continue; /* this one doesn't move */
536 ** the guy that was msg j is about to become msg i.
537 ** rename 'j' to make a hole, then recursively rename
538 ** guys to fill up the hole.
540 old = smsgs[j].s_msg;
541 new = smsgs[i].s_msg;
542 strncpy(f1, m_name(old), sizeof(f1));
545 printf("renaming message chain from %d to %d\n",
549 ** Run the external hook to refile the old message as the
550 ** temporary message number that is off of the end of the
551 ** messages in the folder.
554 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
555 snprintf(newbuf, sizeof (newbuf), "%s/%d",
556 mp->foldpath, mp->hghmsg + 1);
557 ext_hook("ref-hook", f1, newbuf);
559 if (rename(f1, tmpfil) == NOTOK)
560 adios(EX_IOERR, tmpfil, "unable to rename %s to ", f1);
562 get_msg_flags(mp, &tmpset, old);
564 rename_chain(mp, mlist, j, i);
567 ** Run the external hook to refile the temorary message number
568 ** to the real place.
571 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
572 ext_hook("ref-hook", newbuf, f1);
574 if (rename(tmpfil, m_name(new)) == NOTOK)
575 adios(EX_IOERR, m_name(new), "unable to rename %s to", tmpfil);
577 set_msg_flags(mp, &tmpset, new);
578 mp->msgflags |= SEQMOD;