test-mergesort: add sort subcommand
[git/debian.git] / t / helper / test-mergesort.c
blob05be0d067ac8ca9f6266aae1a954f4801655b053
1 #include "test-tool.h"
2 #include "cache.h"
3 #include "mergesort.h"
5 struct line {
6 char *text;
7 struct line *next;
8 };
10 static void *get_next(const void *a)
12 return ((const struct line *)a)->next;
15 static void set_next(void *a, void *b)
17 ((struct line *)a)->next = b;
20 static int compare_strings(const void *a, const void *b)
22 const struct line *x = a, *y = b;
23 return strcmp(x->text, y->text);
26 static int sort_stdin(void)
28 struct line *line, *p = NULL, *lines = NULL;
29 struct strbuf sb = STRBUF_INIT;
31 while (!strbuf_getline(&sb, stdin)) {
32 line = xmalloc(sizeof(struct line));
33 line->text = strbuf_detach(&sb, NULL);
34 if (p) {
35 line->next = p->next;
36 p->next = line;
37 } else {
38 line->next = NULL;
39 lines = line;
41 p = line;
44 lines = llist_mergesort(lines, get_next, set_next, compare_strings);
46 while (lines) {
47 puts(lines->text);
48 lines = lines->next;
50 return 0;
53 int cmd__mergesort(int argc, const char **argv)
55 if (argc == 2 && !strcmp(argv[1], "sort"))
56 return sort_stdin();
57 usage("test-tool mergesort sort");