Add _filename variable

This commit is contained in:
2024-02-10 22:23:47 -06:00
parent fcafd8d7b8
commit 0ce53941ec
3 changed files with 51 additions and 2 deletions

View File

@@ -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);

View File

@@ -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;
}

View File

@@ -3,7 +3,7 @@
#include <strings.h>
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;