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