roll_downstream_gcs_deps.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. #!/usr/bin/env python3
  2. # Copyright 2024 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """This scripts copies DEPS package information from one source onto
  6. destination.
  7. If the destination doesn't have packages, the script errors out.
  8. Example usage:
  9. roll_downstream_gcs_deps.py \
  10. --source some/repo/DEPS \
  11. --destination some/downstream/repo/DEPS \
  12. --package src/build/linux/debian_bullseye_amd64-sysroot \
  13. --package src/build/linux/debian_bullseye_arm64-sysroot
  14. """
  15. import argparse
  16. import ast
  17. import sys
  18. from typing import Dict, List
  19. def _get_deps(deps_ast: ast.Module) -> Dict[str, ast.Dict]:
  20. """Searches for the deps dict in a DEPS file AST.
  21. Args:
  22. deps_ast: AST of the DEPS file.
  23. Raises:
  24. Exception: If the deps dict is not found.
  25. Returns:
  26. The deps dict.
  27. """
  28. for statement in deps_ast.body:
  29. if not isinstance(statement, ast.Assign):
  30. continue
  31. if len(statement.targets) != 1:
  32. continue
  33. target = statement.targets[0]
  34. if not isinstance(target, ast.Name):
  35. continue
  36. if target.id != 'deps':
  37. continue
  38. if not isinstance(statement.value, ast.Dict):
  39. continue
  40. deps = {}
  41. for key, value in zip(statement.value.keys, statement.value.values):
  42. if not isinstance(key, ast.Constant):
  43. continue
  44. deps[key.value] = value
  45. return deps
  46. raise Exception('no deps found')
  47. def _get_gcs_object_list_ast(package_ast: ast.Dict) -> ast.List:
  48. """Searches for the objects list in a GCS package AST.
  49. Args:
  50. package_ast: AST of the GCS package.
  51. Raises:
  52. Exception: If the package is not a GCS package.
  53. Returns:
  54. AST of the objects list.
  55. """
  56. is_gcs = False
  57. result = None
  58. for key, value in zip(package_ast.keys, package_ast.values):
  59. if not isinstance(key, ast.Constant):
  60. continue
  61. if key.value == 'dep_type' and isinstance(
  62. value, ast.Constant) and value.value == 'gcs':
  63. is_gcs = True
  64. if key.value == 'objects' and isinstance(value, ast.List):
  65. result = value
  66. assert is_gcs, 'Not a GCS dependency!'
  67. assert result, 'No objects found!'
  68. return result
  69. def _replace_ast(destination: str, dest_ast: ast.Module, source: str,
  70. source_ast: ast.Module) -> str:
  71. """Replaces the content of dest_ast with the content of the
  72. same package in source_ast.
  73. Args:
  74. destination: Destination DEPS file content.
  75. dest_ast: AST in the destination DEPS file that will be replaced.
  76. source: Source DEPS file content.
  77. source_ast: AST in the source DEPS file that will replace content of
  78. destination.
  79. Returns:
  80. Content of destination DEPS file with replaced content.
  81. """
  82. source_lines = source.splitlines()
  83. lines = destination.splitlines()
  84. # Copy all lines before the replaced AST.
  85. result = '\n'.join(lines[:dest_ast.lineno - 1]) + '\n'
  86. # Partially copy the line content before AST's value.
  87. result += lines[dest_ast.lineno - 1][:dest_ast.col_offset]
  88. # Copy data from source AST.
  89. if source_ast.lineno == source_ast.end_lineno:
  90. # Starts and ends on the same line.
  91. result += source_lines[
  92. source_ast.lineno -
  93. 1][source_ast.col_offset:source_ast.end_col_offset]
  94. else:
  95. # Copy multiline content from source. The first line and the last line
  96. # of source AST should be partially copied as `result` has a partial
  97. # line from `destination`.
  98. # Partially copy the first line of source AST.
  99. result += source_lines[source_ast.lineno -
  100. 1][source_ast.col_offset:] + '\n'
  101. # Copy content in the middle.
  102. result += '\n'.join(
  103. source_lines[source_ast.lineno:source_ast.end_lineno - 1]) + '\n'
  104. # Partially copy the last line of source AST.
  105. result += source_lines[source_ast.end_lineno -
  106. 1][:source_ast.end_col_offset]
  107. # Copy the rest of the line after the package value.
  108. result += lines[dest_ast.end_lineno - 1][dest_ast.end_col_offset:] + '\n'
  109. # Copy the rest of the lines after the package value.
  110. result += '\n'.join(lines[dest_ast.end_lineno:])
  111. # Add trailing newline
  112. if destination.endswith('\n'):
  113. result += '\n'
  114. return result
  115. def copy_packages(source_content: str, destination_content: str,
  116. source_packages: List[str],
  117. destination_packages: List[str]) -> str:
  118. """Copies GCS packages from source to destination.
  119. Args:
  120. source: Source DEPS file content.
  121. destination: Destination DEPS file content.
  122. packages: List of GCS packages to copy. Only objects are copied.
  123. Returns:
  124. Destination DEPS file content with packages copied.
  125. """
  126. source_deps = _get_deps(ast.parse(source_content, mode='exec'))
  127. for i in range(len(source_packages)):
  128. source_package = source_packages[i]
  129. destination_package = destination_packages[i]
  130. if source_package not in source_deps:
  131. raise Exception('Package %s not found in source' % source_package)
  132. dest_deps = _get_deps(ast.parse(destination_content, mode='exec'))
  133. if destination_package not in dest_deps:
  134. raise Exception('Package %s not found in destination' %
  135. destination_package)
  136. destination_content = _replace_ast(
  137. destination_content,
  138. _get_gcs_object_list_ast(dest_deps[destination_package]),
  139. source_content,
  140. _get_gcs_object_list_ast(source_deps[source_package]))
  141. return destination_content
  142. def main():
  143. parser = argparse.ArgumentParser(description=__doc__)
  144. parser.add_argument('--source-deps',
  145. required=True,
  146. help='Source DEPS file where content will be copied '
  147. 'from')
  148. parser.add_argument('--source-package',
  149. action='append',
  150. required=True,
  151. help='List of DEPS packages to update')
  152. parser.add_argument('--destination-deps',
  153. required=True,
  154. help='Destination DEPS file, where content will be '
  155. 'saved')
  156. parser.add_argument('--destination-package',
  157. action='append',
  158. required=True,
  159. help='List of DEPS packages to update')
  160. args = parser.parse_args()
  161. if not args.source_package:
  162. parser.error('No source packages specified to roll, aborting...')
  163. if not args.destination_package:
  164. parser.error('No destination packages specified to roll, aborting...')
  165. if len(args.destination_package) != len(args.source_package):
  166. parser.error('Source and destination packages must be of the same '
  167. 'length, aborting...')
  168. with open(args.source_deps) as f:
  169. source_content = f.read()
  170. with open(args.destination_deps) as f:
  171. destination_content = f.read()
  172. new_content = copy_packages(source_content, destination_content,
  173. args.source_package, args.destination_package)
  174. with open(args.destination_deps, 'w') as f:
  175. f.write(new_content)
  176. print('Run:')
  177. print(' Destination DEPS file updated. You still need to create and '
  178. 'upload a change.')
  179. return 0
  180. if __name__ == '__main__':
  181. sys.exit(main())