Skip to content

Commit

Permalink
[api] Implement saneopt_get_all
Browse files Browse the repository at this point in the history
  • Loading branch information
mmalecki committed Mar 30, 2013
1 parent 2339f59 commit b2696b9
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
15 changes: 15 additions & 0 deletions include/saneopt.h
Expand Up @@ -30,6 +30,21 @@ int saneopt_alias(saneopt_t* opt, char* option, char* alias);
*/
char* saneopt_get(saneopt_t* opt, char* option);

/*
* Get all values for option called `option`.
* Return value is a NULL-terminated array.
*
* For example, getting all values for "option", with the following args:
*
* ./app --option first --option second
*
* Will return ["first", "second"].
*
* If a occurrence is lacking a value (e.g. `--option --next-option`), it'll be
* set to "".
*/
char** saneopt_get_all(saneopt_t* opt, char* option);

/*
* Get command line arguments, that is: any arguments not being an argument
* value and all arguments after "--".
Expand Down
28 changes: 28 additions & 0 deletions src/saneopt.c
Expand Up @@ -91,6 +91,34 @@ char* saneopt_get(saneopt_t* opt, char* option) {
return NULL;
}

char** saneopt_get_all(saneopt_t* opt, char* option) {
int i, count;
char* arg;
char** result = malloc(sizeof(char*));
result[0] = NULL;

for (i = 0; i < opt->argc; i++) {
arg = opt->argv[i];

if (strcmp(arg, "--") == 0)
return result;

if (saneopt__matches(opt, option, arg)) {
result = realloc(result, sizeof(char*) * (++count + 1));

if (result == NULL)
return NULL;

result[count - 1] = ((i + 1) < opt->argc && opt->argv[i + 1][0] != '-')
? opt->argv[i + 1]
: "";
result[count] = NULL;
}
}

return result;
}

char** saneopt_arguments(saneopt_t* opt) {
int i, count = 0, saw_marker = 0, saw_option = 0, saw_value = 0;;
char* arg;
Expand Down
23 changes: 23 additions & 0 deletions test/test-saneopt.c
Expand Up @@ -129,6 +129,28 @@ void test_arguments() {
free(opt);
}

void test_all() {
printf("test_all()\n");

char** argv = malloc(4 * sizeof(char*));
char** args;

argv[0] = "--option";
argv[1] = "first";
argv[2] = "--option";
argv[3] = "second";

saneopt_t* opt = saneopt_init(4, argv);
args = saneopt_get_all(opt, "option");
assert(strcmp(args[0], "first") == 0);
assert(strcmp(args[1], "second") == 0);
assert(args[2] == NULL);

free(argv);
free(opt);
free(args);
}

int main(int argc, char** argv) {
test_no_arg();
test_no_value();
Expand All @@ -137,6 +159,7 @@ int main(int argc, char** argv) {
test_short_alias();
test_stop_after_arguments();
test_arguments();
test_all();

return 0;
}

0 comments on commit b2696b9

Please sign in to comment.