3 #include "string-list.h"
6 * Parse an argument into a string list. arg should either be a
7 * ':'-separated list of strings, or "-" to indicate an empty string
8 * list (as opposed to "", which indicates a string list containing a
9 * single empty string). list->strdup_strings must be set.
11 static void parse_string_list(struct string_list *list, const char *arg)
13 if (!strcmp(arg, "-"))
16 (void)string_list_split(list, arg, ':', -1);
19 static void write_list(const struct string_list *list)
22 for (i = 0; i < list->nr; i++)
23 printf("[%d]: \"%s\"\n", i, list->items[i].string);
26 static void write_list_compact(const struct string_list *list)
32 printf("%s", list->items[0].string);
33 for (i = 1; i < list->nr; i++)
34 printf(":%s", list->items[i].string);
39 static int prefix_cb(struct string_list_item *item, void *cb_data)
41 const char *prefix = (const char *)cb_data;
42 return starts_with(item->string, prefix);
45 int cmd__string_list(int argc, const char **argv)
47 if (argc == 5 && !strcmp(argv[1], "split")) {
48 struct string_list list = STRING_LIST_INIT_DUP;
50 const char *s = argv[2];
52 int maxsplit = atoi(argv[4]);
54 i = string_list_split(&list, s, delim, maxsplit);
57 string_list_clear(&list, 0);
61 if (argc == 5 && !strcmp(argv[1], "split_in_place")) {
62 struct string_list list = STRING_LIST_INIT_NODUP;
64 char *s = xstrdup(argv[2]);
66 int maxsplit = atoi(argv[4]);
68 i = string_list_split_in_place(&list, s, delim, maxsplit);
71 string_list_clear(&list, 0);
76 if (argc == 4 && !strcmp(argv[1], "filter")) {
78 * Retain only the items that have the specified prefix.
79 * Arguments: list|- prefix
81 struct string_list list = STRING_LIST_INIT_DUP;
82 const char *prefix = argv[3];
84 parse_string_list(&list, argv[2]);
85 filter_string_list(&list, 0, prefix_cb, (void *)prefix);
86 write_list_compact(&list);
87 string_list_clear(&list, 0);
91 if (argc == 3 && !strcmp(argv[1], "remove_duplicates")) {
92 struct string_list list = STRING_LIST_INIT_DUP;
94 parse_string_list(&list, argv[2]);
95 string_list_remove_duplicates(&list, 0);
96 write_list_compact(&list);
97 string_list_clear(&list, 0);
101 if (argc == 2 && !strcmp(argv[1], "sort")) {
102 struct string_list list = STRING_LIST_INIT_NODUP;
103 struct strbuf sb = STRBUF_INIT;
104 struct string_list_item *item;
106 strbuf_read(&sb, 0, 0);
109 * Split by newline, but don't create a string_list item
110 * for the empty string after the last separator.
112 if (sb.len && sb.buf[sb.len - 1] == '\n')
113 strbuf_setlen(&sb, sb.len - 1);
114 string_list_split_in_place(&list, sb.buf, '\n', -1);
116 string_list_sort(&list);
118 for_each_string_list_item(item, &list)
121 string_list_clear(&list, 0);
126 fprintf(stderr, "%s: unknown function name: %s\n", argv[0],
127 argv[1] ? argv[1] : "(there was none)");