Permalink
Browse files

[api wip] Begin work on saneopt

  • Loading branch information...
mmalecki committed Mar 29, 2013
1 parent 74c018a commit adf92bf973e21fa903de26eac4773a47d2cae850
Showing with 119 additions and 0 deletions.
  1. +23 −0 Makefile
  2. +41 −0 include/saneopt.h
  3. +55 −0 src/saneopt.c
View
@@ -0,0 +1,23 @@
+OBJS += src/saneopt.o
+
+TEST_OBJS += test/test-saneopt
+
+CFLAGS=-g -Wall -Iinclude
+
+all: libsaneopt.a
+
+libsaneopt.a: $(OBJS)
+ ar rcs $@ $^
+
+src/%.o: src/%.c
+ gcc $(CFLAGS) -c $< -o $@
+
+test/%: test/%.c
+ gcc -L. -lsaneopt $(CFLAGS) $< -o $@
+
+test: libsaneopt.a $(OBJS) $(TEST_OBJS)
+ test/test-saneopt
+
+clean:
+ rm -f libsaneopt.a
+ rm -f $(OBJS)
View
@@ -0,0 +1,41 @@
+#ifndef _SANEOPT_H
+#define _SANEOPT_H
+
+struct saneopt__alias {
+ char* option;
+ char* alias;
+} typedef saneopt__alias_t;
+
+struct saneopt {
+ int argc;
+ char** argv;
+
+ saneopt__alias_t** aliases;
+ unsigned int alias_count;
+} typedef saneopt_t;
+
+struct saneopt_arg {
+ char* value;
+} typedef saneopt_arg_t;
+
+/*
+ * Create a new `saneopt` parser.
+ */
+saneopt_t* saneopt_new(int argc, char** argv);
+
+/*
+ * Set an alias from `old` to `new`.
+ */
+void saneopt_alias(saneopt_t* opt, char* old, char* new_);
+
+/*
+ * Check if argument is empty (wasn't passed or has no value).
+ */
+int saneopt_empty(saneopt_arg_t* arg);
+
+/*
+ * Get option called `option`.
+ */
+saneopt_arg_t* saneopt_get(saneopt_t* opt, char* name);
+
+#endif
View
@@ -0,0 +1,55 @@
+#include <stdlib.h>
+#include <string.h>
+
+#include "../include/saneopt.h"
+
+saneopt_t* saneopt_new(int argc, char** argv) {
+ saneopt_t* saneopt = malloc(sizeof(saneopt_t));
+ saneopt->argc = argc;
+ saneopt->argv = argv;
+
+ saneopt->aliases = NULL;
+ saneopt->alias_count = 0;
+ return saneopt;
+}
+
+void saneopt_alias(saneopt_t* opt, char* option, char* alias) {
+ saneopt__alias_t* alias_ = malloc(sizeof(saneopt__alias_t));
+ alias_->option = option;
+ alias_->alias = alias;
+
+ opt->aliases = realloc(
+ opt->aliases,
+ ++opt->alias_count * sizeof(saneopt__alias_t*)
+ );
+ opt->aliases[opt->alias_count - 1] = alias_;
+}
+
+int saneopt_empty(saneopt_arg_t* arg) {
+ return arg == NULL || arg->value == NULL;
+}
+
+saneopt_arg_t* saneopt_get(saneopt_t* opt, char* name) {
+ int i, argc;
+ char* arg;
+ char** argv;
+ saneopt_arg_t* result;
+
+ argc = opt->argc;
+ argv = opt->argv;
+
+ for (i = 0; i < argc; i++) {
+ arg = argv[i];
+ if (strncmp(arg, "--", 2) == 0) {
+ if (strcmp(arg + 2, name) == 0) {
+ result = malloc(sizeof(saneopt_arg_t));
+ if ((i + 1) < argc && argv[i + 1][0] != '-') {
+ result->value = argv[i + 1];
+ return result;
+ }
+ }
+ }
+ }
+
+ return NULL;
+}

0 comments on commit adf92bf

Please sign in to comment.