1#!/usr/bin/python 2 3# Copyright 2011 Google Inc. All Rights Reserved. 4# 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 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 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. 16 17"""Python module for generating .ninja files. 18 19Note that this is emphatically not a required piece of Ninja; it's 20just a helpful utility for build-file-generation systems that already 21use Python. 22""" 23 24import re 25import textwrap 26 27def escape_path(word): 28 return word.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:') 29 30class Writer(object): 31 def __init__(self, output, width=78): 32 self.output = output 33 self.width = width 34 35 def newline(self): 36 self.output.write('\n') 37 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') 42 43 def variable(self, key, value, indent=0): 44 if value is None: 45 return 46 if isinstance(value, list): 47 value = ' '.join(filter(None, value)) # Filter out empty strings. 48 self._line('%s = %s' % (key, value), indent) 49 50 def pool(self, name, depth): 51 self._line('pool %s' % name) 52 self.variable('depth', depth, indent=1) 53 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) 59 if description: 60 self.variable('description', description, indent=1) 61 if depfile: 62 self.variable('depfile', depfile, indent=1) 63 if generator: 64 self.variable('generator', '1', indent=1) 65 if pool: 66 self.variable('pool', pool, indent=1) 67 if restat: 68 self.variable('restat', '1', indent=1) 69 if rspfile: 70 self.variable('rspfile', rspfile, indent=1) 71 if rspfile_content: 72 self.variable('rspfile_content', rspfile_content, indent=1) 73 if deps: 74 self.variable('deps', deps, indent=1) 75 76 def build(self, outputs, rule, inputs=None, implicit=None, order_only=None, 77 variables=None, implicit_outputs=None, pool=None, dyndep=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)] 81 82 if implicit: 83 implicit = [escape_path(x) for x in as_list(implicit)] 84 all_inputs.append('|') 85 all_inputs.extend(implicit) 86 if order_only: 87 order_only = [escape_path(x) for x in as_list(order_only)] 88 all_inputs.append('||') 89 all_inputs.extend(order_only) 90 if implicit_outputs: 91 implicit_outputs = [escape_path(x) 92 for x in as_list(implicit_outputs)] 93 out_outputs.append('|') 94 out_outputs.extend(implicit_outputs) 95 96 self._line('build %s: %s' % (' '.join(out_outputs), 97 ' '.join([rule] + all_inputs))) 98 if pool is not None: 99 self._line(' pool = %s' % pool) 100 if dyndep is not None: 101 self._line(' dyndep = %s' % dyndep) 102 103 if variables: 104 if isinstance(variables, dict): 105 iterator = iter(variables.items()) 106 else: 107 iterator = iter(variables) 108 109 for key, val in iterator: 110 self.variable(key, val, indent=1) 111 112 return outputs 113 114 def include(self, path): 115 self._line('include %s' % path) 116 117 def subninja(self, path): 118 self._line('subninja %s' % path) 119 120 def default(self, paths): 121 self._line('default %s' % ' '.join(as_list(paths))) 122 123 def _count_dollars_before_index(self, s, i): 124 """Returns the number of '$' characters right in front of s[i].""" 125 dollar_count = 0 126 dollar_index = i - 1 127 while dollar_index > 0 and s[dollar_index] == '$': 128 dollar_count += 1 129 dollar_index -= 1 130 return dollar_count 131 132 def _line(self, text, indent=0): 133 """Write 'text' word-wrapped at self.width characters.""" 134 leading_space = ' ' * indent 135 while len(leading_space) + len(text) > self.width: 136 # The text is too wide; wrap if possible. 137 138 # Find the rightmost space that would obey our width constraint and 139 # that's not an escaped space. 140 available_space = self.width - len(leading_space) - len(' $') 141 space = available_space 142 while True: 143 space = text.rfind(' ', 0, space) 144 if (space < 0 or 145 self._count_dollars_before_index(text, space) % 2 == 0): 146 break 147 148 if space < 0: 149 # No such space; just use the first unescaped space we can find. 150 space = available_space - 1 151 while True: 152 space = text.find(' ', space + 1) 153 if (space < 0 or 154 self._count_dollars_before_index(text, space) % 2 == 0): 155 break 156 if space < 0: 157 # Give up on breaking. 158 break 159 160 self.output.write(leading_space + text[0:space] + ' $\n') 161 text = text[space+1:] 162 163 # Subsequent lines are continuations, so indent them. 164 leading_space = ' ' * (indent+2) 165 166 self.output.write(leading_space + text + '\n') 167 168 def close(self): 169 self.output.close() 170 171 172def as_list(input): 173 if input is None: 174 return [] 175 if isinstance(input, list): 176 return input 177 return [input] 178 179 180def escape(string): 181 """Escape a string such that it can be embedded into a Ninja file without 182 further interpretation.""" 183 assert '\n' not in string, 'Ninja syntax does not allow newlines' 184 # We only have one special metacharacter: '$'. 185 return string.replace('$', '$$') 186 187 188def expand(string, vars, local_vars={}): 189 """Expand a string containing $vars as Ninja would. 190 191 Note: doesn't handle the full Ninja variable syntax, but it's enough 192 to make configure.py's use of it work. 193 """ 194 def exp(m): 195 var = m.group(1) 196 if var == '$': 197 return '$' 198 return local_vars.get(var, vars.get(var, '')) 199 return re.sub(r'\$(\$|\w*)', exp, string) 200