clone.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. # Copyright (c) 2023 The ungoogled-chromium Authors. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """
  7. Module for cloning the source tree.
  8. """
  9. import sys
  10. from argparse import ArgumentParser
  11. from os import environ, pathsep
  12. from pathlib import Path
  13. from shutil import copytree, copy, move
  14. from stat import S_IWRITE
  15. from subprocess import run
  16. from _common import add_common_params, get_chromium_version, get_logger
  17. from prune_binaries import CONTINGENT_PATHS
  18. # Config file for gclient
  19. # Instances of 'src' replaced with UC_OUT, which will be replaced with the output directory
  20. # third_party/angle/third_party/VK-GL-CTS/src is set to None since it's large and unused
  21. # target_* arguments set to match tarball rather than actual build target
  22. GC_CONFIG = """\
  23. solutions = [
  24. {
  25. "name": "UC_OUT",
  26. "url": "https://chromium.googlesource.com/chromium/src.git",
  27. "managed": False,
  28. "custom_deps": {
  29. "UC_OUT/third_party/angle/third_party/VK-GL-CTS/src": None,
  30. },
  31. "custom_vars": {
  32. "checkout_configuration": "small",
  33. },
  34. },
  35. ];
  36. target_os = ['unix'];
  37. target_os_only = True;
  38. target_cpu = ['x64'];
  39. target_cpu_only = True;
  40. """
  41. def clone(args): # pylint: disable=too-many-branches, too-many-statements
  42. """Clones, downloads, and generates the required sources"""
  43. get_logger().info('Setting up cloning environment')
  44. iswin = sys.platform.startswith('win')
  45. chromium_version = get_chromium_version()
  46. ucstaging = args.output / 'uc_staging'
  47. dtpath = ucstaging / 'depot_tools'
  48. gnpath = ucstaging / 'gn'
  49. environ['GCLIENT_FILE'] = str(ucstaging / '.gclient')
  50. environ['PATH'] += pathsep + str(dtpath)
  51. environ['PYTHONPATH'] = str(dtpath)
  52. # Prevent gclient from auto updating depot_tools
  53. environ['DEPOT_TOOLS_UPDATE'] = '0'
  54. # Don't generate pycache files
  55. environ['PYTHONDONTWRITEBYTECODE'] = '1'
  56. # Allow usage of system python
  57. environ['VPYTHON_BYPASS'] = 'manually managed python not supported by chrome operations'
  58. # depth=2 since generating LASTCHANGE and gpu_lists_version.h require at least two commits
  59. get_logger().info('Cloning chromium source: %s', chromium_version)
  60. if (args.output / '.git').exists():
  61. run(['git', 'fetch', 'origin', 'tag', chromium_version, '--depth=2'],
  62. cwd=args.output,
  63. check=True)
  64. run(['git', 'reset', '--hard', 'FETCH_HEAD'], cwd=args.output, check=True)
  65. run(['git', 'clean', '-ffdx', '-e', 'uc_staging'], cwd=args.output, check=True)
  66. else:
  67. run([
  68. 'git', 'clone', '-c', 'advice.detachedHead=false', '-b', chromium_version, '--depth=2',
  69. "https://chromium.googlesource.com/chromium/src",
  70. str(args.output)
  71. ],
  72. check=True)
  73. # Set up staging directory
  74. ucstaging.mkdir(exist_ok=True)
  75. get_logger().info('Cloning depot_tools')
  76. if dtpath.exists():
  77. run(['git', 'fetch', '--depth=1'], cwd=dtpath, check=True)
  78. run(['git', 'reset', '--hard', 'FETCH_HEAD'], cwd=dtpath, check=True)
  79. run(['git', 'clean', '-ffdx'], cwd=dtpath, check=True)
  80. else:
  81. run([
  82. 'git', 'clone', '--depth=1',
  83. "https://chromium.googlesource.com/chromium/tools/depot_tools",
  84. str(dtpath)
  85. ],
  86. check=True)
  87. if iswin:
  88. (dtpath / 'git.bat').write_text('git')
  89. # Apply changes to gclient
  90. run(['git', 'apply'],
  91. input=Path(__file__).with_name('depot_tools.patch').read_text().replace(
  92. 'UC_OUT', str(args.output)).replace('UC_STAGING', str(ucstaging)),
  93. cwd=dtpath,
  94. check=True,
  95. universal_newlines=True)
  96. # gn requires full history to be able to generate last_commit_position.h
  97. get_logger().info('Cloning gn')
  98. if gnpath.exists():
  99. run(['git', 'fetch'], cwd=gnpath, check=True)
  100. run(['git', 'reset', '--hard', 'FETCH_HEAD'], cwd=gnpath, check=True)
  101. run(['git', 'clean', '-ffdx'], cwd=gnpath, check=True)
  102. else:
  103. run(['git', 'clone', "https://gn.googlesource.com/gn", str(gnpath)], check=True)
  104. get_logger().info('Running gsync')
  105. if args.custom_config:
  106. copy(args.custom_config, ucstaging / '.gclient').replace('UC_OUT', str(args.output))
  107. else:
  108. (ucstaging / '.gclient').write_text(GC_CONFIG.replace('UC_OUT', str(args.output)))
  109. gcpath = dtpath / 'gclient'
  110. if iswin:
  111. gcpath = gcpath.with_suffix('.bat')
  112. # -f, -D, and -R forces a hard reset on changes and deletes deps that have been removed
  113. run([str(gcpath), 'sync', '-f', '-D', '-R', '--no-history', '--nohooks'], check=True)
  114. # Follow tarball procedure:
  115. # https://source.chromium.org/chromium/chromium/tools/build/+/main:recipes/recipes/publish_tarball.py
  116. get_logger().info('Downloading node modules')
  117. run([
  118. sys.executable,
  119. str(dtpath / 'download_from_google_storage.py'), '--no_resume', '--extract', '--no_auth',
  120. '--bucket', 'chromium-nodejs', '-s',
  121. str(args.output / 'third_party' / 'node' / 'node_modules.tar.gz.sha1')
  122. ],
  123. check=True)
  124. get_logger().info('Downloading pgo profiles')
  125. run([
  126. sys.executable,
  127. str(args.output / 'tools' / 'update_pgo_profiles.py'), '--target=' + args.pgo, 'update',
  128. '--gs-url-base=chromium-optimization-profiles/pgo_profiles'
  129. ],
  130. check=True)
  131. # https://chromium-review.googlesource.com/c/chromium/tools/build/+/4380399
  132. run([
  133. sys.executable,
  134. str(args.output / 'v8' / 'tools' / 'builtins-pgo' / 'download_profiles.py'), 'download',
  135. '--depot-tools',
  136. str(dtpath)
  137. ],
  138. check=True)
  139. get_logger().info('Generating: DAWN_VERSION')
  140. run([
  141. sys.executable,
  142. str(args.output / 'build' / 'util' / 'lastchange.py'), '-s',
  143. str(args.output / 'third_party' / 'dawn'), '--revision',
  144. str(args.output / 'gpu' / 'webgpu' / 'DAWN_VERSION')
  145. ],
  146. check=True)
  147. get_logger().info('Generating: LASTCHANGE')
  148. run([
  149. sys.executable,
  150. str(args.output / 'build' / 'util' / 'lastchange.py'), '-o',
  151. str(args.output / 'build' / 'util' / 'LASTCHANGE')
  152. ],
  153. check=True)
  154. get_logger().info('Generating: gpu_lists_version.h')
  155. run([
  156. sys.executable,
  157. str(args.output / 'build' / 'util' / 'lastchange.py'), '-m', 'GPU_LISTS_VERSION',
  158. '--revision-id-only', '--header',
  159. str(args.output / 'gpu' / 'config' / 'gpu_lists_version.h')
  160. ],
  161. check=True)
  162. get_logger().info('Generating: skia_commit_hash.h')
  163. run([
  164. sys.executable,
  165. str(args.output / 'build' / 'util' / 'lastchange.py'), '-m', 'SKIA_COMMIT_HASH', '-s',
  166. str(args.output / 'third_party' / 'skia'), '--header',
  167. str(args.output / 'skia' / 'ext' / 'skia_commit_hash.h')
  168. ],
  169. check=True)
  170. get_logger().info('Generating: last_commit_position.h')
  171. run([sys.executable, str(gnpath / 'build' / 'gen.py')], check=True)
  172. for item in gnpath.iterdir():
  173. if not item.is_dir():
  174. copy(item, args.output / 'tools' / 'gn')
  175. elif item.name != '.git' and item.name != 'out':
  176. copytree(item, args.output / 'tools' / 'gn' / item.name)
  177. move(str(gnpath / 'out' / 'last_commit_position.h'),
  178. str(args.output / 'tools' / 'gn' / 'bootstrap'))
  179. get_logger().info('Removing uneeded files')
  180. # Match removals for the tarball:
  181. # https://source.chromium.org/chromium/chromium/tools/build/+/main:recipes/recipe_modules/chromium/resources/export_tarball.py
  182. remove_dirs = (
  183. (args.output / 'chrome' / 'test' / 'data'),
  184. (args.output / 'content' / 'test' / 'data'),
  185. (args.output / 'courgette' / 'testdata'),
  186. (args.output / 'extensions' / 'test' / 'data'),
  187. (args.output / 'media' / 'test' / 'data'),
  188. (args.output / 'native_client' / 'src' / 'trusted' / 'service_runtime' / 'testdata'),
  189. (args.output / 'third_party' / 'blink' / 'tools'),
  190. (args.output / 'third_party' / 'blink' / 'web_tests'),
  191. (args.output / 'third_party' / 'breakpad' / 'breakpad' / 'src' / 'processor' / 'testdata'),
  192. (args.output / 'third_party' / 'catapult' / 'tracing' / 'test_data'),
  193. (args.output / 'third_party' / 'hunspell' / 'tests'),
  194. (args.output / 'third_party' / 'hunspell_dictionaries'),
  195. (args.output / 'third_party' / 'jdk' / 'current'),
  196. (args.output / 'third_party' / 'jdk' / 'extras'),
  197. (args.output / 'third_party' / 'liblouis' / 'src' / 'tests' / 'braille-specs'),
  198. (args.output / 'third_party' / 'xdg-utils' / 'tests'),
  199. (args.output / 'v8' / 'test'),
  200. )
  201. keep_files = (
  202. (args.output / 'chrome' / 'test' / 'data' / 'webui' / 'i18n_process_css_test.html'),
  203. (args.output / 'chrome' / 'test' / 'data' / 'webui' / 'mojo' / 'foobar.mojom'),
  204. (args.output / 'chrome' / 'test' / 'data' / 'webui' / 'web_ui_test.mojom'),
  205. (args.output / 'v8' / 'test' / 'torque' / 'test-torque.tq'),
  206. )
  207. keep_suffix = ('.gn', '.gni', '.grd', '.gyp', '.isolate', '.pydeps')
  208. # Include Contingent Paths
  209. for cpath in CONTINGENT_PATHS:
  210. remove_dirs += (args.output / Path(cpath), )
  211. for remove_dir in remove_dirs:
  212. for path in sorted(remove_dir.rglob('*'), key=lambda l: len(str(l)), reverse=True):
  213. if path.is_file() and path not in keep_files and path.suffix not in keep_suffix:
  214. try:
  215. path.unlink()
  216. # read-only files can't be deleted on Windows
  217. # so remove the flag and try again.
  218. except PermissionError:
  219. path.chmod(S_IWRITE)
  220. path.unlink()
  221. elif path.is_dir() and not any(path.iterdir()):
  222. try:
  223. path.rmdir()
  224. except PermissionError:
  225. path.chmod(S_IWRITE)
  226. path.rmdir()
  227. for path in sorted(args.output.rglob('*'), key=lambda l: len(str(l)), reverse=True):
  228. if not path.is_symlink() and '.git' not in path.parts:
  229. if path.is_file() and ('out' in path.parts or path.name.startswith('ChangeLog')):
  230. try:
  231. path.unlink()
  232. except PermissionError:
  233. path.chmod(S_IWRITE)
  234. path.unlink()
  235. elif path.is_dir() and not any(path.iterdir()):
  236. try:
  237. path.rmdir()
  238. except PermissionError:
  239. path.chmod(S_IWRITE)
  240. path.rmdir()
  241. get_logger().info('Source cloning complete')
  242. def main():
  243. """CLI Entrypoint"""
  244. parser = ArgumentParser(description=__doc__)
  245. parser.add_argument('-o',
  246. '--output',
  247. type=Path,
  248. metavar='DIRECTORY',
  249. default='chromium',
  250. help='Output directory for the cloned sources. Default: %(default)s')
  251. parser.add_argument('-c',
  252. '--custom-config',
  253. type=Path,
  254. metavar='FILE',
  255. help='Supply a replacement for the default gclient config.')
  256. parser.add_argument('-p',
  257. '--pgo',
  258. default='linux',
  259. choices=('linux', 'mac', 'mac-arm', 'win32', 'win64'),
  260. help='Specifiy which pgo profile to download. Default: %(default)s')
  261. add_common_params(parser)
  262. args = parser.parse_args()
  263. clone(args)
  264. if __name__ == '__main__':
  265. main()