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
|
#include <ctype.h>
#include <err.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#define USAGE "usage: %s file [...]\n", argv[0]
int
main(int argc, char *argv[])
{
char *b, *bb, *bbb, buf[1024], *cmd[32], dep[1024], *t, *tt, tgt[64];
FILE *fp;
int i, icmd, j, max;
struct stat sb, ssb;
tgt[0] = dep[0] = 0;
/* process arguments */
if (argc-1 == 0) {
fprintf(stderr, USAGE);
return 1;
}
/* allocate memory */
for (i = 0; i < 32; i++) {
cmd[i] = malloc(1024*sizeof(char));
if (!cmd[i]) err(1, "malloc");
}
/* process each file */
for (i = 1, icmd = 0; i < argc; i++, icmd = 0) {
fp = fopen(argv[i], "r");
if (!fp) err(1, "fopen");
/* read line by line */
while (fgets(buf, sizeof(buf), fp)) {
buf[strcspn(buf, "\n")] = 0;
/* parse line */
b = buf;
for (b++; *b; b++) {
if (!(*(b+1) && *(b+2) && *(b+3))) continue;
if (!(*b == ' ' || *b == ' ')) continue;
/* command line */
if (*(b+1) == '$' && *(b+2) == ' ') {
strncpy(cmd[icmd++],b+3,sizeof(buf)-1);
/* find target */
for (b = b+3; *b; b++) {
if (!(*b+1)) continue;
if (*b != '>') continue;
strncpy(tgt,b+1,sizeof(tgt)-1);
}
continue;
}
/* depend line */
if (*(b+1) == '%' && *(b+2) == ' ') {
strncpy(dep, b+3, sizeof(dep)-1);
continue;
}
}
}
if (!icmd) {
fprintf(stderr, "%s: no command line found\n", argv[i]);
continue;
}
if (!*tgt)
goto build;
/* compare source > target */
for (t = tgt; *t; t++)
if (!isspace(*t)) break;
for (tt = tgt; *tt; tt++)
if (isspace(*tt)) { *tt = 0; break; }
if (stat(t, &ssb))
err(1, t);
if (stat(argv[i], &sb))
err(1, argv[i]);
if (sb.st_mtime > ssb.st_mtime)
goto build;
/* compare dependencies > target */
if (*dep) {
for (t = dep; *t; t++)
if (!isspace(*t)) break;
for (j = 0; t[j]; j++) {
if (isspace(t[j]) || t[j+1] == 0) {
tt = strdup(t);
tt[j+(t[j+1]==0)] = 0;
if (stat(tt, &sb))
err(1, tt);
free(tt);
if (sb.st_mtime > ssb.st_mtime)
goto build;
for (; t[j]; j++)
if (!isspace(t[j])) break;
t += j;
j = 0;
}
}
}
fprintf(stderr, "%s: already up-to-date\n", argv[i]);
goto done;
build:
/* run commands */
for (j = 0; j < icmd; j++) {
fprintf(stderr, "%s: %s\n", argv[i], cmd[j]);
system(cmd[j]);
}
done:
fclose(fp);
}
}
|