ninja_syntax.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #!/usr/bin/python
  2. """Python module for generating .ninja files.
  3. Note that this is emphatically not a required piece of Ninja; it's
  4. just a helpful utility for build-file-generation systems that already
  5. use Python.
  6. """
  7. import re
  8. import textwrap
  9. def escape_path(word):
  10. return word.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')
  11. class Writer(object):
  12. def __init__(self, output, width=78):
  13. self.output = output
  14. self.width = width
  15. def newline(self):
  16. self.output.write('\n')
  17. def comment(self, text):
  18. for line in textwrap.wrap(text, self.width - 2, break_long_words=False,
  19. break_on_hyphens=False):
  20. self.output.write('# ' + line + '\n')
  21. def variable(self, key, value, indent=0):
  22. if value is None:
  23. return
  24. if isinstance(value, list):
  25. value = ' '.join(filter(None, value)) # Filter out empty strings.
  26. self._line('%s = %s' % (key, value), indent)
  27. def pool(self, name, depth):
  28. self._line('pool %s' % name)
  29. self.variable('depth', depth, indent=1)
  30. def rule(self, name, command, description=None, depfile=None,
  31. generator=False, pool=None, restat=False, rspfile=None,
  32. rspfile_content=None, deps=None):
  33. self._line('rule %s' % name)
  34. self.variable('command', command, indent=1)
  35. if description:
  36. self.variable('description', description, indent=1)
  37. if depfile:
  38. self.variable('depfile', depfile, indent=1)
  39. if generator:
  40. self.variable('generator', '1', indent=1)
  41. if pool:
  42. self.variable('pool', pool, indent=1)
  43. if restat:
  44. self.variable('restat', '1', indent=1)
  45. if rspfile:
  46. self.variable('rspfile', rspfile, indent=1)
  47. if rspfile_content:
  48. self.variable('rspfile_content', rspfile_content, indent=1)
  49. if deps:
  50. self.variable('deps', deps, indent=1)
  51. def build(self, outputs, rule, inputs=None, implicit=None, order_only=None,
  52. variables=None, implicit_outputs=None, pool=None):
  53. outputs = as_list(outputs)
  54. out_outputs = [escape_path(x) for x in outputs]
  55. all_inputs = [escape_path(x) for x in as_list(inputs)]
  56. if implicit:
  57. implicit = [escape_path(x) for x in as_list(implicit)]
  58. all_inputs.append('|')
  59. all_inputs.extend(implicit)
  60. if order_only:
  61. order_only = [escape_path(x) for x in as_list(order_only)]
  62. all_inputs.append('||')
  63. all_inputs.extend(order_only)
  64. if implicit_outputs:
  65. implicit_outputs = [escape_path(x)
  66. for x in as_list(implicit_outputs)]
  67. out_outputs.append('|')
  68. out_outputs.extend(implicit_outputs)
  69. self._line('build %s: %s' % (' '.join(out_outputs),
  70. ' '.join([rule] + all_inputs)))
  71. if pool is not None:
  72. self._line(' pool = %s' % pool)
  73. if variables:
  74. if isinstance(variables, dict):
  75. iterator = iter(variables.items())
  76. else:
  77. iterator = iter(variables)
  78. for key, val in iterator:
  79. self.variable(key, val, indent=1)
  80. return outputs
  81. def include(self, path):
  82. self._line('include %s' % path)
  83. def subninja(self, path):
  84. self._line('subninja %s' % path)
  85. def default(self, paths):
  86. self._line('default %s' % ' '.join(as_list(paths)))
  87. def _count_dollars_before_index(self, s, i):
  88. """Returns the number of '$' characters right in front of s[i]."""
  89. dollar_count = 0
  90. dollar_index = i - 1
  91. while dollar_index > 0 and s[dollar_index] == '$':
  92. dollar_count += 1
  93. dollar_index -= 1
  94. return dollar_count
  95. def _line(self, text, indent=0):
  96. """Write 'text' word-wrapped at self.width characters."""
  97. leading_space = ' ' * indent
  98. while len(leading_space) + len(text) > self.width:
  99. # The text is too wide; wrap if possible.
  100. # Find the rightmost space that would obey our width constraint and
  101. # that's not an escaped space.
  102. available_space = self.width - len(leading_space) - len(' $')
  103. space = available_space
  104. while True:
  105. space = text.rfind(' ', 0, space)
  106. if (space < 0 or
  107. self._count_dollars_before_index(text, space) % 2 == 0):
  108. break
  109. if space < 0:
  110. # No such space; just use the first unescaped space we can find.
  111. space = available_space - 1
  112. while True:
  113. space = text.find(' ', space + 1)
  114. if (space < 0 or
  115. self._count_dollars_before_index(text, space) % 2 == 0):
  116. break
  117. if space < 0:
  118. # Give up on breaking.
  119. break
  120. self.output.write(leading_space + text[0:space] + ' $\n')
  121. text = text[space+1:]
  122. # Subsequent lines are continuations, so indent them.
  123. leading_space = ' ' * (indent+2)
  124. self.output.write(leading_space + text + '\n')
  125. def close(self):
  126. self.output.close()
  127. def as_list(input):
  128. if input is None:
  129. return []
  130. if isinstance(input, list):
  131. return input
  132. return [input]
  133. def escape(string):
  134. """Escape a string such that it can be embedded into a Ninja file without
  135. further interpretation."""
  136. assert '\n' not in string, 'Ninja syntax does not allow newlines'
  137. # We only have one special metacharacter: '$'.
  138. return string.replace('$', '$$')
  139. def expand(string, vars, local_vars={}):
  140. """Expand a string containing $vars as Ninja would.
  141. Note: doesn't handle the full Ninja variable syntax, but it's enough
  142. to make configure.py's use of it work.
  143. """
  144. def exp(m):
  145. var = m.group(1)
  146. if var == '$':
  147. return '$'
  148. return local_vars.get(var, vars.get(var, ''))
  149. return re.sub(r'\$(\$|\w*)', exp, string)