gclient_eval.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. # Copyright 2017 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import ast
  5. import collections
  6. import logging
  7. import sys
  8. import tokenize
  9. import gclient_utils
  10. from third_party import schema
  11. from third_party import six
  12. if six.PY2:
  13. # We use cStringIO.StringIO because it is equivalent to Py3's io.StringIO.
  14. from cStringIO import StringIO
  15. import collections as collections_abc
  16. else:
  17. from collections import abc as collections_abc
  18. from io import StringIO
  19. # pylint: disable=redefined-builtin
  20. basestring = str
  21. class _NodeDict(collections_abc.MutableMapping):
  22. """Dict-like type that also stores information on AST nodes and tokens."""
  23. def __init__(self, data=None, tokens=None):
  24. self.data = collections.OrderedDict(data or [])
  25. self.tokens = tokens
  26. def __str__(self):
  27. return str({k: v[0] for k, v in self.data.items()})
  28. def __repr__(self):
  29. return self.__str__()
  30. def __getitem__(self, key):
  31. return self.data[key][0]
  32. def __setitem__(self, key, value):
  33. self.data[key] = (value, None)
  34. def __delitem__(self, key):
  35. del self.data[key]
  36. def __iter__(self):
  37. return iter(self.data)
  38. def __len__(self):
  39. return len(self.data)
  40. def MoveTokens(self, origin, delta):
  41. if self.tokens:
  42. new_tokens = {}
  43. for pos, token in self.tokens.items():
  44. if pos[0] >= origin:
  45. pos = (pos[0] + delta, pos[1])
  46. token = token[:2] + (pos,) + token[3:]
  47. new_tokens[pos] = token
  48. for value, node in self.data.values():
  49. if node.lineno >= origin:
  50. node.lineno += delta
  51. if isinstance(value, _NodeDict):
  52. value.MoveTokens(origin, delta)
  53. def GetNode(self, key):
  54. return self.data[key][1]
  55. def SetNode(self, key, value, node):
  56. self.data[key] = (value, node)
  57. def _NodeDictSchema(dict_schema):
  58. """Validate dict_schema after converting _NodeDict to a regular dict."""
  59. def validate(d):
  60. schema.Schema(dict_schema).validate(dict(d))
  61. return True
  62. return validate
  63. # See https://github.com/keleshev/schema for docs how to configure schema.
  64. _GCLIENT_DEPS_SCHEMA = _NodeDictSchema({
  65. schema.Optional(basestring):
  66. schema.Or(
  67. None,
  68. basestring,
  69. _NodeDictSchema({
  70. # Repo and revision to check out under the path
  71. # (same as if no dict was used).
  72. 'url': schema.Or(None, basestring),
  73. # Optional condition string. The dep will only be processed
  74. # if the condition evaluates to True.
  75. schema.Optional('condition'): basestring,
  76. schema.Optional('dep_type', default='git'): basestring,
  77. }),
  78. # CIPD package.
  79. _NodeDictSchema({
  80. 'packages': [
  81. _NodeDictSchema({
  82. 'package': basestring,
  83. 'version': basestring,
  84. })
  85. ],
  86. schema.Optional('condition'): basestring,
  87. schema.Optional('dep_type', default='cipd'): basestring,
  88. }),
  89. ),
  90. })
  91. _GCLIENT_HOOKS_SCHEMA = [
  92. _NodeDictSchema({
  93. # Hook action: list of command-line arguments to invoke.
  94. 'action': [basestring],
  95. # Name of the hook. Doesn't affect operation.
  96. schema.Optional('name'): basestring,
  97. # Hook pattern (regex). Originally intended to limit some hooks to run
  98. # only when files matching the pattern have changed. In practice, with
  99. # git, gclient runs all the hooks regardless of this field.
  100. schema.Optional('pattern'): basestring,
  101. # Working directory where to execute the hook.
  102. schema.Optional('cwd'): basestring,
  103. # Optional condition string. The hook will only be run
  104. # if the condition evaluates to True.
  105. schema.Optional('condition'): basestring,
  106. })
  107. ]
  108. _GCLIENT_SCHEMA = schema.Schema(
  109. _NodeDictSchema({
  110. # List of host names from which dependencies are allowed (whitelist).
  111. # NOTE: when not present, all hosts are allowed.
  112. # NOTE: scoped to current DEPS file, not recursive.
  113. schema.Optional('allowed_hosts'): [schema.Optional(basestring)],
  114. # Mapping from paths to repo and revision to check out under that path.
  115. # Applying this mapping to the on-disk checkout is the main purpose
  116. # of gclient, and also why the config file is called DEPS.
  117. #
  118. # The following functions are allowed:
  119. #
  120. # Var(): allows variable substitution (either from 'vars' dict below,
  121. # or command-line override)
  122. schema.Optional('deps'): _GCLIENT_DEPS_SCHEMA,
  123. # Similar to 'deps' (see above) - also keyed by OS (e.g. 'linux').
  124. # Also see 'target_os'.
  125. schema.Optional('deps_os'): _NodeDictSchema({
  126. schema.Optional(basestring): _GCLIENT_DEPS_SCHEMA,
  127. }),
  128. # Dependency to get gclient_gn_args* settings from. This allows these
  129. # values to be set in a recursedeps file, rather than requiring that
  130. # they exist in the top-level solution.
  131. schema.Optional('gclient_gn_args_from'): basestring,
  132. # Path to GN args file to write selected variables.
  133. schema.Optional('gclient_gn_args_file'): basestring,
  134. # Subset of variables to write to the GN args file (see above).
  135. schema.Optional('gclient_gn_args'): [schema.Optional(basestring)],
  136. # Hooks executed after gclient sync (unless suppressed), or explicitly
  137. # on gclient hooks. See _GCLIENT_HOOKS_SCHEMA for details.
  138. # Also see 'pre_deps_hooks'.
  139. schema.Optional('hooks'): _GCLIENT_HOOKS_SCHEMA,
  140. # Similar to 'hooks', also keyed by OS.
  141. schema.Optional('hooks_os'): _NodeDictSchema({
  142. schema.Optional(basestring): _GCLIENT_HOOKS_SCHEMA
  143. }),
  144. # Rules which #includes are allowed in the directory.
  145. # Also see 'skip_child_includes' and 'specific_include_rules'.
  146. schema.Optional('include_rules'): [schema.Optional(basestring)],
  147. # Hooks executed before processing DEPS. See 'hooks' for more details.
  148. schema.Optional('pre_deps_hooks'): _GCLIENT_HOOKS_SCHEMA,
  149. # Recursion limit for nested DEPS.
  150. schema.Optional('recursion'): int,
  151. # Whitelists deps for which recursion should be enabled.
  152. schema.Optional('recursedeps'): [
  153. schema.Optional(schema.Or(
  154. basestring,
  155. (basestring, basestring),
  156. [basestring, basestring]
  157. )),
  158. ],
  159. # Blacklists directories for checking 'include_rules'.
  160. schema.Optional('skip_child_includes'): [schema.Optional(basestring)],
  161. # Mapping from paths to include rules specific for that path.
  162. # See 'include_rules' for more details.
  163. schema.Optional('specific_include_rules'): _NodeDictSchema({
  164. schema.Optional(basestring): [basestring]
  165. }),
  166. # List of additional OS names to consider when selecting dependencies
  167. # from deps_os.
  168. schema.Optional('target_os'): [schema.Optional(basestring)],
  169. # For recursed-upon sub-dependencies, check out their own dependencies
  170. # relative to the parent's path, rather than relative to the .gclient
  171. # file.
  172. schema.Optional('use_relative_paths'): bool,
  173. # For recursed-upon sub-dependencies, run their hooks relative to the
  174. # parent's path instead of relative to the .gclient file.
  175. schema.Optional('use_relative_hooks'): bool,
  176. # Variables that can be referenced using Var() - see 'deps'.
  177. schema.Optional('vars'): _NodeDictSchema({
  178. schema.Optional(basestring): schema.Or(basestring, bool),
  179. }),
  180. }))
  181. def _gclient_eval(node_or_string, filename='<unknown>', vars_dict=None):
  182. """Safely evaluates a single expression. Returns the result."""
  183. _allowed_names = {'None': None, 'True': True, 'False': False}
  184. if isinstance(node_or_string, basestring):
  185. node_or_string = ast.parse(node_or_string, filename=filename, mode='eval')
  186. if isinstance(node_or_string, ast.Expression):
  187. node_or_string = node_or_string.body
  188. def _convert(node):
  189. if isinstance(node, ast.Str):
  190. if vars_dict is None:
  191. return node.s
  192. try:
  193. return node.s.format(**vars_dict)
  194. except KeyError as e:
  195. raise KeyError(
  196. '%s was used as a variable, but was not declared in the vars dict '
  197. '(file %r, line %s)' % (
  198. e.args[0], filename, getattr(node, 'lineno', '<unknown>')))
  199. elif isinstance(node, ast.Num):
  200. return node.n
  201. elif isinstance(node, ast.Tuple):
  202. return tuple(map(_convert, node.elts))
  203. elif isinstance(node, ast.List):
  204. return list(map(_convert, node.elts))
  205. elif isinstance(node, ast.Dict):
  206. node_dict = _NodeDict()
  207. for key_node, value_node in zip(node.keys, node.values):
  208. key = _convert(key_node)
  209. if key in node_dict:
  210. raise ValueError(
  211. 'duplicate key in dictionary: %s (file %r, line %s)' % (
  212. key, filename, getattr(key_node, 'lineno', '<unknown>')))
  213. node_dict.SetNode(key, _convert(value_node), value_node)
  214. return node_dict
  215. elif isinstance(node, ast.Name):
  216. if node.id not in _allowed_names:
  217. raise ValueError(
  218. 'invalid name %r (file %r, line %s)' % (
  219. node.id, filename, getattr(node, 'lineno', '<unknown>')))
  220. return _allowed_names[node.id]
  221. elif not sys.version_info[:2] < (3, 4) and isinstance(
  222. node, ast.NameConstant): # Since Python 3.4
  223. return node.value
  224. elif isinstance(node, ast.Call):
  225. if not isinstance(node.func, ast.Name) or node.func.id != 'Var':
  226. raise ValueError(
  227. 'Var is the only allowed function (file %r, line %s)' % (
  228. filename, getattr(node, 'lineno', '<unknown>')))
  229. if node.keywords or getattr(node, 'starargs', None) or getattr(
  230. node, 'kwargs', None) or len(node.args) != 1:
  231. raise ValueError(
  232. 'Var takes exactly one argument (file %r, line %s)' % (
  233. filename, getattr(node, 'lineno', '<unknown>')))
  234. arg = _convert(node.args[0])
  235. if not isinstance(arg, basestring):
  236. raise ValueError(
  237. 'Var\'s argument must be a variable name (file %r, line %s)' % (
  238. filename, getattr(node, 'lineno', '<unknown>')))
  239. if vars_dict is None:
  240. return '{' + arg + '}'
  241. if arg not in vars_dict:
  242. raise KeyError(
  243. '%s was used as a variable, but was not declared in the vars dict '
  244. '(file %r, line %s)' % (
  245. arg, filename, getattr(node, 'lineno', '<unknown>')))
  246. return vars_dict[arg]
  247. elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
  248. return _convert(node.left) + _convert(node.right)
  249. elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
  250. return _convert(node.left) % _convert(node.right)
  251. else:
  252. raise ValueError(
  253. 'unexpected AST node: %s %s (file %r, line %s)' % (
  254. node, ast.dump(node), filename,
  255. getattr(node, 'lineno', '<unknown>')))
  256. return _convert(node_or_string)
  257. def Exec(content, filename='<unknown>', vars_override=None, builtin_vars=None):
  258. """Safely execs a set of assignments."""
  259. def _validate_statement(node, local_scope):
  260. if not isinstance(node, ast.Assign):
  261. raise ValueError(
  262. 'unexpected AST node: %s %s (file %r, line %s)' % (
  263. node, ast.dump(node), filename,
  264. getattr(node, 'lineno', '<unknown>')))
  265. if len(node.targets) != 1:
  266. raise ValueError(
  267. 'invalid assignment: use exactly one target (file %r, line %s)' % (
  268. filename, getattr(node, 'lineno', '<unknown>')))
  269. target = node.targets[0]
  270. if not isinstance(target, ast.Name):
  271. raise ValueError(
  272. 'invalid assignment: target should be a name (file %r, line %s)' % (
  273. filename, getattr(node, 'lineno', '<unknown>')))
  274. if target.id in local_scope:
  275. raise ValueError(
  276. 'invalid assignment: overrides var %r (file %r, line %s)' % (
  277. target.id, filename, getattr(node, 'lineno', '<unknown>')))
  278. node_or_string = ast.parse(content, filename=filename, mode='exec')
  279. if isinstance(node_or_string, ast.Expression):
  280. node_or_string = node_or_string.body
  281. if not isinstance(node_or_string, ast.Module):
  282. raise ValueError(
  283. 'unexpected AST node: %s %s (file %r, line %s)' % (
  284. node_or_string,
  285. ast.dump(node_or_string),
  286. filename,
  287. getattr(node_or_string, 'lineno', '<unknown>')))
  288. statements = {}
  289. for statement in node_or_string.body:
  290. _validate_statement(statement, statements)
  291. statements[statement.targets[0].id] = statement.value
  292. # The tokenized representation needs to end with a newline token, otherwise
  293. # untokenization will trigger an assert later on.
  294. # In Python 2.7 on Windows we need to ensure the input ends with a newline
  295. # for a newline token to be generated.
  296. # In other cases a newline token is always generated during tokenization so
  297. # this has no effect.
  298. # TODO: Remove this workaround after migrating to Python 3.
  299. content += '\n'
  300. tokens = {
  301. token[2]: list(token) for token in tokenize.generate_tokens(
  302. StringIO(content).readline)
  303. }
  304. local_scope = _NodeDict({}, tokens)
  305. # Process vars first, so we can expand variables in the rest of the DEPS file.
  306. vars_dict = {}
  307. if 'vars' in statements:
  308. vars_statement = statements['vars']
  309. value = _gclient_eval(vars_statement, filename)
  310. local_scope.SetNode('vars', value, vars_statement)
  311. # Update the parsed vars with the overrides, but only if they are already
  312. # present (overrides do not introduce new variables).
  313. vars_dict.update(value)
  314. if builtin_vars:
  315. vars_dict.update(builtin_vars)
  316. if vars_override:
  317. vars_dict.update({k: v for k, v in vars_override.items() if k in vars_dict})
  318. for name, node in statements.items():
  319. value = _gclient_eval(node, filename, vars_dict)
  320. local_scope.SetNode(name, value, node)
  321. try:
  322. return _GCLIENT_SCHEMA.validate(local_scope)
  323. except schema.SchemaError as e:
  324. raise gclient_utils.Error(str(e))
  325. def _StandardizeDeps(deps_dict, vars_dict):
  326. """"Standardizes the deps_dict.
  327. For each dependency:
  328. - Expands the variable in the dependency name.
  329. - Ensures the dependency is a dictionary.
  330. - Set's the 'dep_type' to be 'git' by default.
  331. """
  332. new_deps_dict = {}
  333. for dep_name, dep_info in deps_dict.items():
  334. dep_name = dep_name.format(**vars_dict)
  335. if not isinstance(dep_info, collections_abc.Mapping):
  336. dep_info = {'url': dep_info}
  337. dep_info.setdefault('dep_type', 'git')
  338. new_deps_dict[dep_name] = dep_info
  339. return new_deps_dict
  340. def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
  341. """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
  342. The dependencies in os_deps_dict are transformed into conditional dependencies
  343. using |'checkout_' + os_name|.
  344. If the dependency is already present, the URL and revision must coincide.
  345. """
  346. for dep_name, dep_info in os_deps_dict.items():
  347. # Make this condition very visible, so it's not a silent failure.
  348. # It's unclear how to support None override in deps_os.
  349. if dep_info['url'] is None:
  350. logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info, os_name)
  351. continue
  352. os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
  353. UpdateCondition(dep_info, 'and', os_condition)
  354. if dep_name in deps_dict:
  355. if deps_dict[dep_name]['url'] != dep_info['url']:
  356. raise gclient_utils.Error(
  357. 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
  358. 'entry (%r).' % (
  359. os_name, dep_name, dep_info, deps_dict[dep_name]))
  360. UpdateCondition(dep_info, 'or', deps_dict[dep_name].get('condition'))
  361. deps_dict[dep_name] = dep_info
  362. def UpdateCondition(info_dict, op, new_condition):
  363. """Updates info_dict's condition with |new_condition|.
  364. An absent value is treated as implicitly True.
  365. """
  366. curr_condition = info_dict.get('condition')
  367. # Easy case: Both are present.
  368. if curr_condition and new_condition:
  369. info_dict['condition'] = '(%s) %s (%s)' % (
  370. curr_condition, op, new_condition)
  371. # If |op| == 'and', and at least one condition is present, then use it.
  372. elif op == 'and' and (curr_condition or new_condition):
  373. info_dict['condition'] = curr_condition or new_condition
  374. # Otherwise, no condition should be set
  375. elif curr_condition:
  376. del info_dict['condition']
  377. def Parse(content, filename, vars_override=None, builtin_vars=None):
  378. """Parses DEPS strings.
  379. Executes the Python-like string stored in content, resulting in a Python
  380. dictionary specified by the schema above. Supports syntax validation and
  381. variable expansion.
  382. Args:
  383. content: str. DEPS file stored as a string.
  384. filename: str. The name of the DEPS file, or a string describing the source
  385. of the content, e.g. '<string>', '<unknown>'.
  386. vars_override: dict, optional. A dictionary with overrides for the variables
  387. defined by the DEPS file.
  388. builtin_vars: dict, optional. A dictionary with variables that are provided
  389. by default.
  390. Returns:
  391. A Python dict with the parsed contents of the DEPS file, as specified by the
  392. schema above.
  393. """
  394. result = Exec(content, filename, vars_override, builtin_vars)
  395. vars_dict = result.get('vars', {})
  396. if 'deps' in result:
  397. result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
  398. if 'deps_os' in result:
  399. deps = result.setdefault('deps', {})
  400. for os_name, os_deps in result['deps_os'].items():
  401. os_deps = _StandardizeDeps(os_deps, vars_dict)
  402. _MergeDepsOs(deps, os_deps, os_name)
  403. del result['deps_os']
  404. if 'hooks_os' in result:
  405. hooks = result.setdefault('hooks', [])
  406. for os_name, os_hooks in result['hooks_os'].items():
  407. for hook in os_hooks:
  408. UpdateCondition(hook, 'and', 'checkout_' + os_name)
  409. hooks.extend(os_hooks)
  410. del result['hooks_os']
  411. return result
  412. def EvaluateCondition(condition, variables, referenced_variables=None):
  413. """Safely evaluates a boolean condition. Returns the result."""
  414. if not referenced_variables:
  415. referenced_variables = set()
  416. _allowed_names = {'None': None, 'True': True, 'False': False}
  417. main_node = ast.parse(condition, mode='eval')
  418. if isinstance(main_node, ast.Expression):
  419. main_node = main_node.body
  420. def _convert(node, allow_tuple=False):
  421. if isinstance(node, ast.Str):
  422. return node.s
  423. elif isinstance(node, ast.Tuple) and allow_tuple:
  424. return tuple(map(_convert, node.elts))
  425. elif isinstance(node, ast.Name):
  426. if node.id in referenced_variables:
  427. raise ValueError(
  428. 'invalid cyclic reference to %r (inside %r)' % (
  429. node.id, condition))
  430. elif node.id in _allowed_names:
  431. return _allowed_names[node.id]
  432. elif node.id in variables:
  433. value = variables[node.id]
  434. # Allow using "native" types, without wrapping everything in strings.
  435. # Note that schema constraints still apply to variables.
  436. if not isinstance(value, basestring):
  437. return value
  438. # Recursively evaluate the variable reference.
  439. return EvaluateCondition(
  440. variables[node.id],
  441. variables,
  442. referenced_variables.union([node.id]))
  443. else:
  444. # Implicitly convert unrecognized names to strings.
  445. # If we want to change this, we'll need to explicitly distinguish
  446. # between arguments for GN to be passed verbatim, and ones to
  447. # be evaluated.
  448. return node.id
  449. elif not sys.version_info[:2] < (3, 4) and isinstance(
  450. node, ast.NameConstant): # Since Python 3.4
  451. return node.value
  452. elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
  453. bool_values = []
  454. for value in node.values:
  455. bool_values.append(_convert(value))
  456. if not isinstance(bool_values[-1], bool):
  457. raise ValueError(
  458. 'invalid "or" operand %r (inside %r)' % (
  459. bool_values[-1], condition))
  460. return any(bool_values)
  461. elif isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
  462. bool_values = []
  463. for value in node.values:
  464. bool_values.append(_convert(value))
  465. if not isinstance(bool_values[-1], bool):
  466. raise ValueError(
  467. 'invalid "and" operand %r (inside %r)' % (
  468. bool_values[-1], condition))
  469. return all(bool_values)
  470. elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
  471. value = _convert(node.operand)
  472. if not isinstance(value, bool):
  473. raise ValueError(
  474. 'invalid "not" operand %r (inside %r)' % (value, condition))
  475. return not value
  476. elif isinstance(node, ast.Compare):
  477. if len(node.ops) != 1:
  478. raise ValueError(
  479. 'invalid compare: exactly 1 operator required (inside %r)' % (
  480. condition))
  481. if len(node.comparators) != 1:
  482. raise ValueError(
  483. 'invalid compare: exactly 1 comparator required (inside %r)' % (
  484. condition))
  485. left = _convert(node.left)
  486. right = _convert(
  487. node.comparators[0], allow_tuple=isinstance(node.ops[0], ast.In))
  488. if isinstance(node.ops[0], ast.Eq):
  489. return left == right
  490. if isinstance(node.ops[0], ast.NotEq):
  491. return left != right
  492. if isinstance(node.ops[0], ast.In):
  493. return left in right
  494. raise ValueError(
  495. 'unexpected operator: %s %s (inside %r)' % (
  496. node.ops[0], ast.dump(node), condition))
  497. else:
  498. raise ValueError(
  499. 'unexpected AST node: %s %s (inside %r)' % (
  500. node, ast.dump(node), condition))
  501. return _convert(main_node)
  502. def RenderDEPSFile(gclient_dict):
  503. contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
  504. # The last token is a newline, which we ensure in Exec() for compatibility.
  505. # However tests pass in inputs not ending with a newline and expect the same
  506. # back, so for backwards compatibility need to remove that newline character.
  507. # TODO: Fix tests to expect the newline
  508. return tokenize.untokenize(contents)[:-1]
  509. def _UpdateAstString(tokens, node, value):
  510. position = node.lineno, node.col_offset
  511. quote_char = ''
  512. if isinstance(node, ast.Str):
  513. quote_char = tokens[position][1][0]
  514. value = value.encode('unicode_escape').decode('utf-8')
  515. tokens[position][1] = quote_char + value + quote_char
  516. node.s = value
  517. def _ShiftLinesInTokens(tokens, delta, start):
  518. new_tokens = {}
  519. for token in tokens.values():
  520. if token[2][0] >= start:
  521. token[2] = token[2][0] + delta, token[2][1]
  522. token[3] = token[3][0] + delta, token[3][1]
  523. new_tokens[token[2]] = token
  524. return new_tokens
  525. def AddVar(gclient_dict, var_name, value):
  526. if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
  527. raise ValueError(
  528. "Can't use SetVar for the given gclient dict. It contains no "
  529. "formatting information.")
  530. if 'vars' not in gclient_dict:
  531. raise KeyError("vars dict is not defined.")
  532. if var_name in gclient_dict['vars']:
  533. raise ValueError(
  534. "%s has already been declared in the vars dict. Consider using SetVar "
  535. "instead." % var_name)
  536. if not gclient_dict['vars']:
  537. raise ValueError('vars dict is empty. This is not yet supported.')
  538. # We will attempt to add the var right after 'vars = {'.
  539. node = gclient_dict.GetNode('vars')
  540. if node is None:
  541. raise ValueError(
  542. "The vars dict has no formatting information." % var_name)
  543. line = node.lineno + 1
  544. # We will try to match the new var's indentation to the next variable.
  545. col = node.keys[0].col_offset
  546. # We use a minimal Python dictionary, so that ast can parse it.
  547. var_content = '{\n%s"%s": "%s",\n}\n' % (' ' * col, var_name, value)
  548. var_ast = ast.parse(var_content).body[0].value
  549. # Set the ast nodes for the key and value.
  550. vars_node = gclient_dict.GetNode('vars')
  551. var_name_node = var_ast.keys[0]
  552. var_name_node.lineno += line - 2
  553. vars_node.keys.insert(0, var_name_node)
  554. value_node = var_ast.values[0]
  555. value_node.lineno += line - 2
  556. vars_node.values.insert(0, value_node)
  557. # Update the tokens.
  558. var_tokens = list(tokenize.generate_tokens(StringIO(var_content).readline))
  559. var_tokens = {
  560. token[2]: list(token)
  561. # Ignore the tokens corresponding to braces and new lines.
  562. for token in var_tokens[2:-3]
  563. }
  564. gclient_dict.tokens = _ShiftLinesInTokens(gclient_dict.tokens, 1, line)
  565. gclient_dict.tokens.update(_ShiftLinesInTokens(var_tokens, line - 2, 0))
  566. def SetVar(gclient_dict, var_name, value):
  567. if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
  568. raise ValueError(
  569. "Can't use SetVar for the given gclient dict. It contains no "
  570. "formatting information.")
  571. tokens = gclient_dict.tokens
  572. if 'vars' not in gclient_dict:
  573. raise KeyError("vars dict is not defined.")
  574. if var_name not in gclient_dict['vars']:
  575. raise ValueError(
  576. "%s has not been declared in the vars dict. Consider using AddVar "
  577. "instead." % var_name)
  578. node = gclient_dict['vars'].GetNode(var_name)
  579. if node is None:
  580. raise ValueError(
  581. "The vars entry for %s has no formatting information." % var_name)
  582. _UpdateAstString(tokens, node, value)
  583. gclient_dict['vars'].SetNode(var_name, value, node)
  584. def _GetVarName(node):
  585. if isinstance(node, ast.Call):
  586. return node.args[0].s
  587. elif node.s.endswith('}'):
  588. last_brace = node.s.rfind('{')
  589. return node.s[last_brace+1:-1]
  590. return None
  591. def SetCIPD(gclient_dict, dep_name, package_name, new_version):
  592. if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
  593. raise ValueError(
  594. "Can't use SetCIPD for the given gclient dict. It contains no "
  595. "formatting information.")
  596. tokens = gclient_dict.tokens
  597. if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
  598. raise KeyError(
  599. "Could not find any dependency called %s." % dep_name)
  600. # Find the package with the given name
  601. packages = [
  602. package
  603. for package in gclient_dict['deps'][dep_name]['packages']
  604. if package['package'] == package_name
  605. ]
  606. if len(packages) != 1:
  607. raise ValueError(
  608. "There must be exactly one package with the given name (%s), "
  609. "%s were found." % (package_name, len(packages)))
  610. # TODO(ehmaldonado): Support Var in package's version.
  611. node = packages[0].GetNode('version')
  612. if node is None:
  613. raise ValueError(
  614. "The deps entry for %s:%s has no formatting information." %
  615. (dep_name, package_name))
  616. if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
  617. raise ValueError(
  618. "Unsupported dependency revision format. Please file a bug to the "
  619. "Infra>SDK component in crbug.com")
  620. var_name = _GetVarName(node)
  621. if var_name is not None:
  622. SetVar(gclient_dict, var_name, new_version)
  623. else:
  624. _UpdateAstString(tokens, node, new_version)
  625. packages[0].SetNode('version', new_version, node)
  626. def SetRevision(gclient_dict, dep_name, new_revision):
  627. def _UpdateRevision(dep_dict, dep_key, new_revision):
  628. dep_node = dep_dict.GetNode(dep_key)
  629. if dep_node is None:
  630. raise ValueError(
  631. "The deps entry for %s has no formatting information." % dep_name)
  632. node = dep_node
  633. if isinstance(node, ast.BinOp):
  634. node = node.right
  635. if isinstance(node, ast.Str):
  636. token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
  637. if token != node.s:
  638. raise ValueError(
  639. 'Can\'t update value for %s. Multiline strings and implicitly '
  640. 'concatenated strings are not supported.\n'
  641. 'Consider reformatting the DEPS file.' % dep_key)
  642. if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
  643. raise ValueError(
  644. "Unsupported dependency revision format. Please file a bug to the "
  645. "Infra>SDK component in crbug.com")
  646. var_name = _GetVarName(node)
  647. if var_name is not None:
  648. SetVar(gclient_dict, var_name, new_revision)
  649. else:
  650. if '@' in node.s:
  651. # '@' is part of the last string, which we want to modify. Discard
  652. # whatever was after the '@' and put the new revision in its place.
  653. new_revision = node.s.split('@')[0] + '@' + new_revision
  654. elif '@' not in dep_dict[dep_key]:
  655. # '@' is not part of the URL at all. This mean the dependency is
  656. # unpinned and we should pin it.
  657. new_revision = node.s + '@' + new_revision
  658. _UpdateAstString(tokens, node, new_revision)
  659. dep_dict.SetNode(dep_key, new_revision, node)
  660. if not isinstance(gclient_dict, _NodeDict) or gclient_dict.tokens is None:
  661. raise ValueError(
  662. "Can't use SetRevision for the given gclient dict. It contains no "
  663. "formatting information.")
  664. tokens = gclient_dict.tokens
  665. if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
  666. raise KeyError(
  667. "Could not find any dependency called %s." % dep_name)
  668. if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
  669. _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
  670. else:
  671. _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
  672. def GetVar(gclient_dict, var_name):
  673. if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
  674. raise KeyError(
  675. "Could not find any variable called %s." % var_name)
  676. return gclient_dict['vars'][var_name]
  677. def GetCIPD(gclient_dict, dep_name, package_name):
  678. if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
  679. raise KeyError(
  680. "Could not find any dependency called %s." % dep_name)
  681. # Find the package with the given name
  682. packages = [
  683. package
  684. for package in gclient_dict['deps'][dep_name]['packages']
  685. if package['package'] == package_name
  686. ]
  687. if len(packages) != 1:
  688. raise ValueError(
  689. "There must be exactly one package with the given name (%s), "
  690. "%s were found." % (package_name, len(packages)))
  691. return packages[0]['version']
  692. def GetRevision(gclient_dict, dep_name):
  693. if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
  694. raise KeyError(
  695. "Could not find any dependency called %s." % dep_name)
  696. dep = gclient_dict['deps'][dep_name]
  697. if dep is None:
  698. return None
  699. elif isinstance(dep, basestring):
  700. _, _, revision = dep.partition('@')
  701. return revision or None
  702. elif isinstance(dep, collections_abc.Mapping) and 'url' in dep:
  703. _, _, revision = dep['url'].partition('@')
  704. return revision or None
  705. else:
  706. raise ValueError(
  707. '%s is not a valid git dependency.' % dep_name)