gclient_eval.py 32 KB

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