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): 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 101 if variables: 102 if isinstance(variables, dict): 103 iterator = iter(variables.items()) 104 else: 105 iterator = iter(variables) 106 107 for key, val in iterator: 108 self.variable(key, val, indent=1) 109 110 return outputs 111 112 def include(self, path): 113 self._line('include %s' % path) 114 115 def subninja(self, path): 116 self._line('subninja %s' % path) 117 118 def default(self, paths): 119 self._line('default %s' % ' '.join(as_list(paths))) 120 121 def _count_dollars_before_index(self, s, i): 122 """Returns the number of '$' characters right in front of s[i].""" 123 dollar_count = 0 124 dollar_index = i - 1 125 while dollar_index > 0 and s[dollar_index] == '$': 126 dollar_count += 1 127 dollar_index -= 1 128 return dollar_count 129 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. 135 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 140 while True: 141 space = text.rfind(' ', 0, space) 142 if (space < 0 or 143 self._count_dollars_before_index(text, space) % 2 == 0): 144 break 145 146 if space < 0: 147 # No such space; just use the first unescaped space we can find. 148 space = available_space - 1 149 while True: 150 space = text.find(' ', space + 1) 151 if (space < 0 or 152 self._count_dollars_before_index(text, space) % 2 == 0): 153 break 154 if space < 0: 155 # Give up on breaking. 156 break 157 158 self.output.write(leading_space + text[0:space] + ' $\n') 159 text = text[space+1:] 160 161 # Subsequent lines are continuations, so indent them. 162 leading_space = ' ' * (indent+2) 163 164 self.output.write(leading_space + text + '\n') 165 166 def close(self): 167 self.output.close() 168 169 170def as_list(input): 171 if input is None: 172 return [] 173 if isinstance(input, list): 174 return input 175 return [input] 176 177 178def escape(string): 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('$', '$$') 184 185 186def expand(string, vars, local_vars={}): 187 """Expand a string containing $vars as Ninja would. 188 189 Note: doesn't handle the full Ninja variable syntax, but it's enough 190 to make configure.py's use of it work. 191 """ 192 def exp(m): 193 var = m.group(1) 194 if var == '$': 195 return '$' 196 return local_vars.get(var, vars.get(var, '')) 197 return re.sub(r'\$(\$|\w*)', exp, string) 198