blob: 65870acda8d1a12176fe6e84a78d061e7e14c8fb [file] [log] [blame]
Peter Collingbourned5395fb2012-01-08 22:09:58 +00001import ninja_syntax
2import os
3
4# Simple meta-build system.
5
6class Make(object):
7 def __init__(self):
8 self.output = open(self.output_filename(), 'w')
9 self.rules = {}
10 self.rule_text = ''
11 self.all_targets = []
12 self.clean_files = []
13 self.distclean_files = []
14 self.output.write("""all::
15
16ifndef VERBOSE
17 Verb = @
18endif
19
20""")
21
22 def output_filename(self):
23 return 'Makefile'
24
25 def rule(self, name, command, description=None, depfile=None,
26 generator=False):
27 self.rules[name] = {'command': command, 'description': description,
28 'depfile': depfile, 'generator': generator}
29
30 def build(self, output, rule, inputs=[], implicit=[], order_only=[]):
31 inputs = self._as_list(inputs)
32 implicit = self._as_list(implicit)
33 order_only = self._as_list(order_only)
34
35 output_dir = os.path.dirname(output)
36 if output_dir != '' and not os.path.isdir(output_dir):
37 os.makedirs(output_dir)
38
39 dollar_in = ' '.join(inputs)
40 subst = lambda text: text.replace('$in', dollar_in).replace('$out', output)
41
42 deps = ' '.join(inputs + implicit)
43 if order_only:
44 deps += ' | '
45 deps += ' '.join(order_only)
46 self.output.write('%s: %s\n' % (output, deps))
47
48 r = self.rules[rule]
49 command = subst(r['command'])
50 if r['description']:
51 desc = subst(r['description'])
52 self.output.write('\t@echo %s\n\t$(Verb) %s\n' % (desc, command))
53 else:
54 self.output.write('\t%s\n' % command)
55 if r['depfile']:
56 depfile = subst(r['depfile'])
57 self.output.write('-include '+depfile+'\n')
58 self.output.write('\n')
59
60 self.all_targets.append(output)
61 if r['generator']:
62 self.distclean_files.append(output)
63 else:
64 self.clean_files.append(output)
65
66 def _as_list(self, input):
67 if isinstance(input, list):
68 return input
69 return [input]
70
71 def finish(self):
72 self.output.write('all:: %s\n\n' % ' '.join(self.all_targets))
73 self.output.write('clean: \n\trm -f %s\n\n' % ' '.join(self.clean_files))
74 self.output.write('distclean: clean\n\trm -f %s\n' % ' '.join(self.distclean_files))
75
76class Ninja(ninja_syntax.Writer):
77 def __init__(self):
78 ninja_syntax.Writer.__init__(self, open(self.output_filename(), 'w'))
79
80 def output_filename(self):
81 return 'build.ninja'
82
83 def finish(self):
84 pass
85
86def from_name(name):
87 if name == 'make':
88 return Make()
89 if name == 'ninja':
90 return Ninja()
91 raise LookupError, 'unknown generator: %s; supported generators are make and ninja' % name