]> diplodocus.org Git - nmh/blob - uip/sortm.c
b44c3fd6cbf18745f71bc8d1c31cf3a45654fc28
[nmh] / uip / sortm.c
1 /* sortm.c -- sort messages in a folder by date/time
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <h/mh.h>
9 #include <h/tws.h>
10 #include <h/utils.h>
11
12 #define SORTM_SWITCHES \
13 X("datefield field", 0, DATESW) \
14 X("textfield field", 0, TEXTSW) \
15 X("notextfield", 0, NSUBJSW) \
16 X("subject", -3, SUBJSW) /* backward-compatibility */ \
17 X("limit days", 0, LIMSW) \
18 X("nolimit", 0, NLIMSW) \
19 X("verbose", 0, VERBSW) \
20 X("noverbose", 0, NVERBSW) \
21 X("all", 0, ALLMSGS) \
22 X("noall", 0, NALLMSGS) \
23 X("check", 0, CHECKSW) \
24 X("nocheck", 0, NCHECKSW) \
25 X("version", 0, VERSIONSW) \
26 X("help", 0, HELPSW) \
27
28 #define X(sw, minchars, id) id,
29 DEFINE_SWITCH_ENUM(SORTM);
30 #undef X
31
32 #define X(sw, minchars, id) { sw, minchars, id },
33 DEFINE_SWITCH_ARRAY(SORTM, switches);
34 #undef X
35
36 struct smsg {
37 int s_msg;
38 time_t s_clock;
39 char *s_subj;
40 };
41
42 static struct smsg *smsgs;
43 int nmsgs;
44
45 char *subjsort = (char *) 0; /* sort on subject if != 0 */
46 time_t datelimit = 0;
47 int submajor = 0; /* if true, sort on subject-major */
48 int verbose;
49 int allmsgs = 1;
50 int check_failed = 0;
51
52 /* This keeps compiler happy on calls to qsort */
53 typedef int (*qsort_comp) (const void *, const void *);
54
55 /*
56 * static prototypes
57 */
58 static int read_hdrs (struct msgs *, char *);
59 static int get_fields (char *, int, struct smsg *);
60 static int dsort (struct smsg **, struct smsg **);
61 static int subsort (struct smsg **, struct smsg **);
62 static int txtsort (struct smsg **, struct smsg **);
63 static void rename_chain (struct msgs *, struct smsg **, int, int);
64 static void rename_msgs (struct msgs *, struct smsg **);
65
66
67 int
68 main (int argc, char **argv)
69 {
70 int i, msgnum;
71 char *cp, *maildir, *datesw = NULL;
72 char *folder = NULL, buf[BUFSIZ], **argp;
73 char **arguments;
74 struct msgs_array msgs = { 0, 0, NULL };
75 struct msgs *mp;
76 struct smsg **dlist;
77 int checksw = 0;
78
79 if (nmh_init(argv[0], 1)) { return 1; }
80
81 arguments = getarguments (invo_name, argc, argv, 1);
82 argp = arguments;
83
84 /*
85 * Parse arguments
86 */
87 while ((cp = *argp++)) {
88 if (*cp == '-') {
89 switch (smatch (++cp, switches)) {
90 case AMBIGSW:
91 ambigsw (cp, switches);
92 done (1);
93 case UNKWNSW:
94 adios (NULL, "-%s unknown", cp);
95
96 case HELPSW:
97 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
98 invo_name);
99 print_help (buf, switches, 1);
100 done (0);
101 case VERSIONSW:
102 print_version(invo_name);
103 done (0);
104
105 case DATESW:
106 if (datesw)
107 adios (NULL, "only one date field at a time");
108 if (!(datesw = *argp++) || *datesw == '-')
109 adios (NULL, "missing argument to %s", argp[-2]);
110 continue;
111
112 case TEXTSW:
113 if (subjsort)
114 adios (NULL, "only one text field at a time");
115 if (!(subjsort = *argp++) || *subjsort == '-')
116 adios (NULL, "missing argument to %s", argp[-2]);
117 continue;
118
119 case SUBJSW:
120 subjsort = "subject";
121 continue;
122 case NSUBJSW:
123 subjsort = NULL;
124 continue;
125
126 case LIMSW:
127 if (!(cp = *argp++) || *cp == '-')
128 adios (NULL, "missing argument to %s", argp[-2]);
129 while (*cp == '0')
130 cp++; /* skip any leading zeros */
131 if (!*cp) { /* hit end of string */
132 submajor++; /* sort subject-major */
133 continue;
134 }
135 if (!isdigit((unsigned char) *cp) || !(datelimit = atoi(cp)))
136 adios (NULL, "impossible limit %s", cp);
137 datelimit *= 60*60*24;
138 continue;
139 case NLIMSW:
140 submajor = 0; /* use date-major, but */
141 datelimit = 0; /* use no limit */
142 continue;
143
144 case VERBSW:
145 verbose++;
146 continue;
147 case NVERBSW:
148 verbose = 0;
149 continue;
150
151 case ALLMSGS:
152 allmsgs = 1;
153 continue;
154 case NALLMSGS:
155 allmsgs = 0;
156 continue;
157
158 case CHECKSW:
159 checksw = 1;
160 continue;
161 case NCHECKSW:
162 checksw = 0;
163 continue;
164 }
165 }
166 if (*cp == '+' || *cp == '@') {
167 if (folder)
168 adios (NULL, "only one folder at a time!");
169 else
170 folder = pluspath (cp);
171 } else
172 app_msgarg(&msgs, cp);
173 }
174
175 if (!context_find ("path"))
176 free (path ("./", TFOLDER));
177 if (!msgs.size) {
178 if (allmsgs) {
179 app_msgarg(&msgs, "all");
180 } else {
181 adios (NULL, "must specify messages to sort with -noall");
182 }
183 }
184 if (!datesw)
185 datesw = "date";
186 if (!folder)
187 folder = getfolder (1);
188 maildir = m_maildir (folder);
189
190 if (chdir (maildir) == NOTOK)
191 adios (maildir, "unable to change directory to");
192
193 /* read folder and create message structure */
194 if (!(mp = folder_read (folder, 1)))
195 adios (NULL, "unable to read folder %s", folder);
196
197 /* check for empty folder */
198 if (mp->nummsg == 0)
199 adios (NULL, "no messages in %s", folder);
200
201 /* parse all the message ranges/sequences and set SELECTED */
202 for (msgnum = 0; msgnum < msgs.size; msgnum++)
203 if (!m_convert (mp, msgs.msgs[msgnum]))
204 done (1);
205 seq_setprev (mp); /* set the previous sequence */
206
207 if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
208 adios (NULL, "no messages to sort");
209
210 if (checksw && check_failed) {
211 adios (NULL, "errors found, no messages sorted");
212 }
213
214 /*
215 * sort a list of pointers to our "messages to be sorted".
216 */
217 dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
218 for (i = 0; i < nmsgs; i++)
219 dlist[i] = &smsgs[i];
220 dlist[nmsgs] = 0;
221
222 if (verbose) { /* announce what we're doing */
223 if (subjsort)
224 if (submajor)
225 printf ("sorting by %s\n", subjsort);
226 else
227 printf ("sorting by %s-major %s-minor\n", subjsort, datesw);
228 else
229 printf ("sorting by datefield %s\n", datesw);
230 }
231
232 /* first sort by date, or by subject-major, date-minor */
233 qsort ((char *) dlist, nmsgs, sizeof(*dlist),
234 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
235
236 /*
237 * if we're sorting on subject, we need another list
238 * in subject order, then a merge pass to collate the
239 * two sorts.
240 */
241 if (!submajor && subjsort) { /* already date sorted */
242 struct smsg **slist, **flist;
243 struct smsg ***il, **fp, **dp;
244
245 slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
246 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
247 qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
248
249 /*
250 * make an inversion list so we can quickly find
251 * the collection of messages with the same subj
252 * given a message number.
253 */
254 il = mh_xcalloc(mp->hghsel + 1, sizeof *il);
255 for (i = 0; i < nmsgs; i++)
256 il[slist[i]->s_msg] = &slist[i];
257 /*
258 * make up the final list, chronological but with
259 * all the same subjects grouped together.
260 */
261 flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
262 fp = flist;
263 for (dp = dlist; *dp;) {
264 struct smsg **s = il[(*dp++)->s_msg];
265
266 /* see if we already did this guy */
267 if (! s)
268 continue;
269
270 *fp++ = *s++;
271 /*
272 * take the next message(s) if there is one,
273 * its subject isn't null and its subject
274 * is the same as this one and it's not too
275 * far away in time.
276 */
277 while (*s && (*s)->s_subj[0] &&
278 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
279 (datelimit == 0 ||
280 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
281 il[(*s)->s_msg] = 0;
282 *fp++ = *s++;
283 }
284 }
285 *fp = 0;
286 free (il);
287 free (slist);
288 free (dlist);
289 dlist = flist;
290 }
291
292 /*
293 * At this point, dlist is a sorted array of pointers to smsg structures,
294 * each of which contains a message number.
295 */
296
297 rename_msgs (mp, dlist);
298
299 context_replace (pfolder, folder); /* update current folder */
300 seq_save (mp); /* synchronize message sequences */
301 context_save (); /* save the context file */
302 folder_free (mp); /* free folder/message structure */
303 done (0);
304 return 1;
305 }
306
307 static int
308 read_hdrs (struct msgs *mp, char *datesw)
309 {
310 int msgnum;
311 struct tws tb;
312 struct smsg *s;
313
314 twscopy (&tb, dlocaltimenow ());
315
316 smsgs = mh_xcalloc(mp->hghsel - mp->lowsel + 2, sizeof *smsgs);
317 s = smsgs;
318 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
319 if (is_selected(mp, msgnum)) {
320 if (get_fields (datesw, msgnum, s)) {
321 s->s_msg = msgnum;
322 s++;
323 }
324 }
325 }
326 s->s_msg = 0;
327 return(s - smsgs);
328 }
329
330
331 /*
332 * Parse the message and get the data or subject field,
333 * if needed.
334 */
335
336 static int
337 get_fields (char *datesw, int msg, struct smsg *smsg)
338 {
339 int state;
340 int compnum;
341 char *msgnam, buf[BUFSIZ], nam[NAMESZ];
342 struct tws *tw;
343 char *datecomp = NULL, *subjcomp = NULL;
344 FILE *in;
345 m_getfld_state_t gstate = 0;
346
347 if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
348 admonish (msgnam, "unable to read message");
349 return (0);
350 }
351 for (compnum = 1;;) {
352 int bufsz = sizeof buf;
353 switch (state = m_getfld (&gstate, nam, buf, &bufsz, in)) {
354 case FLD:
355 case FLDPLUS:
356 compnum++;
357 if (!strcasecmp (nam, datesw)) {
358 datecomp = add (buf, datecomp);
359 while (state == FLDPLUS) {
360 bufsz = sizeof buf;
361 state = m_getfld (&gstate, nam, buf, &bufsz, in);
362 datecomp = add (buf, datecomp);
363 }
364 if (!subjsort || subjcomp)
365 break;
366 } else if (subjsort && !strcasecmp (nam, subjsort)) {
367 subjcomp = add (buf, subjcomp);
368 while (state == FLDPLUS) {
369 bufsz = sizeof buf;
370 state = m_getfld (&gstate, nam, buf, &bufsz, in);
371 subjcomp = add (buf, subjcomp);
372 }
373 if (datecomp)
374 break;
375 } else {
376 /* just flush this guy */
377 while (state == FLDPLUS) {
378 bufsz = sizeof buf;
379 state = m_getfld (&gstate, nam, buf, &bufsz, in);
380 }
381 }
382 continue;
383
384 case BODY:
385 case FILEEOF:
386 break;
387
388 case LENERR:
389 case FMTERR:
390 if (state == LENERR || state == FMTERR) {
391 inform("format error in message %d (header #%d), continuing...",
392 msg, compnum);
393 check_failed = 1;
394 }
395 mh_xfree(datecomp);
396 mh_xfree(subjcomp);
397 fclose (in);
398 return (0);
399
400 default:
401 adios (NULL, "internal error -- you lose");
402 }
403 break;
404 }
405 m_getfld_state_destroy (&gstate);
406
407 /*
408 * If no date component, then use the modification
409 * time of the file as its date
410 */
411 if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
412 struct stat st;
413
414 inform("can't parse %s field in message %d, "
415 "will use file modification time", datesw, msg);
416 fstat (fileno (in), &st);
417 smsg->s_clock = st.st_mtime;
418 check_failed = 1;
419 } else {
420 smsg->s_clock = dmktime (tw);
421 }
422
423 if (subjsort) {
424 if (subjcomp) {
425 /*
426 * try to make the subject "canonical": delete
427 * leading "re:", everything but letters & smash
428 * letters to lower case.
429 */
430 char *cp, *cp2, c;
431
432 cp = subjcomp;
433 cp2 = subjcomp;
434 if (strcmp (subjsort, "subject") == 0) {
435 while ((c = *cp)) {
436 if (! isspace((unsigned char) c)) {
437 if(uprf(cp, "re:"))
438 cp += 2;
439 else
440 break;
441 }
442 cp++;
443 }
444 }
445
446 while ((c = *cp++)) {
447 if (isascii((unsigned char) c) && isalnum((unsigned char) c))
448 *cp2++ = tolower((unsigned char)c);
449 }
450
451 *cp2 = '\0';
452 }
453 else
454 subjcomp = "";
455
456 smsg->s_subj = subjcomp;
457 }
458 fclose (in);
459 mh_xfree(datecomp);
460
461 return (1);
462 }
463
464 /*
465 * sort on dates.
466 */
467 static int
468 dsort (struct smsg **a, struct smsg **b)
469 {
470 if ((*a)->s_clock < (*b)->s_clock)
471 return (-1);
472 if ((*a)->s_clock > (*b)->s_clock)
473 return (1);
474 if ((*a)->s_msg < (*b)->s_msg)
475 return (-1);
476 return (1);
477 }
478
479 /*
480 * sort on subjects.
481 */
482 static int
483 subsort (struct smsg **a, struct smsg **b)
484 {
485 int i;
486
487 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
488 return (i);
489
490 return (dsort (a, b));
491 }
492
493 static int
494 txtsort (struct smsg **a, struct smsg **b)
495 {
496 int i;
497
498 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
499 return (i);
500 if ((*a)->s_msg < (*b)->s_msg)
501 return (-1);
502 return (1);
503 }
504
505 static void
506 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
507 {
508 int nxt, old, new;
509 char *newname, oldname[BUFSIZ];
510 char newbuf[PATH_MAX + 1];
511
512 for (;;) {
513 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
514 mlist[msg] = NULL;
515 old = smsgs[nxt].s_msg;
516 new = smsgs[msg].s_msg;
517 strncpy (oldname, m_name (old), sizeof(oldname));
518 newname = m_name (new);
519 if (verbose)
520 printf ("message %d becomes message %d\n", old, new);
521
522 (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
523 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
524 ext_hook("ref-hook", oldname, newbuf);
525
526 if (rename (oldname, newname) == NOTOK)
527 adios (newname, "unable to rename %s to", oldname);
528
529 copy_msg_flags (mp, new, old);
530 if (mp->curmsg == old)
531 seq_setcur (mp, new);
532
533 if (nxt == endmsg)
534 break;
535
536 msg = nxt;
537 }
538 /* if (nxt != endmsg); */
539 /* rename_chain (mp, mlist, nxt, endmsg); */
540 }
541
542 static void
543 rename_msgs (struct msgs *mp, struct smsg **mlist)
544 {
545 int i, j, old, new;
546 bvector_t tmpset = bvector_create (0);
547 char f1[BUFSIZ], tmpfil[BUFSIZ];
548 char newbuf[PATH_MAX + 1];
549 struct smsg *sp;
550
551 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
552
553 for (i = 0; i < nmsgs; i++) {
554 if (! (sp = mlist[i]))
555 continue; /* did this one */
556
557 j = sp - smsgs;
558 if (j == i)
559 continue; /* this one doesn't move */
560
561 /*
562 * the guy that was msg j is about to become msg i.
563 * rename 'j' to make a hole, then recursively rename
564 * guys to fill up the hole.
565 */
566 old = smsgs[j].s_msg;
567 new = smsgs[i].s_msg;
568 strncpy (f1, m_name (old), sizeof(f1));
569
570 if (verbose)
571 printf ("renaming message chain from %d to %d\n", old, new);
572
573 /*
574 * Run the external hook to refile the old message as the
575 * temporary message number that is off of the end of the
576 * messages in the folder.
577 */
578
579 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
580 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
581 ext_hook("ref-hook", f1, newbuf);
582
583 if (rename (f1, tmpfil) == NOTOK)
584 adios (tmpfil, "unable to rename %s to ", f1);
585
586 get_msg_flags (mp, tmpset, old);
587
588 rename_chain (mp, mlist, j, i);
589
590 /*
591 * Run the external hook to refile the temorary message number
592 * to the real place.
593 */
594
595 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
596 ext_hook("ref-hook", newbuf, f1);
597
598 if (rename (tmpfil, m_name(new)) == NOTOK)
599 adios (m_name(new), "unable to rename %s to", tmpfil);
600
601 set_msg_flags (mp, tmpset, new);
602 mp->msgflags |= SEQMOD;
603 }
604
605 bvector_free (tmpset);
606 }