gclient_eval.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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. tokens = {
  340. token[2]: list(token)
  341. for token in tokenize.generate_tokens(StringIO(content).readline)
  342. }
  343. local_scope = _NodeDict({}, tokens)
  344. # Process vars first, so we can expand variables in the rest of the DEPS
  345. # file.
  346. vars_dict = {}
  347. if 'vars' in statements:
  348. vars_statement = statements['vars']
  349. value = _gclient_eval(vars_statement, filename)
  350. local_scope.SetNode('vars', value, vars_statement)
  351. # Update the parsed vars with the overrides, but only if they are
  352. # already present (overrides do not introduce new variables).
  353. vars_dict.update(value)
  354. if builtin_vars:
  355. vars_dict.update(builtin_vars)
  356. if vars_override:
  357. vars_dict.update(
  358. {k: v
  359. for k, v in vars_override.items() if k in vars_dict})
  360. for name, node in statements.items():
  361. value = _gclient_eval(node, filename, vars_dict)
  362. local_scope.SetNode(name, value, node)
  363. try:
  364. return _GCLIENT_SCHEMA.validate(local_scope)
  365. except schema.SchemaError as e:
  366. raise gclient_utils.Error(str(e))
  367. def _StandardizeDeps(deps_dict, vars_dict):
  368. """"Standardizes the deps_dict.
  369. For each dependency:
  370. - Expands the variable in the dependency name.
  371. - Ensures the dependency is a dictionary.
  372. - Set's the 'dep_type' to be 'git' by default.
  373. """
  374. new_deps_dict = {}
  375. for dep_name, dep_info in deps_dict.items():
  376. dep_name = dep_name.format(**vars_dict)
  377. if not isinstance(dep_info, collections.abc.Mapping):
  378. dep_info = {'url': dep_info}
  379. dep_info.setdefault('dep_type', 'git')
  380. new_deps_dict[dep_name] = dep_info
  381. return new_deps_dict
  382. def _MergeDepsOs(deps_dict, os_deps_dict, os_name):
  383. """Merges the deps in os_deps_dict into conditional dependencies in deps_dict.
  384. The dependencies in os_deps_dict are transformed into conditional dependencies
  385. using |'checkout_' + os_name|.
  386. If the dependency is already present, the URL and revision must coincide.
  387. """
  388. for dep_name, dep_info in os_deps_dict.items():
  389. # Make this condition very visible, so it's not a silent failure.
  390. # It's unclear how to support None override in deps_os.
  391. if dep_info['url'] is None:
  392. logging.error('Ignoring %r:%r in %r deps_os', dep_name, dep_info,
  393. os_name)
  394. continue
  395. os_condition = 'checkout_' + (os_name if os_name != 'unix' else 'linux')
  396. UpdateCondition(dep_info, 'and', os_condition)
  397. if dep_name in deps_dict:
  398. if deps_dict[dep_name]['url'] != dep_info['url']:
  399. raise gclient_utils.Error(
  400. 'Value from deps_os (%r; %r: %r) conflicts with existing deps '
  401. 'entry (%r).' %
  402. (os_name, dep_name, dep_info, deps_dict[dep_name]))
  403. UpdateCondition(dep_info, 'or',
  404. deps_dict[dep_name].get('condition'))
  405. deps_dict[dep_name] = dep_info
  406. def UpdateCondition(info_dict, op, new_condition):
  407. """Updates info_dict's condition with |new_condition|.
  408. An absent value is treated as implicitly True.
  409. """
  410. curr_condition = info_dict.get('condition')
  411. # Easy case: Both are present.
  412. if curr_condition and new_condition:
  413. info_dict['condition'] = '(%s) %s (%s)' % (curr_condition, op,
  414. new_condition)
  415. # If |op| == 'and', and at least one condition is present, then use it.
  416. elif op == 'and' and (curr_condition or new_condition):
  417. info_dict['condition'] = curr_condition or new_condition
  418. # Otherwise, no condition should be set
  419. elif curr_condition:
  420. del info_dict['condition']
  421. def Parse(content, filename, vars_override=None, builtin_vars=None):
  422. """Parses DEPS strings.
  423. Executes the Python-like string stored in content, resulting in a Python
  424. dictionary specified by the schema above. Supports syntax validation and
  425. variable expansion.
  426. Args:
  427. content: str. DEPS file stored as a string.
  428. filename: str. The name of the DEPS file, or a string describing the source
  429. of the content, e.g. '<string>', '<unknown>'.
  430. vars_override: dict, optional. A dictionary with overrides for the variables
  431. defined by the DEPS file.
  432. builtin_vars: dict, optional. A dictionary with variables that are provided
  433. by default.
  434. Returns:
  435. A Python dict with the parsed contents of the DEPS file, as specified by the
  436. schema above.
  437. """
  438. result = Exec(content, filename, vars_override, builtin_vars)
  439. vars_dict = result.get('vars', {})
  440. if 'deps' in result:
  441. result['deps'] = _StandardizeDeps(result['deps'], vars_dict)
  442. if 'deps_os' in result:
  443. deps = result.setdefault('deps', {})
  444. for os_name, os_deps in result['deps_os'].items():
  445. os_deps = _StandardizeDeps(os_deps, vars_dict)
  446. _MergeDepsOs(deps, os_deps, os_name)
  447. del result['deps_os']
  448. if 'hooks_os' in result:
  449. hooks = result.setdefault('hooks', [])
  450. for os_name, os_hooks in result['hooks_os'].items():
  451. for hook in os_hooks:
  452. UpdateCondition(hook, 'and', 'checkout_' + os_name)
  453. hooks.extend(os_hooks)
  454. del result['hooks_os']
  455. return result
  456. def EvaluateCondition(condition, variables, referenced_variables=None):
  457. """Safely evaluates a boolean condition. Returns the result."""
  458. if not referenced_variables:
  459. referenced_variables = set()
  460. _allowed_names = {'None': None, 'True': True, 'False': False}
  461. main_node = ast.parse(condition, mode='eval')
  462. if isinstance(main_node, ast.Expression):
  463. main_node = main_node.body
  464. def _convert(node, allow_tuple=False):
  465. if isinstance(node, ast.Str):
  466. return node.s
  467. if isinstance(node, ast.Tuple) and allow_tuple:
  468. return tuple(map(_convert, node.elts))
  469. if isinstance(node, ast.Name):
  470. if node.id in referenced_variables:
  471. raise ValueError('invalid cyclic reference to %r (inside %r)' %
  472. (node.id, condition))
  473. if node.id in _allowed_names:
  474. return _allowed_names[node.id]
  475. if node.id in variables:
  476. value = variables[node.id]
  477. # Allow using "native" types, without wrapping everything in
  478. # strings. Note that schema constraints still apply to
  479. # variables.
  480. if not isinstance(value, str):
  481. return value
  482. # Recursively evaluate the variable reference.
  483. return EvaluateCondition(variables[node.id], variables,
  484. referenced_variables.union([node.id]))
  485. # Implicitly convert unrecognized names to strings.
  486. # If we want to change this, we'll need to explicitly distinguish
  487. # between arguments for GN to be passed verbatim, and ones to
  488. # be evaluated.
  489. return node.id
  490. if not sys.version_info[:2] < (3, 4) and isinstance(
  491. node, ast.NameConstant): # Since Python 3.4
  492. return node.value
  493. if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or):
  494. bool_values = []
  495. for value in node.values:
  496. bool_values.append(_convert(value))
  497. if not isinstance(bool_values[-1], bool):
  498. raise ValueError('invalid "or" operand %r (inside %r)' %
  499. (bool_values[-1], condition))
  500. return any(bool_values)
  501. if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
  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 "and" operand %r (inside %r)' %
  507. (bool_values[-1], condition))
  508. return all(bool_values)
  509. if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
  510. value = _convert(node.operand)
  511. if not isinstance(value, bool):
  512. raise ValueError('invalid "not" operand %r (inside %r)' %
  513. (value, condition))
  514. return not value
  515. if isinstance(node, ast.Compare):
  516. if len(node.ops) != 1:
  517. raise ValueError(
  518. 'invalid compare: exactly 1 operator required (inside %r)' %
  519. (condition))
  520. if len(node.comparators) != 1:
  521. raise ValueError(
  522. 'invalid compare: exactly 1 comparator required (inside %r)'
  523. % (condition))
  524. left = _convert(node.left)
  525. right = _convert(node.comparators[0],
  526. allow_tuple=isinstance(node.ops[0], ast.In))
  527. if isinstance(node.ops[0], ast.Eq):
  528. return left == right
  529. if isinstance(node.ops[0], ast.NotEq):
  530. return left != right
  531. if isinstance(node.ops[0], ast.In):
  532. return left in right
  533. raise ValueError('unexpected operator: %s %s (inside %r)' %
  534. (node.ops[0], ast.dump(node), condition))
  535. raise ValueError('unexpected AST node: %s %s (inside %r)' %
  536. (node, ast.dump(node), condition))
  537. return _convert(main_node)
  538. def RenderDEPSFile(gclient_dict):
  539. contents = sorted(gclient_dict.tokens.values(), key=lambda token: token[2])
  540. return tokenize.untokenize(contents)
  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("The vars dict has no formatting information." %
  576. 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("Could not find any dependency called %s." % dep_name)
  633. # Find the package with the given name
  634. packages = [
  635. package for package in gclient_dict['deps'][dep_name]['packages']
  636. if package['package'] == package_name
  637. ]
  638. if len(packages) != 1:
  639. raise ValueError(
  640. "There must be exactly one package with the given name (%s), "
  641. "%s were found." % (package_name, len(packages)))
  642. # TODO(ehmaldonado): Support Var in package's version.
  643. node = packages[0].GetNode('version')
  644. if node is None:
  645. raise ValueError(
  646. "The deps entry for %s:%s has no formatting information." %
  647. (dep_name, package_name))
  648. if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
  649. raise ValueError(
  650. "Unsupported dependency revision format. Please file a bug to the "
  651. "Infra>SDK component in crbug.com")
  652. var_name = _GetVarName(node)
  653. if var_name is not None:
  654. SetVar(gclient_dict, var_name, new_version)
  655. else:
  656. _UpdateAstString(tokens, node, new_version)
  657. packages[0].SetNode('version', new_version, node)
  658. def SetRevision(gclient_dict, dep_name, new_revision):
  659. def _UpdateRevision(dep_dict, dep_key, new_revision):
  660. dep_node = dep_dict.GetNode(dep_key)
  661. if dep_node is None:
  662. raise ValueError(
  663. "The deps entry for %s has no formatting information." %
  664. dep_name)
  665. node = dep_node
  666. if isinstance(node, ast.BinOp):
  667. node = node.right
  668. if isinstance(node, ast.Str):
  669. token = _gclient_eval(tokens[node.lineno, node.col_offset][1])
  670. if token != node.s:
  671. raise ValueError(
  672. 'Can\'t update value for %s. Multiline strings and implicitly '
  673. 'concatenated strings are not supported.\n'
  674. 'Consider reformatting the DEPS file.' % dep_key)
  675. if not isinstance(node, ast.Call) and not isinstance(node, ast.Str):
  676. raise ValueError(
  677. "Unsupported dependency revision format. Please file a bug to the "
  678. "Infra>SDK component in crbug.com")
  679. var_name = _GetVarName(node)
  680. if var_name is not None:
  681. SetVar(gclient_dict, var_name, new_revision)
  682. else:
  683. if '@' in node.s:
  684. # '@' is part of the last string, which we want to modify.
  685. # Discard whatever was after the '@' and put the new revision in
  686. # 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("Could not find any dependency called %s." % dep_name)
  701. if isinstance(gclient_dict['deps'][dep_name], _NodeDict):
  702. _UpdateRevision(gclient_dict['deps'][dep_name], 'url', new_revision)
  703. else:
  704. _UpdateRevision(gclient_dict['deps'], dep_name, new_revision)
  705. def GetVar(gclient_dict, var_name):
  706. if 'vars' not in gclient_dict or var_name not in gclient_dict['vars']:
  707. raise KeyError("Could not find any variable called %s." % var_name)
  708. val = gclient_dict['vars'][var_name]
  709. if isinstance(val, ConstantString):
  710. return val.value
  711. return val
  712. def GetCIPD(gclient_dict, dep_name, package_name):
  713. if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
  714. raise KeyError("Could not find any dependency called %s." % dep_name)
  715. # Find the package with the given name
  716. packages = [
  717. package for package in gclient_dict['deps'][dep_name]['packages']
  718. if package['package'] == package_name
  719. ]
  720. if len(packages) != 1:
  721. raise ValueError(
  722. "There must be exactly one package with the given name (%s), "
  723. "%s were found." % (package_name, len(packages)))
  724. return packages[0]['version']
  725. def GetRevision(gclient_dict, dep_name):
  726. if 'deps' not in gclient_dict or dep_name not in gclient_dict['deps']:
  727. suggestions = []
  728. if 'deps' in gclient_dict:
  729. for key in gclient_dict['deps']:
  730. if dep_name in key:
  731. suggestions.append(key)
  732. if suggestions:
  733. raise KeyError(
  734. "Could not find any dependency called %s. Did you mean %s" %
  735. (dep_name, ' or '.join(suggestions)))
  736. raise KeyError("Could not find any dependency called %s." % dep_name)
  737. dep = gclient_dict['deps'][dep_name]
  738. if dep is None:
  739. return None
  740. if isinstance(dep, str):
  741. _, _, revision = dep.partition('@')
  742. return revision or None
  743. if isinstance(dep, collections.abc.Mapping) and 'url' in dep:
  744. _, _, revision = dep['url'].partition('@')
  745. return revision or None
  746. raise ValueError('%s is not a valid git dependency.' % dep_name)