pddm.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. #! /usr/bin/python
  2. #
  3. # Protocol Buffers - Google's data interchange format
  4. # Copyright 2015 Google Inc. All rights reserved.
  5. # https://developers.google.com/protocol-buffers/
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions are
  9. # met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above
  14. # copyright notice, this list of conditions and the following disclaimer
  15. # in the documentation and/or other materials provided with the
  16. # distribution.
  17. # * Neither the name of Google Inc. nor the names of its
  18. # contributors may be used to endorse or promote products derived from
  19. # this software without specific prior written permission.
  20. #
  21. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. """PDDM - Poor Developers' Debug-able Macros
  33. A simple markup that can be added in comments of source so they can then be
  34. expanded out into code. Most of this could be done with CPP macros, but then
  35. developers can't really step through them in the debugger, this way they are
  36. expanded to the same code, but you can debug them.
  37. Any file can be processed, but the syntax is designed around a C based compiler.
  38. Processed lines start with "//%". There are three types of sections you can
  39. create: Text (left alone), Macro Definitions, and Macro Expansions. There is
  40. no order required between definitions and expansions, all definitions are read
  41. before any expansions are processed (thus, if desired, definitions can be put
  42. at the end of the file to keep them out of the way of the code).
  43. Macro Definitions are started with "//%PDDM-DEFINE Name(args)" and all lines
  44. afterwards that start with "//%" are included in the definition. Multiple
  45. macros can be defined in one block by just using a another "//%PDDM-DEFINE"
  46. line to start the next macro. Optionally, a macro can be ended with
  47. "//%PDDM-DEFINE-END", this can be useful when you want to make it clear that
  48. trailing blank lines are included in the macro. You can also end a definition
  49. with an expansion.
  50. Macro Expansions are started by single lines containing
  51. "//%PDDM-EXPAND Name(args)" and then with "//%PDDM-EXPAND-END" or another
  52. expansions. All lines in-between are replaced by the result of the expansion.
  53. The first line of the expansion is always a blank like just for readability.
  54. Expansion itself is pretty simple, one macro can invoke another macro, but
  55. you cannot nest the invoke of a macro in another macro (i.e. - can't do
  56. "foo(bar(a))", but you can define foo(a) and bar(b) where bar invokes foo()
  57. within its expansion.
  58. When macros are expanded, the arg references can also add "$O" suffix to the
  59. name (i.e. - "NAME$O") to specify an option to be applied. The options are:
  60. $S - Replace each character in the value with a space.
  61. $l - Lowercase the first letter of the value.
  62. $L - Lowercase the whole value.
  63. $u - Uppercase the first letter of the value.
  64. $U - Uppercase the whole value.
  65. Within a macro you can use ## to cause things to get joined together after
  66. expansion (i.e. - "a##b" within a macro will become "ab").
  67. Example:
  68. int foo(MyEnum x) {
  69. switch (x) {
  70. //%PDDM-EXPAND case(Enum_Left, 1)
  71. //%PDDM-EXPAND case(Enum_Center, 2)
  72. //%PDDM-EXPAND case(Enum_Right, 3)
  73. //%PDDM-EXPAND-END
  74. }
  75. //%PDDM-DEFINE case(_A, _B)
  76. //% case _A:
  77. //% return _B;
  78. A macro ends at the start of the next one, or an optional %PDDM-DEFINE-END
  79. can be used to avoid adding extra blank lines/returns (or make it clear when
  80. it is desired).
  81. One macro can invoke another by simply using its name NAME(ARGS). You cannot
  82. nest an invoke inside another (i.e. - NAME1(NAME2(ARGS)) isn't supported).
  83. Within a macro you can use ## to cause things to get joined together after
  84. processing (i.e. - "a##b" within a macro will become "ab").
  85. """
  86. import optparse
  87. import os
  88. import re
  89. import sys
  90. # Regex for macro definition.
  91. _MACRO_RE = re.compile(r'(?P<name>\w+)\((?P<args>.*?)\)')
  92. # Regex for macro's argument definition.
  93. _MACRO_ARG_NAME_RE = re.compile(r'^\w+$')
  94. # Line inserted after each EXPAND.
  95. _GENERATED_CODE_LINE = (
  96. '// This block of code is generated, do not edit it directly.'
  97. )
  98. def _MacroRefRe(macro_names):
  99. # Takes in a list of macro names and makes a regex that will match invokes
  100. # of those macros.
  101. return re.compile(r'\b(?P<macro_ref>(?P<name>(%s))\((?P<args>.*?)\))' %
  102. '|'.join(macro_names))
  103. def _MacroArgRefRe(macro_arg_names):
  104. # Takes in a list of macro arg names and makes a regex that will match
  105. # uses of those args.
  106. return re.compile(r'\b(?P<name>(%s))(\$(?P<option>.))?\b' %
  107. '|'.join(macro_arg_names))
  108. class PDDMError(Exception):
  109. """Error thrown by pddm."""
  110. pass
  111. class MacroCollection(object):
  112. """Hold a set of macros and can resolve/expand them."""
  113. def __init__(self, a_file=None):
  114. """Initializes the collection.
  115. Args:
  116. a_file: The file like stream to parse.
  117. Raises:
  118. PDDMError if there are any issues.
  119. """
  120. self._macros = dict()
  121. if a_file:
  122. self.ParseInput(a_file)
  123. class MacroDefinition(object):
  124. """Holds a macro definition."""
  125. def __init__(self, name, arg_names):
  126. self._name = name
  127. self._args = tuple(arg_names)
  128. self._body = ''
  129. self._needNewLine = False
  130. def AppendLine(self, line):
  131. if self._needNewLine:
  132. self._body += '\n'
  133. self._body += line
  134. self._needNewLine = not line.endswith('\n')
  135. @property
  136. def name(self):
  137. return self._name
  138. @property
  139. def args(self):
  140. return self._args
  141. @property
  142. def body(self):
  143. return self._body
  144. def ParseInput(self, a_file):
  145. """Consumes input extracting definitions.
  146. Args:
  147. a_file: The file like stream to parse.
  148. Raises:
  149. PDDMError if there are any issues.
  150. """
  151. input_lines = a_file.read().splitlines()
  152. self.ParseLines(input_lines)
  153. def ParseLines(self, input_lines):
  154. """Parses list of lines.
  155. Args:
  156. input_lines: A list of strings of input to parse (no newlines on the
  157. strings).
  158. Raises:
  159. PDDMError if there are any issues.
  160. """
  161. current_macro = None
  162. for line in input_lines:
  163. if line.startswith('PDDM-'):
  164. directive = line.split(' ', 1)[0]
  165. if directive == 'PDDM-DEFINE':
  166. name, args = self._ParseDefineLine(line)
  167. if self._macros.get(name):
  168. raise PDDMError('Attempt to redefine macro: "%s"' % line)
  169. current_macro = self.MacroDefinition(name, args)
  170. self._macros[name] = current_macro
  171. continue
  172. if directive == 'PDDM-DEFINE-END':
  173. if not current_macro:
  174. raise PDDMError('Got DEFINE-END directive without an active macro:'
  175. ' "%s"' % line)
  176. current_macro = None
  177. continue
  178. raise PDDMError('Hit a line with an unknown directive: "%s"' % line)
  179. if current_macro:
  180. current_macro.AppendLine(line)
  181. continue
  182. # Allow blank lines between macro definitions.
  183. if line.strip() == '':
  184. continue
  185. raise PDDMError('Hit a line that wasn\'t a directive and no open macro'
  186. ' definition: "%s"' % line)
  187. def _ParseDefineLine(self, input_line):
  188. assert input_line.startswith('PDDM-DEFINE')
  189. line = input_line[12:].strip()
  190. match = _MACRO_RE.match(line)
  191. # Must match full line
  192. if match is None or match.group(0) != line:
  193. raise PDDMError('Failed to parse macro definition: "%s"' % input_line)
  194. name = match.group('name')
  195. args_str = match.group('args').strip()
  196. args = []
  197. if args_str:
  198. for part in args_str.split(','):
  199. arg = part.strip()
  200. if arg == '':
  201. raise PDDMError('Empty arg name in macro definition: "%s"'
  202. % input_line)
  203. if not _MACRO_ARG_NAME_RE.match(arg):
  204. raise PDDMError('Invalid arg name "%s" in macro definition: "%s"'
  205. % (arg, input_line))
  206. if arg in args:
  207. raise PDDMError('Arg name "%s" used more than once in macro'
  208. ' definition: "%s"' % (arg, input_line))
  209. args.append(arg)
  210. return (name, tuple(args))
  211. def Expand(self, macro_ref_str):
  212. """Expands the macro reference.
  213. Args:
  214. macro_ref_str: String of a macro reference (i.e. foo(a, b)).
  215. Returns:
  216. The text from the expansion.
  217. Raises:
  218. PDDMError if there are any issues.
  219. """
  220. match = _MACRO_RE.match(macro_ref_str)
  221. if match is None or match.group(0) != macro_ref_str:
  222. raise PDDMError('Failed to parse macro reference: "%s"' % macro_ref_str)
  223. if match.group('name') not in self._macros:
  224. raise PDDMError('No macro named "%s".' % match.group('name'))
  225. return self._Expand(match, [], macro_ref_str)
  226. def _FormatStack(self, macro_ref_stack):
  227. result = ''
  228. for _, macro_ref in reversed(macro_ref_stack):
  229. result += '\n...while expanding "%s".' % macro_ref
  230. return result
  231. def _Expand(self, macro_ref_match, macro_stack, macro_ref_str=None):
  232. if macro_ref_str is None:
  233. macro_ref_str = macro_ref_match.group('macro_ref')
  234. name = macro_ref_match.group('name')
  235. for prev_name, prev_macro_ref in macro_stack:
  236. if name == prev_name:
  237. raise PDDMError('Found macro recursion, invoking "%s":%s' %
  238. (macro_ref_str, self._FormatStack(macro_stack)))
  239. macro = self._macros[name]
  240. args_str = macro_ref_match.group('args').strip()
  241. args = []
  242. if args_str or len(macro.args):
  243. args = [x.strip() for x in args_str.split(',')]
  244. if len(args) != len(macro.args):
  245. raise PDDMError('Expected %d args, got: "%s".%s' %
  246. (len(macro.args), macro_ref_str,
  247. self._FormatStack(macro_stack)))
  248. # Replace args usages.
  249. result = self._ReplaceArgValues(macro, args, macro_ref_str, macro_stack)
  250. # Expand any macro invokes.
  251. new_macro_stack = macro_stack + [(name, macro_ref_str)]
  252. while True:
  253. eval_result = self._EvalMacrosRefs(result, new_macro_stack)
  254. # Consume all ## directives to glue things together.
  255. eval_result = eval_result.replace('##', '')
  256. if eval_result == result:
  257. break
  258. result = eval_result
  259. return result
  260. def _ReplaceArgValues(self,
  261. macro, arg_values, macro_ref_to_report, macro_stack):
  262. if len(arg_values) == 0:
  263. # Nothing to do
  264. return macro.body
  265. assert len(arg_values) == len(macro.args)
  266. args = dict(zip(macro.args, arg_values))
  267. def _lookupArg(match):
  268. val = args[match.group('name')]
  269. opt = match.group('option')
  270. if opt:
  271. if opt == 'S': # Spaces for the length
  272. return ' ' * len(val)
  273. elif opt == 'l': # Lowercase first character
  274. if val:
  275. return val[0].lower() + val[1:]
  276. else:
  277. return val
  278. elif opt == 'L': # All Lowercase
  279. return val.lower()
  280. elif opt == 'u': # Uppercase first character
  281. if val:
  282. return val[0].upper() + val[1:]
  283. else:
  284. return val
  285. elif opt == 'U': # All Uppercase
  286. return val.upper()
  287. else:
  288. raise PDDMError('Unknown arg option "%s$%s" while expanding "%s".%s'
  289. % (match.group('name'), match.group('option'),
  290. macro_ref_to_report,
  291. self._FormatStack(macro_stack)))
  292. return val
  293. # Let the regex do the work!
  294. macro_arg_ref_re = _MacroArgRefRe(macro.args)
  295. return macro_arg_ref_re.sub(_lookupArg, macro.body)
  296. def _EvalMacrosRefs(self, text, macro_stack):
  297. macro_ref_re = _MacroRefRe(self._macros.keys())
  298. def _resolveMacro(match):
  299. return self._Expand(match, macro_stack)
  300. return macro_ref_re.sub(_resolveMacro, text)
  301. class SourceFile(object):
  302. """Represents a source file with PDDM directives in it."""
  303. def __init__(self, a_file, import_resolver=None):
  304. """Initializes the file reading in the file.
  305. Args:
  306. a_file: The file to read in.
  307. import_resolver: a function that given a path will return a stream for
  308. the contents.
  309. Raises:
  310. PDDMError if there are any issues.
  311. """
  312. self._sections = []
  313. self._original_content = a_file.read()
  314. self._import_resolver = import_resolver
  315. self._processed_content = None
  316. class SectionBase(object):
  317. def __init__(self, first_line_num):
  318. self._lines = []
  319. self._first_line_num = first_line_num
  320. def TryAppend(self, line, line_num):
  321. """Try appending a line.
  322. Args:
  323. line: The line to append.
  324. line_num: The number of the line.
  325. Returns:
  326. A tuple of (SUCCESS, CAN_ADD_MORE). If SUCCESS if False, the line
  327. wasn't append. If SUCCESS is True, then CAN_ADD_MORE is True/False to
  328. indicate if more lines can be added after this one.
  329. """
  330. assert False, "subclass should have overridden"
  331. return (False, False)
  332. def HitEOF(self):
  333. """Called when the EOF was reached for for a given section."""
  334. pass
  335. def BindMacroCollection(self, macro_collection):
  336. """Binds the chunk to a macro collection.
  337. Args:
  338. macro_collection: The collection to bind too.
  339. """
  340. pass
  341. def Append(self, line):
  342. self._lines.append(line)
  343. @property
  344. def lines(self):
  345. return self._lines
  346. @property
  347. def num_lines_captured(self):
  348. return len(self._lines)
  349. @property
  350. def first_line_num(self):
  351. return self._first_line_num
  352. @property
  353. def first_line(self):
  354. if not self._lines:
  355. return ''
  356. return self._lines[0]
  357. @property
  358. def text(self):
  359. return '\n'.join(self.lines) + '\n'
  360. class TextSection(SectionBase):
  361. """Text section that is echoed out as is."""
  362. def TryAppend(self, line, line_num):
  363. if line.startswith('//%PDDM'):
  364. return (False, False)
  365. self.Append(line)
  366. return (True, True)
  367. class ExpansionSection(SectionBase):
  368. """Section that is the result of an macro expansion."""
  369. def __init__(self, first_line_num):
  370. SourceFile.SectionBase.__init__(self, first_line_num)
  371. self._macro_collection = None
  372. def TryAppend(self, line, line_num):
  373. if line.startswith('//%PDDM'):
  374. directive = line.split(' ', 1)[0]
  375. if directive == '//%PDDM-EXPAND':
  376. self.Append(line)
  377. return (True, True)
  378. if directive == '//%PDDM-EXPAND-END':
  379. assert self.num_lines_captured > 0
  380. return (True, False)
  381. raise PDDMError('Ran into directive ("%s", line %d) while in "%s".' %
  382. (directive, line_num, self.first_line))
  383. # Eat other lines.
  384. return (True, True)
  385. def HitEOF(self):
  386. raise PDDMError('Hit the end of the file while in "%s".' %
  387. self.first_line)
  388. def BindMacroCollection(self, macro_collection):
  389. self._macro_collection = macro_collection
  390. @property
  391. def lines(self):
  392. captured_lines = SourceFile.SectionBase.lines.fget(self)
  393. directive_len = len('//%PDDM-EXPAND')
  394. result = []
  395. for line in captured_lines:
  396. result.append(line)
  397. if self._macro_collection:
  398. # Always add a blank line, seems to read better. (If need be, add an
  399. # option to the EXPAND to indicate if this should be done.)
  400. result.extend([_GENERATED_CODE_LINE, '// clang-format off', ''])
  401. macro = line[directive_len:].strip()
  402. try:
  403. expand_result = self._macro_collection.Expand(macro)
  404. # Since expansions are line oriented, strip trailing whitespace
  405. # from the lines.
  406. lines = [x.rstrip() for x in expand_result.split('\n')]
  407. lines.append('// clang-format on')
  408. result.append('\n'.join(lines))
  409. except PDDMError as e:
  410. raise PDDMError('%s\n...while expanding "%s" from the section'
  411. ' that started:\n Line %d: %s' %
  412. (e.message, macro,
  413. self.first_line_num, self.first_line))
  414. # Add the ending marker.
  415. if len(captured_lines) == 1:
  416. result.append('//%%PDDM-EXPAND-END %s' %
  417. captured_lines[0][directive_len:].strip())
  418. else:
  419. result.append('//%%PDDM-EXPAND-END (%s expansions)' %
  420. len(captured_lines))
  421. return result
  422. class DefinitionSection(SectionBase):
  423. """Section containing macro definitions"""
  424. def TryAppend(self, line, line_num):
  425. if not line.startswith('//%'):
  426. return (False, False)
  427. if line.startswith('//%PDDM'):
  428. directive = line.split(' ', 1)[0]
  429. if directive == "//%PDDM-EXPAND":
  430. return False, False
  431. if directive not in ('//%PDDM-DEFINE', '//%PDDM-DEFINE-END'):
  432. raise PDDMError('Ran into directive ("%s", line %d) while in "%s".' %
  433. (directive, line_num, self.first_line))
  434. self.Append(line)
  435. return (True, True)
  436. def BindMacroCollection(self, macro_collection):
  437. if macro_collection:
  438. try:
  439. # Parse the lines after stripping the prefix.
  440. macro_collection.ParseLines([x[3:] for x in self.lines])
  441. except PDDMError as e:
  442. raise PDDMError('%s\n...while parsing section that started:\n'
  443. ' Line %d: %s' %
  444. (e.message, self.first_line_num, self.first_line))
  445. class ImportDefinesSection(SectionBase):
  446. """Section containing an import of PDDM-DEFINES from an external file."""
  447. def __init__(self, first_line_num, import_resolver):
  448. SourceFile.SectionBase.__init__(self, first_line_num)
  449. self._import_resolver = import_resolver
  450. def TryAppend(self, line, line_num):
  451. if not line.startswith('//%PDDM-IMPORT-DEFINES '):
  452. return (False, False)
  453. assert self.num_lines_captured == 0
  454. self.Append(line)
  455. return (True, False)
  456. def BindMacroCollection(self, macro_colletion):
  457. if not macro_colletion:
  458. return
  459. if self._import_resolver is None:
  460. raise PDDMError('Got an IMPORT-DEFINES without a resolver (line %d):'
  461. ' "%s".' % (self.first_line_num, self.first_line))
  462. import_name = self.first_line.split(' ', 1)[1].strip()
  463. imported_file = self._import_resolver(import_name)
  464. if imported_file is None:
  465. raise PDDMError('Resolver failed to find "%s" (line %d):'
  466. ' "%s".' %
  467. (import_name, self.first_line_num, self.first_line))
  468. try:
  469. imported_src_file = SourceFile(imported_file, self._import_resolver)
  470. imported_src_file._ParseFile()
  471. for section in imported_src_file._sections:
  472. section.BindMacroCollection(macro_colletion)
  473. except PDDMError as e:
  474. raise PDDMError('%s\n...while importing defines:\n'
  475. ' Line %d: %s' %
  476. (e.message, self.first_line_num, self.first_line))
  477. def _ParseFile(self):
  478. self._sections = []
  479. lines = self._original_content.splitlines()
  480. cur_section = None
  481. for line_num, line in enumerate(lines, 1):
  482. if not cur_section:
  483. cur_section = self._MakeSection(line, line_num)
  484. was_added, accept_more = cur_section.TryAppend(line, line_num)
  485. if not was_added:
  486. cur_section = self._MakeSection(line, line_num)
  487. was_added, accept_more = cur_section.TryAppend(line, line_num)
  488. assert was_added
  489. if not accept_more:
  490. cur_section = None
  491. if cur_section:
  492. cur_section.HitEOF()
  493. def _MakeSection(self, line, line_num):
  494. if not line.startswith('//%PDDM'):
  495. section = self.TextSection(line_num)
  496. else:
  497. directive = line.split(' ', 1)[0]
  498. if directive == '//%PDDM-EXPAND':
  499. section = self.ExpansionSection(line_num)
  500. elif directive == '//%PDDM-DEFINE':
  501. section = self.DefinitionSection(line_num)
  502. elif directive == '//%PDDM-IMPORT-DEFINES':
  503. section = self.ImportDefinesSection(line_num, self._import_resolver)
  504. else:
  505. raise PDDMError('Unexpected line %d: "%s".' % (line_num, line))
  506. self._sections.append(section)
  507. return section
  508. def ProcessContent(self, strip_expansion=False):
  509. """Processes the file contents."""
  510. self._ParseFile()
  511. if strip_expansion:
  512. # Without a collection the expansions become blank, removing them.
  513. collection = None
  514. else:
  515. collection = MacroCollection()
  516. for section in self._sections:
  517. section.BindMacroCollection(collection)
  518. result = ''
  519. for section in self._sections:
  520. result += section.text
  521. self._processed_content = result
  522. @property
  523. def original_content(self):
  524. return self._original_content
  525. @property
  526. def processed_content(self):
  527. return self._processed_content
  528. def main(args):
  529. usage = '%prog [OPTIONS] PATH ...'
  530. description = (
  531. 'Processes PDDM directives in the given paths and write them back out.'
  532. )
  533. parser = optparse.OptionParser(usage=usage, description=description)
  534. parser.add_option('--dry-run',
  535. default=False, action='store_true',
  536. help='Don\'t write back to the file(s), just report if the'
  537. ' contents needs an update and exit with a value of 1.')
  538. parser.add_option('--verbose',
  539. default=False, action='store_true',
  540. help='Reports is a file is already current.')
  541. parser.add_option('--collapse',
  542. default=False, action='store_true',
  543. help='Removes all the generated code.')
  544. opts, extra_args = parser.parse_args(args)
  545. if not extra_args:
  546. parser.error('Need at least one file to process')
  547. result = 0
  548. for a_path in extra_args:
  549. if not os.path.exists(a_path):
  550. sys.stderr.write('ERROR: File not found: %s\n' % a_path)
  551. return 100
  552. def _ImportResolver(name):
  553. # resolve based on the file being read.
  554. a_dir = os.path.dirname(a_path)
  555. import_path = os.path.join(a_dir, name)
  556. if not os.path.exists(import_path):
  557. return None
  558. return open(import_path, 'r')
  559. with open(a_path, 'r') as f:
  560. src_file = SourceFile(f, _ImportResolver)
  561. try:
  562. src_file.ProcessContent(strip_expansion=opts.collapse)
  563. except PDDMError as e:
  564. sys.stderr.write('ERROR: %s\n...While processing "%s"\n' %
  565. (e.message, a_path))
  566. return 101
  567. if src_file.processed_content != src_file.original_content:
  568. if not opts.dry_run:
  569. print('Updating for "%s".' % a_path)
  570. with open(a_path, 'w') as f:
  571. f.write(src_file.processed_content)
  572. else:
  573. # Special result to indicate things need updating.
  574. print('Update needed for "%s".' % a_path)
  575. result = 1
  576. elif opts.verbose:
  577. print('No update for "%s".' % a_path)
  578. return result
  579. if __name__ == '__main__':
  580. sys.exit(main(sys.argv[1:]))