From: Michael Tremer Date: Fri, 16 Apr 2021 13:55:32 +0000 (+0000) Subject: config: Add function that lists all sections X-Git-Tag: 0.9.28~1285^2~350 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4715e3fc44c058a187838e250fbc11ff36d19897;p=pakfire.git config: Add function that lists all sections Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/config.c b/src/libpakfire/config.c index 13dc13fc1..65aa5fb84 100644 --- a/src/libpakfire/config.c +++ b/src/libpakfire/config.c @@ -206,6 +206,44 @@ int pakfire_config_get_bool(struct pakfire_config* config, return _default; } +static int pakfire_section_in_sections(char** sections, const char* section) { + if (!sections) + return 0; + + for (char** s = sections; *s; s++) { + if (strcmp(section, *s) == 0) + return 1; + } + + return 0; +} + +char** pakfire_config_sections(struct pakfire_config* config) { + struct pakfire_config_entry* entry; + + char** sections = NULL; + size_t num_sections = 0; + + STAILQ_FOREACH(entry, &config->entries, nodes) { + // Skip empty sections + if (!*entry->section) + continue; + + // Skip if this section is already on the list + if (pakfire_section_in_sections(sections, entry->section)) + continue; + + // Make space in the array + sections = reallocarray(sections, sizeof(*sections), num_sections++ + 1); + if (!sections) + return NULL; + + sections[num_sections - 1] = strdup(entry->section); + } + + return sections; +} + static ssize_t strip(char* s) { if (!s) return 0; diff --git a/src/libpakfire/include/pakfire/config.h b/src/libpakfire/include/pakfire/config.h index 31fc5666b..0dca2b6e2 100644 --- a/src/libpakfire/include/pakfire/config.h +++ b/src/libpakfire/include/pakfire/config.h @@ -40,6 +40,8 @@ long int pakfire_config_get_int(struct pakfire_config* config, int pakfire_config_get_bool(struct pakfire_config* config, const char* section, const char* key, int _default); +char** pakfire_config_sections(struct pakfire_config* config); + int pakfire_config_read(struct pakfire_config* config, FILE* f); #endif diff --git a/tests/libpakfire/config.c b/tests/libpakfire/config.c index 235297549..30757b4c7 100644 --- a/tests/libpakfire/config.c +++ b/tests/libpakfire/config.c @@ -91,6 +91,22 @@ static int test_parse(const struct test* t) { ASSERT_STRING_EQUALS(pakfire_config_get(config, "section2", "key1", NULL), "value1"); ASSERT_STRING_EQUALS(pakfire_config_get(config, "section2", "key2", NULL), "value2"); + // Get sections + char** sections = pakfire_config_sections(config); + ASSERT(sections); + + // Count sections + size_t counter = 0; + for (char** section = sections; *section; section++) + counter++; + + ASSERT(counter == 2); + + // Check for section names + ASSERT_STRING_EQUALS(sections[0], "section1"); + ASSERT_STRING_EQUALS(sections[1], "section2"); + ASSERT_NULL(sections[2]); + pakfire_config_free(config); fclose(f);