3 # Copyright 2011 Google Inc. All Rights Reserved.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 """Python module for generating .ninja files.
19 Note that this is emphatically not a required piece of Ninja; it's
20 just a helpful utility for build-file-generation systems that already
27 def escape_path(word):
28 return word.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')
31 def __init__(self, output, width=78):
36 self.output.write('\n')
38 def comment(self, text):
39 for line in textwrap.wrap(text, self.width - 2, break_long_words=False,
40 break_on_hyphens=False):
41 self.output.write('# ' + line + '\n')
43 def variable(self, key, value, indent=0):
46 if isinstance(value, list):
47 value = ' '.join(filter(None, value)) # Filter out empty strings.
48 self._line('%s = %s' % (key, value), indent)
50 def pool(self, name, depth):
51 self._line('pool %s' % name)
52 self.variable('depth', depth, indent=1)
54 def rule(self, name, command, description=None, depfile=None,
55 generator=False, pool=None, restat=False, rspfile=None,
56 rspfile_content=None, deps=None):
57 self._line('rule %s' % name)
58 self.variable('command', command, indent=1)
60 self.variable('description', description, indent=1)
62 self.variable('depfile', depfile, indent=1)
64 self.variable('generator', '1', indent=1)
66 self.variable('pool', pool, indent=1)
68 self.variable('restat', '1', indent=1)
70 self.variable('rspfile', rspfile, indent=1)
72 self.variable('rspfile_content', rspfile_content, indent=1)
74 self.variable('deps', deps, indent=1)
76 def build(self, outputs, rule, inputs=None, implicit=None, order_only=None,
77 variables=None, implicit_outputs=None, pool=None):
78 outputs = as_list(outputs)
79 out_outputs = [escape_path(x) for x in outputs]
80 all_inputs = [escape_path(x) for x in as_list(inputs)]
83 implicit = [escape_path(x) for x in as_list(implicit)]
84 all_inputs.append('|')
85 all_inputs.extend(implicit)
87 order_only = [escape_path(x) for x in as_list(order_only)]
88 all_inputs.append('||')
89 all_inputs.extend(order_only)
91 implicit_outputs = [escape_path(x)
92 for x in as_list(implicit_outputs)]
93 out_outputs.append('|')
94 out_outputs.extend(implicit_outputs)
96 self._line('build %s: %s' % (' '.join(out_outputs),
97 ' '.join([rule] + all_inputs)))
99 self._line(' pool = %s' % pool)
102 if isinstance(variables, dict):
103 iterator = iter(variables.items())
105 iterator = iter(variables)
107 for key, val in iterator:
108 self.variable(key, val, indent=1)
112 def include(self, path):
113 self._line('include %s' % path)
115 def subninja(self, path):
116 self._line('subninja %s' % path)
118 def default(self, paths):
119 self._line('default %s' % ' '.join(as_list(paths)))
121 def _count_dollars_before_index(self, s, i):
122 """Returns the number of '$' characters right in front of s[i]."""
125 while dollar_index > 0 and s[dollar_index] == '$':
130 def _line(self, text, indent=0):
131 """Write 'text' word-wrapped at self.width characters."""
132 leading_space = ' ' * indent
133 while len(leading_space) + len(text) > self.width:
134 # The text is too wide; wrap if possible.
136 # Find the rightmost space that would obey our width constraint and
137 # that's not an escaped space.
138 available_space = self.width - len(leading_space) - len(' $')
139 space = available_space
141 space = text.rfind(' ', 0, space)
143 self._count_dollars_before_index(text, space) % 2 == 0):
147 # No such space; just use the first unescaped space we can find.
148 space = available_space - 1
150 space = text.find(' ', space + 1)
152 self._count_dollars_before_index(text, space) % 2 == 0):
155 # Give up on breaking.
158 self.output.write(leading_space + text[0:space] + ' $\n')
159 text = text[space+1:]
161 # Subsequent lines are continuations, so indent them.
162 leading_space = ' ' * (indent+2)
164 self.output.write(leading_space + text + '\n')
173 if isinstance(input, list):
179 """Escape a string such that it can be embedded into a Ninja file without
180 further interpretation."""
181 assert '\n' not in string, 'Ninja syntax does not allow newlines'
182 # We only have one special metacharacter: '$'.
183 return string.replace('$', '$$')
186 def expand(string, vars, local_vars={}):
187 """Expand a string containing $vars as Ninja would.
189 Note: doesn't handle the full Ninja variable syntax, but it's enough
190 to make configure.py's use of it work.
196 return local_vars.get(var, vars.get(var, ''))
197 return re.sub(r'\$(\$|\w*)', exp, string)