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