template

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

template.c (1296B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 FILE *inin;
      6 
      7 static void *
      8 usage() {
      9 	fprintf(stderr, "template [-d delim] [-h] [file|-]\n");
     10 }
     11 
     12 static char *
     13 readto(FILE *f, char d) {
     14 	static char word[128];
     15 	char *w = word;
     16 	char c;
     17 	
     18 	while ((c = getc(f)) != EOF) {
     19 		if (c == d)
     20 			break;
     21 		*w = c;
     22 		w++;
     23 		if (w - word == 128) {
     24 			fprintf(stderr, "variable name too long\n");
     25 		       	exit(1);	
     26 		}
     27 	}
     28 	*w = 0;
     29 	return word;
     30 }
     31 
     32 int
     33 main(int argc, char **argv) {
     34 	int i;
     35 	char c, p, delim = ':';
     36 	char *last = argv[argc - 1];
     37 	char *varname, *var;
     38 
     39 	for (i = 1; i < argc; i++) {
     40 		if (argv[i][0] == '-' && argv[i][2] == 0) {
     41 			switch (argv[i][1]) {
     42 			case 'd':
     43 				i++;
     44 				delim = argv[i][0];
     45 				break;
     46 			case 'h':
     47 			default:
     48 				usage();
     49 				return 0;
     50 			}
     51 		} else {
     52 			if (strcmp(last, "-") == 0)
     53 				inin = stdin;
     54 			else {
     55 				inin = fopen(last, "r");
     56 				if (!inin)
     57 					perror("Couldn't open file");
     58 			}
     59 		}
     60 	}
     61 	if (!inin) 
     62 		inin = stdin;
     63 	
     64 	for (c = getc(inin); c != EOF; c = getc(inin)) {
     65 		if (c == delim && p != '\\') {
     66 			varname = readto(inin, delim);
     67 			if (var = getenv(varname))
     68 				printf("%s", var);
     69 			else {
     70 				fflush(stdout);
     71 				fprintf(stderr, "no var called %s\n", varname);
     72 				exit(1);
     73 			}
     74 		} else 
     75 			putchar(c);
     76 		p = c;
     77 	}
     78 
     79 	return 0;
     80 }