aboutsummaryrefslogtreecommitdiff
path: root/build
blob: b6d36533abdfecebbf3f1cad268165f1be646e4c (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
#!/usr/bin/perl

# build -- process and act on embedded build instructions

use strict;
use warnings;

# parse arguments

my ($debug, $fork) = (0, 0);
my $usage = "usage: $0 [-dddf] file [...]\n";

while (@ARGV and ($_ = $ARGV[0]) =~ /^-/) {
	shift @ARGV;
	last if $_ eq '--';
	$debug++ for /(d)/g;
	$fork++ if /f/;
	die $usage if /[^-df]/;
}

die $usage if not @ARGV;

# find build line(s) in each file

my $i;
for my $file (@ARGV) {
	my ($cmd, $target, @deps);
	open my $f, '<', $file or die "could not open $file: $!\n";
	$i = 1;
	while (<$f>) {
		if (not $cmd and m{
			^ .*
			(?: (?:build|generate) \s+ (?:it \s+)? with
			  | (?:built|generated) \s+ with
			  | the \s+ command
			  | run(?:ning)?
			  | issu(?:e|ing)
			) \s+
			(.+?) \s* (?: > \s* (.+?))? \.? \s*
			(?:\*/)? \s* $
		}x) {
			warn "$file build line: $_" if $debug > 2;
			$cmd = $1;
			$target = $2;
		}
		elsif (not @deps and m{
			^ .*
			(?: depends \s+ on
			  | dependent \s+ on
			) \s+
			(?: the \s+ files? \s+ )?
			(.+?) \.? \s*
			(?:\*/)? \s* $
		}x) {
			warn "$file dependency line: $_" if $debug > 2;
			push @deps, $_ for split /,?\s+/, $1;
			if ($deps[-2] eq 'and') {
				$deps[-2] = $deps[-1];
				pop @deps;
			}
		}
		last if ++$i > 20;
	}
	warn "$file dependencies: @deps\n" if $debug > 1;
	build($file, $cmd, $target, @deps) if $cmd;
	warn "$file: no build line found\n" if not $cmd;
}

# build target according to build line

sub build {
	my ($source, $cmd, $target, @deps) = @_;
	my $m = (stat$target)[9];

	if (! -e $target) {
		warn "$source: building because $target does not exist\n"
			if $debug;
		goto update;
	}

	for ($source, @deps) {
		if (! -e $_) {
			warn "$source: non-existent dependency '$_'\n";
			next;
		}
		if ($m < (stat$_)[9]) {
			warn "$source: building because $_ is modified\n"
				if $debug;
			goto update;
		}
	}
	warn "$source: $target already up-to-date\n";
	return;

update:
	warn "$source: $cmd > $target\n";
	if ($fork) {
		exec('/bin/sh', '-c', "$cmd > $target") if fork() == 0;
	} else {
		system("$cmd > $target");
	}
	return;
}