kwil-header-tool/src/args.c

73 lines
2.0 KiB
C
Raw Permalink Normal View History

2023-09-11 16:44:51 +00:00
#include "args.h"
#include <stdlib.h>
#include <string.h>
void kwil_parse_args(struct kwil_args_t* self, int argc, char** argv) {
self->argc = argc;
self->argv = argv;
self->parsed = 0;
// allocate filename array with capacity of 1
self->filenames = malloc(sizeof(char**));
self->filenames_cap = 1;
self->filenames_len = 0;
for(self->parsed = 0; self->parsed < argc; ++self->parsed) {
kwil_args_parse_arg(self, self->parsed);
}
}
void kwil_free_args(struct kwil_args_t* self) {
for(int i = 0; i < self->filenames_len; ++i) {
free(self->filenames[i]);
}
free(self->filenames);
self->filenames_cap = 0;
self->filenames_len = 0;
}
int kwil_args_add_filename(struct kwil_args_t* self, const char* filename) {
// resize the array if needed
if(self->filenames_len >= self->filenames_cap) {
size_t new_cap = self->filenames_cap * 2;
char** new_array = realloc(self->filenames, new_cap * sizeof(char**));
if(new_array == NULL) {
return 1;
}
self->filenames_cap = new_cap;
self->filenames = new_array;
}
// allocate enough memory for the string and null terminator
size_t len = strlen(filename);
self->filenames[self->filenames_len] = malloc(len + 1);
// copy string (includes null terminator)
strcpy(self->filenames[self->filenames_len], filename);
++self->filenames_len;
return 0;
}
void kwil_args_parse_arg(struct kwil_args_t* self, int at) {
if(at == 0) {
// is program argument, ignore
} else if(self->argv[at][0] == '-') {
// is a flag, parse flag
// no flags to parse
} else {
// asume a filename
kwil_args_parse_filename(self, at);
}
}
void kwil_args_parse_filename(struct kwil_args_t* self, int filename) {
const char* filename_str = self->argv[filename];
int len = strlen(filename_str);
if(strcmp(filename_str + len - 7, ".kwil.h") != 0) {
kwil_args_add_filename(self, filename_str);
}
}