From 2c9c526255ada53d1b75d856e6554e7508740411 Mon Sep 17 00:00:00 2001 From: Werner Almesberger Date: Tue, 26 Jul 2016 03:15:13 -0300 Subject: [PATCH] sch2fig/: new option -Dvar=value to set in template --- sch2fig/fig.c | 31 +++++++++++++++++++++++++++++-- sch2fig/fig.h | 2 +- sch2fig/main.c | 16 +++++++++++++--- 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/sch2fig/fig.c b/sch2fig/fig.c index 90defc8..595bcb6 100644 --- a/sch2fig/fig.c +++ b/sch2fig/fig.c @@ -420,7 +420,32 @@ static void fig_header(void) } -void fig_init(const char *template) +static bool apply_vars(char *buf, int n_vars, const char **vars) +{ + char *p; + const char **var, *eq; + int var_len, value_len; + + p = strchr(buf, '<'); + if (!p) + return 0; + for (var = vars; var != vars + n_vars; var++) { + eq = strchr(*var, '='); + assert(eq); + var_len = eq - *var; + if (strncmp(p + 1, *var, var_len)) + continue; + value_len = strlen(eq + 1); + memmove(p + value_len, p + var_len + 2, + strlen(p + var_len + 2) + 1); + memcpy(p, eq + 1, value_len); + return 1; + } + return 0; +} + + +void fig_init(const char *template, int n_vars, const char **vars) { FILE *file; char buf[1000]; @@ -435,7 +460,9 @@ void fig_init(const char *template) perror(template); exit(1); } - while (fgets(buf, sizeof(buf), file)) + while (fgets(buf, sizeof(buf), file)) { + while (apply_vars(buf, n_vars, vars)); printf("%s", buf); + } fclose(file); } diff --git a/sch2fig/fig.h b/sch2fig/fig.h index c90f27f..528d851 100644 --- a/sch2fig/fig.h +++ b/sch2fig/fig.h @@ -53,6 +53,6 @@ void fig_text(int x, int y, const char *s, unsigned size, /* inititalization */ -void fig_init(const char *template); +void fig_init(const char *template, int n_vars, const char **vars); #endif /* !FIG_H */ diff --git a/sch2fig/main.c b/sch2fig/main.c index 49c7b2c..d0ef7de 100644 --- a/sch2fig/main.c +++ b/sch2fig/main.c @@ -59,7 +59,8 @@ static void read_file(const char *name, void *ctx, static void usage(const char *name) { fprintf(stderr, - "usage: %s [-t template.fig] [file.lib ...] file.sch\n", name); +"usage: %s [-t template.fig] [-Dvar=value ...] [file.lib ...] file.sch\n", + name); exit(1); } @@ -69,12 +70,21 @@ int main(int argc, char **argv) const char *template = NULL; char c; int arg; + int n_vars = 0; + const char **vars = NULL; - while ((c = getopt(argc, argv, "t:")) != EOF) + while ((c = getopt(argc, argv, "t:D:")) != EOF) switch (c) { case 't': template = optarg; break; + case 'D': + if (!strchr(optarg, '=')) + usage(*argv); + n_vars++; + vars = realloc(vars, sizeof(const char *) * n_vars); + vars[n_vars - 1] = optarg; + break; default: usage(*argv); } @@ -82,7 +92,7 @@ int main(int argc, char **argv) if (argc - optind < 1) usage(*argv); - fig_init(template); + fig_init(template, n_vars, vars); for (arg = optind; arg != argc; arg++) { if (arg == argc - 1) { struct sch_ctx ctx;