From dcb7758a74fb5ff4f8b6eecb6589223a408f3f9b Mon Sep 17 00:00:00 2001 From: John Ankarstrom Date: Tue, 6 Jul 2021 21:15:06 +0200 Subject: Rewrite in C --- build.c | 125 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 build.c (limited to 'build.c') diff --git a/build.c b/build.c new file mode 100644 index 0000000..e69164c --- /dev/null +++ b/build.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include +#include +#include + +#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); + } +} -- cgit v1.2.3