gclient_eval.py 35 KB

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