aboutsummaryrefslogtreecommitdiff
path: root/shtpl.c
blob: 3db16b08a3c1392bff17676c5b782d2615d20b64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE 1024
#define MAX_COMMANDSIZE 4096

static void	 addc(char, int);
static void	 blank(size_t);
static void	 dotemplate();
static void	 shtpl(FILE*);

enum states {
	TEXT = 0,
	BEGIN_T,
	IN_T,
	END_T
};

char cmd[MAX_COMMANDSIZE];

int
main(int argc, char **argv)
{
	FILE *f;
	int i;

	if (argc == 1)
		shtpl(stdin);
	else {
		for (i = 1; i < argc; i++) {
			f = fopen(argv[i], "r");
			if (f == NULL) {
				fprintf(stderr, "Error opening %s\n", argv[i]);
				continue;
			}
			shtpl(f);
			fclose(f);
		}
	}

	return 0;
}

static void
addc(char c, int pos)
{
	if (pos + 2 >= MAX_COMMANDSIZE) {
		fprintf(stderr, "Command too long %s\n", cmd);
		exit(1);
	}

	cmd[pos] = c;
}

static void
blank(size_t size)
{
	memset(cmd, 0, size);
}

static void
dotemplate()
{
	char c1, c2;
	FILE *pipe;

	pipe = popen(cmd, "r");
	c1 = getc(pipe);
	while ((c2 = getc(pipe)) != EOF) {
		printf("%c", c1);
		c1 = c2;
	}
	if (c1 != '\n')
		printf("%c", c1);
	pclose(pipe);
}

static void
shtpl(FILE *f)
{
	char c;
	char buf[BUFSIZE];
	size_t i;
        enum states state;
	int pos;

	blank(MAX_COMMANDSIZE);
	state = TEXT;
	pos = 0;

        while (fgets(buf, BUFSIZE, f)) {
                for (i = 0, c = buf[i]; i < BUFSIZE && c != '\0'; i++, c = buf[i] )
			switch (state) {
			case TEXT:
				if (c == '{')
					state = BEGIN_T;
				else
					printf("%c", c);
				break;
			case BEGIN_T:
				if (c == '{')
					state = IN_T;
				else {
					state = TEXT;
					printf("{%c", c);
				}
				break;
			case END_T:
				if (c == '}') {
					state = TEXT;
					addc('\0', pos);
					dotemplate();
					blank(MAX_COMMANDSIZE);
					pos = 0;
				} else {
					state = IN_T;
					addc('}', pos++);
					addc(c, pos++);
				}
				break;
			case IN_T:
				if (c == '}')
					state = END_T;
				else
					addc(c, pos++);
				break;
			default:
				assert(0 && "Unknown state");
                        }
	}
}