Permalink
Browse files

[api] Write `saneopt_arguments`

  • Loading branch information...
mmalecki committed Mar 30, 2013
1 parent 74aea49 commit 594c2964a89ce150f02426d5b4c3a427c2350b4f
Showing with 60 additions and 1 deletion.
  1. +3 −1 include/saneopt.h
  2. +30 −0 src/saneopt.c
  3. +27 −0 test/test-saneopt.c
View
@@ -32,13 +32,15 @@ char* saneopt_get(saneopt_t* opt, char* option);
/*
* Get command line arguments, that is: any arguments not being an argument
* value and all arguments after "--".
+ * Return value is number of arguments, actual arguments are put into
+ * `arguments`.
*
* For example, parsing:
*
* ./app --option value foo bar -- --not-option baz
*
* Will result in this function returning ["foo", "bar", "--not-option", "baz"].
*/
-char** saneopt_arguments(saneopt_t* opt);
+int saneopt_arguments(saneopt_t* opt, char*** arguments);
#endif
View
@@ -81,3 +81,33 @@ char* saneopt_get(saneopt_t* opt, char* option) {
return NULL;
}
+
+int saneopt_arguments(saneopt_t* opt, char*** arguments) {
+ int i, count = 0, saw_marker = 0, saw_option = 0, saw_value = 0;;
+ char* arg;
+
+ for (i = 0; i < opt->argc; i++) {
+ arg = opt->argv[i];
+
+ if (strcmp(arg, "--") == 0) {
+ saw_marker = 1;
+ continue;
+ }
+ else if (strncmp(arg, "-", 1) == 0) {
+ saw_option = 1;
+ continue;
+ }
+ else if (saw_option) {
+ saw_option = 0;
+ saw_value = 1;
+ continue;
+ }
+ else if (saw_value || saw_marker || !saw_option) {
+ *arguments = realloc(*arguments, sizeof(char*) * ++count);
+ (*arguments)[count - 1] = arg;
+ saw_value = 0;
+ }
+ }
+
+ return count;
+}
View
@@ -104,13 +104,40 @@ void test_stop_after_arguments() {
free(opt);
}
+void test_arguments() {
+ printf("test_arguments()\n");
+
+ char** argv = malloc(6 * sizeof(char*));
+ char** args = NULL;
+ int argc;
+
+ argv[0] = "--option";
+ argv[1] = "value";
+ argv[2] = "arg0";
+ argv[3] = "arg1";
+ argv[4] = "--";
+ argv[5] = "arg2";
+
+ saneopt_t* opt = saneopt_init(6, argv);
+ argc = saneopt_arguments(opt, &args);
+ assert(strcmp(saneopt_get(opt, "option"), "value") == 0);
+ assert(argc == 3);
+ assert(strcmp(args[0], "arg0") == 0);
+ assert(strcmp(args[1], "arg1") == 0);
+ assert(strcmp(args[2], "arg2") == 0);
+
+ free(argv);
+ free(opt);
+}
+
int main(int argc, char** argv) {
test_no_arg();
test_no_value();
test_value();
test_long_alias();
test_short_alias();
test_stop_after_arguments();
+ test_arguments();
return 0;
}

0 comments on commit 594c296

Please sign in to comment.