template

a simple template tool for shell scripts
Log | Files | Refs

commit b0e09ddca612774abe589daa1e6b6bc53b11386e
Author: thing1 <thing1@seacrossedlovers.xyz>
Date:   Fri, 22 Aug 2025 22:10:23 +0100

init commit

Diffstat:
A.gitignore | 1+
AMakefile | 17+++++++++++++++++
Aexamples/example.html | 1+
Aexamples/example.log | 4++++
Aexamples/loggen.sh | 7+++++++
Aexamples/template.c | 0
Atemplate.c | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 110 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +template diff --git a/Makefile b/Makefile @@ -0,0 +1,17 @@ +CFLAGS=-ggdb +SRC=template.c +DIR=/usr/local/bin + +all: template + +template: ${SRC} + cc ${SRC} -o template ${CFLAGS} + +clean: + rm template + +install: template + cp template ${DIR}/ + +uninstall: + rm ${DIR}/template diff --git a/examples/example.html b/examples/example.html @@ -0,0 +1 @@ +<p>:DISPLAY:</p> diff --git a/examples/example.log b/examples/example.log @@ -0,0 +1,4 @@ +time: $time$ +name: $name$ +user: $user$ +dir: $dir$ diff --git a/examples/loggen.sh b/examples/loggen.sh @@ -0,0 +1,7 @@ +#!/bin/sh +export time=$(date) +export name=$(uname -a) +export user=$(whoami) +export dir=$(pwd) + +template -d '$' example.log diff --git a/examples/template.c b/examples/template.c diff --git a/template.c b/template.c @@ -0,0 +1,80 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +FILE *inin; + +static void * +usage() { + fprintf(stderr, "template [-d delim] [-h] [file|-]\n"); +} + +static char * +readto(FILE *f, char d) { + static char word[128]; + char *w = word; + char c; + + while ((c = getc(f)) != EOF) { + if (c == d) + break; + *w = c; + w++; + if (w - word == 128) { + fprintf(stderr, "variable name too long\n"); + exit(1); + } + } + *w = 0; + return word; +} + +int +main(int argc, char **argv) { + int i; + char c, p, delim = ':'; + char *last = argv[argc - 1]; + char *varname, *var; + + for (i = 1; i < argc; i++) { + if (argv[i][0] == '-' && argv[i][2] == 0) { + switch (argv[i][1]) { + case 'd': + i++; + delim = argv[i][0]; + break; + case 'h': + default: + usage(); + return 0; + } + } else { + if (strcmp(last, "-") == 0) + inin = stdin; + else { + inin = fopen(last, "r"); + if (!inin) + perror("Couldn't open file"); + } + } + } + if (!inin) + inin = stdin; + + for (c = getc(inin); c != EOF; c = getc(inin)) { + if (c == delim && p != '\\') { + varname = readto(inin, delim); + if (var = getenv(varname)) + printf("%s", var); + else { + fflush(stdout); + fprintf(stderr, "no var called %s\n", varname); + exit(1); + } + } else + putchar(c); + p = c; + } + + return 0; +}