]> diplodocus.org Git - nmh/blob - sbr/maildir_read_and_sort.c
Added start_test/finish_test to a bunch of tests.
[nmh] / sbr / maildir_read_and_sort.c
1 /* maildir_read_and_sort.c -- returns a sorted list of msgs in a Maildir.
2 *
3 * This code is Copyright (c) 2020, 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
10 #include "sbr/maildir_read_and_sort.h"
11
12 #include "sbr/concat.h"
13 #include "sbr/error.h"
14
15 static int maildir_srt(const void *va, const void *vb) PURE;
16
17 static int
18 maildir_srt(const void *va, const void *vb)
19 {
20 const struct Maildir_entry *a = va, *b = vb;
21 if (a->mtime > b->mtime)
22 return 1;
23 if (a->mtime < b->mtime)
24 return -1;
25 return 0;
26 }
27
28 static void read_one_dir (char *dirpath, char *dirpath_base,
29 struct Maildir_entry **maildir, int *maildir_size,
30 int *nmsgs) {
31 DIR *md;
32 struct dirent *de;
33 struct stat ms;
34 char *cp;
35
36 cp = concat (dirpath_base, dirpath, NULL);
37 if ((md = opendir(cp)) == NULL)
38 die("unable to open %s", cp);
39 while ((de = readdir (md)) != NULL) {
40 if (de->d_name[0] == '.')
41 continue;
42 if (*nmsgs >= *maildir_size) {
43 if ((*maildir = realloc(*maildir, sizeof(**maildir) * (2*(*nmsgs)+16))) == NULL)
44 die("not enough memory for %d messages", 2*(*nmsgs)+16);
45 *maildir_size = 2*(*nmsgs)+16;
46 }
47 (*maildir)[*nmsgs].filename = concat (cp, "/", de->d_name, NULL);
48 if (stat((*maildir)[*nmsgs].filename, &ms) != 0)
49 adios ((*maildir)[*nmsgs].filename, "couldn't get delivery time");
50 (*maildir)[*nmsgs].mtime = ms.st_mtime;
51 (*nmsgs)++;
52 }
53 free (cp);
54 closedir (md);
55 }
56
57 /*
58 * On return, maildir_out will be NULL or point to memory the caller may free.
59 */
60 void maildir_read_and_sort (char *maildirpath,
61 struct Maildir_entry **maildir_out,
62 int *num_maildir_entries_out) {
63 int num_maildir_entries = 0;
64 struct Maildir_entry *Maildir = NULL;
65 int msize = 0;
66
67 read_one_dir("/new", maildirpath, &Maildir, &msize, &num_maildir_entries);
68 read_one_dir("/cur", maildirpath, &Maildir, &msize, &num_maildir_entries);
69 if (num_maildir_entries == 0)
70 die("no mail to incorporate");
71 qsort (Maildir, num_maildir_entries, sizeof(*Maildir), maildir_srt);
72
73 *num_maildir_entries_out = num_maildir_entries;
74 *maildir_out = Maildir;
75 }