string-list: optionally omit empty string pieces in string_list_split*()

Teach the unified split_string() machinery a new flag bit, STRING_LIST_SPLIT_NONEMPTY, to cause empty split pieces to be omitted from the resulting string list. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Aug 1, 2025 at 15:04 UTC 27531efa41cfa882473513dd93e696a16f6eb87b
3 files changed +20
string-list.c
+3
@@ -294,6 +294,9 @@ static int append_one(struct string_list *list,
294 break;
295 }
296
297 + if ((flags & STRING_LIST_SPLIT_NONEMPTY) && (end <= p))
298 + return 0;
299 +
300 if (in_place) {
301 *((char *)end) = '\0';
302 string_list_append(list, p);
string-list.h
+2
@@ -289,6 +289,8 @@ enum {
289 * it to the list
290 */
291 STRING_LIST_SPLIT_TRIM = (1 << 0),
292 + /* omit adding empty string piece to the resulting list */
293 + STRING_LIST_SPLIT_NONEMPTY = (1 << 1),
294 };
295
296 int string_list_split_f(struct string_list *, const char *string,
t/unit-tests/u-string-list.c
+15
@@ -92,6 +92,13 @@ void test_string_list__split_f(void)
92 "foo", "bar", "baz", NULL);
93 t_string_list_split_f(" a b c ", " ", 1, STRING_LIST_SPLIT_TRIM,
94 "a", "b c", NULL);
95 + t_string_list_split_f("::foo::bar:baz:", ":", -1, STRING_LIST_SPLIT_NONEMPTY,
96 + "foo", "bar", "baz", NULL);
97 + t_string_list_split_f("foo:baz", ":", -1, STRING_LIST_SPLIT_NONEMPTY,
98 + "foo", "baz", NULL);
99 + t_string_list_split_f("foo :: : baz", ":", -1,
100 + STRING_LIST_SPLIT_NONEMPTY | STRING_LIST_SPLIT_TRIM,
101 + "foo", "baz", NULL);
102 }
103
104 static void t_string_list_split_in_place_f(const char *data_, const char *delim,
@@ -125,6 +132,14 @@ void test_string_list__split_in_place_f(void)
132 "foo", "bar", "baz", NULL);
133 t_string_list_split_in_place_f(" a b c ", " ", 1, STRING_LIST_SPLIT_TRIM,
134 "a", "b c", NULL);
135 + t_string_list_split_in_place_f("::foo::bar:baz:", ":", -1,
136 + STRING_LIST_SPLIT_NONEMPTY,
137 + "foo", "bar", "baz", NULL);
138 + t_string_list_split_in_place_f("foo:baz", ":", -1, STRING_LIST_SPLIT_NONEMPTY,
139 + "foo", "baz", NULL);
140 + t_string_list_split_in_place_f("foo :: : baz", ":", -1,
141 + STRING_LIST_SPLIT_NONEMPTY | STRING_LIST_SPLIT_TRIM,
142 + "foo", "baz", NULL);
143 }
144
145 void test_string_list__split(void)