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