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