mailsplit: sort maildir filenames more cleverly

A maildir does not technically record the order in which items were placed into it. That means that when applying a patch series from a maildir, we may get the patches in the wrong order. We try to work around this by sorting the filenames. Unfortunately, this may or may not work depending on the naming scheme used by the writer of the maildir. For instance, mutt will write: ${epoch_seconds}.${pid}_${seq}.${host} where we have: - epoch_seconds: timestamp at which entry was written - pid: PID of writing process - seq: a sequence number to ensure uniqueness of filenames - host: hostname None of the numbers are zero-padded. Therefore, when we sort the names as byte strings, entries that cross a digit boundary (e.g., 10) will sort out of order. In the case of timestamps, it almost never matters (because we do not cross a digit boundary in the epoch time very often these days). But for the sequence number, a 10-patch series would be ordered as 1, 10, 2, 3, etc. To fix this, we can use a custom sort comparison function which traverses each string, comparing chunks of digits numerically, and otherwise doing a byte-for-byte comparison. That would sort: 123.456_1.bar 123.456_2.bar ... 123.456_10.bar according to the sequence number. Since maildir does not define a filename format, this is really just a heuristic. But it happens to work for mutt, and there is a reasonable chance that it will work for other writers, too (at least as well as a straight sort). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Mar 1, 2013 at 18:35 UTC 18505c34237d3544729c3deed3e4f851fb672086
1 file changed +23
builtin/mailsplit.c
+23
@@ -130,6 +130,27 @@ static int populate_maildir_list(struct string_list *list, const char *path)
130 return 0;
131 }
132
133 +static int maildir_filename_cmp(const char *a, const char *b)
134 +{
135 + while (*a && *b) {
136 + if (isdigit(*a) && isdigit(*b)) {
137 + long int na, nb;
138 + na = strtol(a, (char **)&a, 10);
139 + nb = strtol(b, (char **)&b, 10);
140 + if (na != nb)
141 + return na - nb;
142 + /* strtol advanced our pointers */
143 + }
144 + else {
145 + if (*a != *b)
146 + return (unsigned char)*a - (unsigned char)*b;
147 + a++;
148 + b++;
149 + }
150 + }
151 + return (unsigned char)*a - (unsigned char)*b;
152 +}
153 +
154 static int split_maildir(const char *maildir, const char *dir,
155 int nr_prec, int skip)
156 {
@@ -139,6 +160,8 @@ static int split_maildir(const char *maildir, const char *dir,
160 int i;
161 struct string_list list = STRING_LIST_INIT_DUP;
162
163 + list.cmp = maildir_filename_cmp;
164 +
165 if (populate_maildir_list(&list, maildir) < 0)
166 goto out;
167