gclient_eval.py 36 KB

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