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 = r1bindex (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]",
104 print_help (buf, switches, 1);
107 print_version(invo_name);
112 adios (NULL, "only one date field at a time");
113 if (!(datesw = *argp++) || *datesw == '-')
114 adios (NULL, "missing argument to %s", argp[-2]);
119 adios (NULL, "only one text field at a time");
120 if (!(subjsort = *argp++) || *subjsort == '-')
121 adios (NULL, "missing argument to %s", argp[-2]);
125 subjsort = "subject";
128 subjsort = (char *)0;
132 if (!(cp = *argp++) || *cp == '-')
133 adios (NULL, "missing argument to %s", argp[-2]);
135 cp++; /* skip any leading zeros */
136 if (!*cp) { /* hit end of string */
137 submajor++; /* sort subject-major */
140 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
141 adios (NULL, "impossible limit %s", cp);
142 datelimit *= 60*60*24;
145 submajor = 0; /* use date-major, but */
146 datelimit = 0; /* use no limit */
157 if (*cp == '+' || *cp == '@') {
159 adios (NULL, "only one folder at a time!");
161 folder = pluspath (cp);
163 app_msgarg(&msgs, cp);
166 if (!context_find ("path"))
167 free (path ("./", TFOLDER));
169 app_msgarg(&msgs, "all");
173 folder = getfolder (1);
174 maildir = m_maildir (folder);
176 if (chdir (maildir) == NOTOK)
177 adios (maildir, "unable to change directory to");
179 /* read folder and create message structure */
180 if (!(mp = folder_read (folder)))
181 adios (NULL, "unable to read folder %s", folder);
183 /* check for empty folder */
185 adios (NULL, "no messages in %s", folder);
187 /* parse all the message ranges/sequences and set SELECTED */
188 for (msgnum = 0; msgnum < msgs.size; msgnum++)
189 if (!m_convert (mp, msgs.msgs[msgnum]))
191 seq_setprev (mp); /* set the previous sequence */
193 if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
194 adios (NULL, "no messages to sort");
197 * sort a list of pointers to our "messages to be sorted".
199 dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
200 for (i = 0; i < nmsgs; i++)
201 dlist[i] = &smsgs[i];
204 if (verbose) { /* announce what we're doing */
206 printf ("sorting by %s-major %s-minor\n",
207 submajor ? subjsort : datesw,
208 submajor ? datesw : subjsort);
210 printf ("sorting by datefield %s\n", datesw);
213 /* first sort by date, or by subject-major, date-minor */
214 qsort ((char *) dlist, nmsgs, sizeof(*dlist),
215 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
218 * if we're sorting on subject, we need another list
219 * in subject order, then a merge pass to collate the
222 if (!submajor && subjsort) { /* already date sorted */
223 struct smsg **slist, **flist;
224 register struct smsg ***il, **fp, **dp;
226 slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
227 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
228 qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
231 * make an inversion list so we can quickly find
232 * the collection of messages with the same subj
233 * given a message number.
235 il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
237 adios (NULL, "couldn't allocate msg list");
238 for (i = 0; i < nmsgs; i++)
239 il[slist[i]->s_msg] = &slist[i];
241 * make up the final list, chronological but with
242 * all the same subjects grouped together.
244 flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
246 for (dp = dlist; *dp;) {
247 register struct smsg **s = il[(*dp++)->s_msg];
249 /* see if we already did this guy */
255 * take the next message(s) if there is one,
256 * its subject isn't null and its subject
257 * is the same as this one and it's not too
260 while (*s && (*s)->s_subj[0] &&
261 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
263 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
275 * At this point, dlist is a sorted array of pointers to smsg
276 * structures, each of which contains a message number.
279 rename_msgs (mp, dlist);
281 context_replace (pfolder, folder); /* update current folder */
282 seq_save (mp); /* synchronize message sequences */
283 context_save (); /* save the context file */
284 folder_free (mp); /* free folder/message structure */
290 read_hdrs (struct msgs *mp, char *datesw)
294 register struct smsg *s;
296 twscopy (&tb, dlocaltimenow ());
298 smsgs = (struct smsg *)
299 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, sizeof(buf), in);
347 datecomp = add (buf, datecomp);
349 if (!subjsort || subjcomp)
351 } else if (subjsort && !mh_strcasecmp (nam, subjsort)) {
352 subjcomp = add (buf, subjcomp);
353 while (state == FLDPLUS) {
354 state = m_getfld (state, nam, buf, sizeof(buf), in);
355 subjcomp = add (buf, subjcomp);
360 /* just flush this guy */
361 while (state == FLDPLUS)
362 state = m_getfld (state, nam, buf, sizeof(buf), in);
373 if (state == LENERR || state == FMTERR)
374 admonish (NULL, "format error in message %d (header #%d)",
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", datesw, msg);
397 fstat (fileno (in), &st);
398 smsg->s_clock = st.st_mtime;
400 smsg->s_clock = dmktime (tw);
406 * try to make the subject "canonical": delete
407 * leading "re:", everything but letters & smash
408 * letters to lower case.
410 register char *cp, *cp2;
411 register unsigned char c;
415 if (strcmp (subjsort, "subject") == 0) {
427 while ((c = *cp++)) {
429 *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 (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
507 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
508 ext_hook("ref-hook", oldname, newbuf);
510 if (rename (oldname, newname) == NOTOK)
511 adios (newname, "unable to rename %s to", oldname);
513 copy_msg_flags (mp, new, old);
514 if (mp->curmsg == old)
515 seq_setcur (mp, new);
522 /* if (nxt != endmsg); */
523 /* rename_chain (mp, mlist, nxt, endmsg); */
527 rename_msgs (struct msgs *mp, struct smsg **mlist)
531 char f1[BUFSIZ], tmpfil[BUFSIZ];
532 char newbuf[MAXPATHLEN + 1];
535 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
537 for (i = 0; i < nmsgs; i++) {
538 if (! (sp = mlist[i]))
539 continue; /* did this one */
543 continue; /* this one doesn't move */
546 * the guy that was msg j is about to become msg i.
547 * rename 'j' to make a hole, then recursively rename
548 * guys to fill up the hole.
550 old = smsgs[j].s_msg;
551 new = smsgs[i].s_msg;
552 strncpy (f1, m_name (old), sizeof(f1));
555 printf ("renaming message chain from %d to %d\n", old, new);
558 * Run the external hook to refile the old message as the
559 * temporary message number that is off of the end of the
560 * messages in the folder.
563 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
564 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
565 ext_hook("ref-hook", f1, newbuf);
567 if (rename (f1, tmpfil) == NOTOK)
568 adios (tmpfil, "unable to rename %s to ", f1);
570 get_msg_flags (mp, &tmpset, old);
572 rename_chain (mp, mlist, j, i);
575 * Run the external hook to refile the temorary message number
579 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
580 ext_hook("ref-hook", newbuf, f1);
582 if (rename (tmpfil, m_name(new)) == NOTOK)
583 adios (m_name(new), "unable to rename %s to", tmpfil);
585 set_msg_flags (mp, &tmpset, new);
586 mp->msgflags |= SEQMOD;