From 0ce53941ec16490d3ebf0622d333c0f88a16d862 Mon Sep 17 00:00:00 2001 From: Nate Choe Date: Sat, 10 Feb 2024 22:23:47 -0600 Subject: [PATCH] Add _filename variable --- src/include/strings.h | 3 ++- src/parse.c | 27 +++++++++++++++++++++++++++ src/strings.c | 23 ++++++++++++++++++++++- 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/include/strings.h b/src/include/strings.h index 8d47fd8..20ad405 100644 --- a/src/include/strings.h +++ b/src/include/strings.h @@ -9,7 +9,8 @@ struct string { char *data; }; -struct string *newstring(); +struct string *newstring(void); +struct string *charp2s(char *s); int appendchar(struct string *string, char c); void freestring(struct string *string); void resetstring(struct string *string); diff --git a/src/parse.c b/src/parse.c index 786ecce..4aab5d3 100644 --- a/src/parse.c +++ b/src/parse.c @@ -38,6 +38,7 @@ static void mputs(struct minstate *state, char *s, FILE *file); static void mputc(struct minstate *state, char c, FILE *file); static long putvar(long i, struct minstate *s, FILE *out, const struct string *file, const struct vector *vars); +static int defvars(struct expandfile *expanded, char *filename); int parsefile(char *template, FILE *out) { struct expandfile expanded; @@ -52,6 +53,10 @@ int parsefile(char *template, FILE *out) { ret = 1; goto error2; } + if (defvars(&expanded, template)) { + ret = 1; + goto error3; + } if (expandfile(&expanded, template, 0)) { ret = 1; goto error3; @@ -325,6 +330,8 @@ static long putvar(long i, struct minstate *s, FILE *out, goto end; } } + if (file->data[i] != SEPARATOR_CHAR) + goto end; } end: while (file->data[i] != ESCAPE_CHAR && i < file->len) @@ -333,3 +340,23 @@ end: return -1; return i; } + +static int defvars(struct expandfile *expanded, char *filename) { + struct var scratch; + if ((scratch.var = charp2s("_filename")) == NULL) { + goto error1; + } + if ((scratch.value = charp2s(filename)) == NULL) { + goto error2; + } + if (addvector(expanded->vars, &scratch)) { + goto error3; + } + return 0; +error3: + freestring(scratch.value); +error2: + freestring(scratch.var); +error1: + return 1; +} diff --git a/src/strings.c b/src/strings.c index 5b16d21..74844f3 100644 --- a/src/strings.c +++ b/src/strings.c @@ -3,7 +3,7 @@ #include -struct string *newstring() { +struct string *newstring(void) { struct string *ret; ret = malloc(sizeof *ret); if (ret == NULL) @@ -20,6 +20,27 @@ error1: return NULL; } +struct string *charp2s(char *s) { + struct string *ret; + long i; + if ((ret = newstring()) == NULL) { + goto error1; + } + for (i = 0; s[i] != '\0'; ++i) { + if (appendchar(ret, s[i])) { + goto error2; + } + } + if (appendchar(ret, '\0')) { + goto error2; + } + return ret; +error2: + freestring(ret); +error1: + return NULL; +} + int appendchar(struct string *string, char c) { if (string->len >= string->alloc) { char *newdata;