clone.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 re
  10. import sys
  11. from argparse import ArgumentParser
  12. from os import environ, pathsep
  13. from pathlib import Path
  14. from shutil import copytree, copy, move
  15. from stat import S_IWRITE
  16. from subprocess import run
  17. from _common import add_common_params, get_chromium_version, get_logger
  18. from prune_binaries import CONTINGENT_PATHS
  19. # Config file for gclient
  20. # Instances of 'src' replaced with UC_OUT, which will be replaced with the output directory
  21. # custom_deps are set to None since they are large and unused
  22. # target_* arguments set to match tarball rather than actual build target
  23. GC_CONFIG = """\
  24. solutions = [
  25. {
  26. "name": "UC_OUT",
  27. "url": "https://chromium.googlesource.com/chromium/src.git",
  28. "managed": False,
  29. "custom_deps": {
  30. "UC_OUT/third_party/angle/third_party/VK-GL-CTS/src": None,
  31. "UC_OUT/third_party/instrumented_libs": None,
  32. },
  33. "custom_vars": {
  34. "checkout_configuration": "small",
  35. "non_git_source": "False",
  36. },
  37. },
  38. ];
  39. target_os = ['unix'];
  40. target_os_only = True;
  41. target_cpu = ['x64'];
  42. target_cpu_only = True;
  43. """
  44. def clone(args): # pylint: disable=too-many-branches, too-many-locals, too-many-statements
  45. """Clones, downloads, and generates the required sources"""
  46. get_logger().info('Setting up cloning environment')
  47. iswin = sys.platform.startswith('win')
  48. chromium_version = get_chromium_version()
  49. ucstaging = args.output / 'uc_staging'
  50. dtpath = ucstaging / 'depot_tools'
  51. gsuver = '5.30'
  52. gsupath = dtpath / 'external_bin' / 'gsutil' / ('gsutil_%s' % gsuver) / 'gsutil'
  53. gnpath = ucstaging / 'gn'
  54. environ['GCLIENT_FILE'] = str(ucstaging / '.gclient')
  55. environ['PATH'] += pathsep + str(dtpath)
  56. environ['PYTHONPATH'] = str(dtpath)
  57. # Prevent gclient from auto updating depot_tools
  58. environ['DEPOT_TOOLS_UPDATE'] = '0'
  59. # Don't generate pycache files
  60. environ['PYTHONDONTWRITEBYTECODE'] = '1'
  61. # Allow usage of system python
  62. environ['VPYTHON_BYPASS'] = 'manually managed python not supported by chrome operations'
  63. # Google has some regex strings that aren't escaped properly or set as raw
  64. environ["PYTHONWARNINGS"] = "ignore::SyntaxWarning"
  65. # depth=2 since generating LASTCHANGE and gpu_lists_version.h require at least two commits
  66. get_logger().info('Cloning chromium source: %s', chromium_version)
  67. if (args.output / '.git').exists():
  68. run(['git', 'fetch', 'origin', 'tag', chromium_version, '--depth=2'],
  69. cwd=args.output,
  70. check=True)
  71. run(['git', 'reset', '--hard', 'FETCH_HEAD'], cwd=args.output, check=True)
  72. run(['git', 'clean', '-ffdx', '-e', 'uc_staging'], cwd=args.output, check=True)
  73. else:
  74. run([
  75. 'git', 'clone', '-c', 'advice.detachedHead=false', '-b', chromium_version, '--depth=2',
  76. "https://chromium.googlesource.com/chromium/src",
  77. str(args.output)
  78. ],
  79. check=True)
  80. # Set up staging directory
  81. ucstaging.mkdir(exist_ok=True)
  82. get_logger().info('Cloning depot_tools')
  83. dt_commit = re.search(r"depot_tools\.git'\s*\+\s*'@'\s*\+\s*'([^']+)',",
  84. Path(args.output / 'DEPS').read_text()).group(1)
  85. if not dt_commit:
  86. get_logger().error('Unable to obtain commit for depot_tools checkout')
  87. sys.exit(1)
  88. if not dtpath.exists():
  89. dtpath.mkdir()
  90. run(['git', 'init', '-q'], cwd=dtpath, check=True)
  91. run([
  92. 'git', 'remote', 'add', 'origin',
  93. 'https://chromium.googlesource.com/chromium/tools/depot_tools'
  94. ],
  95. cwd=dtpath,
  96. check=True)
  97. run(['git', 'fetch', '--depth=1', 'origin', dt_commit], cwd=dtpath, check=True)
  98. run(['git', 'reset', '--hard', dt_commit], cwd=dtpath, check=True)
  99. run(['git', 'clean', '-ffdx'], cwd=dtpath, check=True)
  100. if iswin:
  101. (dtpath / 'git.bat').write_text('git')
  102. # Apply changes to gclient
  103. run(['git', 'apply'],
  104. input=Path(__file__).with_name('depot_tools.patch').read_text().replace(
  105. 'UC_OUT', str(args.output)).replace('UC_STAGING',
  106. str(ucstaging)).replace('GSUVER', gsuver),
  107. cwd=dtpath,
  108. check=True,
  109. universal_newlines=True)
  110. # Manualy set up the gsutil directory for newer versions of Python
  111. get_logger().info('Cloning gsutil')
  112. if not gsupath.exists():
  113. gsupath.mkdir(parents=True)
  114. run(['git', 'init', '-q'], cwd=gsupath, check=True)
  115. run(['git', 'remote', 'add', 'origin', 'https://github.com/GoogleCloudPlatform/gsutil'],
  116. cwd=gsupath,
  117. check=True)
  118. run(['git', 'fetch', '--depth=1', 'origin', 'v%s' % gsuver], cwd=gsupath, check=True)
  119. run(['git', 'reset', '--hard', 'FETCH_HEAD'], cwd=gsupath, check=True)
  120. run(['git', 'clean', '-ffdx'], cwd=gsupath, check=True)
  121. get_logger().info('Updating gsutil submodules')
  122. run(['git', 'submodule', 'update', '--init', '--recursive', '--depth=1', '-q'],
  123. cwd=gsupath,
  124. check=True)
  125. # apitools needs to be set to a newer commit for newer versions of Python
  126. run(['git', 'fetch', 'origin', 'f0dfa4e3fcb510d7d27389e011198d9f176026e2'],
  127. cwd=(gsupath / 'third_party' / 'apitools'),
  128. check=True)
  129. run(['git', 'reset', '--hard', 'FETCH_HEAD'],
  130. cwd=(gsupath / 'third_party' / 'apitools'),
  131. check=True)
  132. (gsupath / 'install.flag').write_text('This flag file is dropped by clone.py')
  133. # gn requires full history to be able to generate last_commit_position.h
  134. get_logger().info('Cloning gn')
  135. gn_commit = re.search(r"gn_version': 'git_revision:([^']+)',",
  136. Path(args.output / 'DEPS').read_text()).group(1)
  137. if not gn_commit:
  138. get_logger().error('Unable to obtain commit for gn checkout')
  139. sys.exit(1)
  140. if gnpath.exists():
  141. run(['git', 'fetch'], cwd=gnpath, check=True)
  142. else:
  143. run(['git', 'clone', "https://gn.googlesource.com/gn", str(gnpath)], check=True)
  144. run(['git', 'reset', '--hard', gn_commit], cwd=gnpath, check=True)
  145. run(['git', 'clean', '-ffdx'], cwd=gnpath, check=True)
  146. get_logger().info('Running gsync')
  147. if args.custom_config:
  148. copy(args.custom_config, ucstaging / '.gclient').replace('UC_OUT', str(args.output))
  149. else:
  150. (ucstaging / '.gclient').write_text(GC_CONFIG.replace('UC_OUT', str(args.output)))
  151. gcpath = dtpath / 'gclient'
  152. if iswin:
  153. gcpath = gcpath.with_suffix('.bat')
  154. # -f, -D, and -R forces a hard reset on changes and deletes deps that have been removed
  155. run([
  156. str(gcpath), 'sync', '-f', '-D', '-R', '--no-history', '--nohooks',
  157. f'--sysroot={args.sysroot}'
  158. ],
  159. check=True)
  160. # Follow tarball procedure:
  161. # https://source.chromium.org/chromium/chromium/tools/build/+/main:recipes/recipes/publish_tarball.py
  162. get_logger().info('Downloading pgo profiles')
  163. run([
  164. sys.executable,
  165. str(args.output / 'tools' / 'update_pgo_profiles.py'), '--target=' + args.pgo, 'update',
  166. '--gs-url-base=chromium-optimization-profiles/pgo_profiles'
  167. ],
  168. check=True)
  169. # https://chromium-review.googlesource.com/c/chromium/tools/build/+/4380399
  170. run([
  171. sys.executable,
  172. str(args.output / 'v8' / 'tools' / 'builtins-pgo' / 'download_profiles.py'), 'download',
  173. '--depot-tools',
  174. str(dtpath)
  175. ],
  176. check=True)
  177. get_logger().info('Generating: DAWN_VERSION')
  178. run([
  179. sys.executable,
  180. str(args.output / 'build' / 'util' / 'lastchange.py'), '-s',
  181. str(args.output / 'third_party' / 'dawn'), '--revision',
  182. str(args.output / 'gpu' / 'webgpu' / 'DAWN_VERSION')
  183. ],
  184. check=True)
  185. get_logger().info('Generating: LASTCHANGE')
  186. run([
  187. sys.executable,
  188. str(args.output / 'build' / 'util' / 'lastchange.py'), '-o',
  189. str(args.output / 'build' / 'util' / 'LASTCHANGE')
  190. ],
  191. check=True)
  192. get_logger().info('Generating: gpu_lists_version.h')
  193. run([
  194. sys.executable,
  195. str(args.output / 'build' / 'util' / 'lastchange.py'), '-m', 'GPU_LISTS_VERSION',
  196. '--revision-id-only', '--header',
  197. str(args.output / 'gpu' / 'config' / 'gpu_lists_version.h')
  198. ],
  199. check=True)
  200. get_logger().info('Generating: skia_commit_hash.h')
  201. run([
  202. sys.executable,
  203. str(args.output / 'build' / 'util' / 'lastchange.py'), '-m', 'SKIA_COMMIT_HASH', '-s',
  204. str(args.output / 'third_party' / 'skia'), '--header',
  205. str(args.output / 'skia' / 'ext' / 'skia_commit_hash.h')
  206. ],
  207. check=True)
  208. get_logger().info('Generating: last_commit_position.h')
  209. run([sys.executable, str(gnpath / 'build' / 'gen.py')], check=True)
  210. for item in gnpath.iterdir():
  211. if not item.is_dir():
  212. copy(item, args.output / 'tools' / 'gn')
  213. elif item.name != '.git' and item.name != 'out':
  214. copytree(item, args.output / 'tools' / 'gn' / item.name)
  215. move(str(gnpath / 'out' / 'last_commit_position.h'),
  216. str(args.output / 'tools' / 'gn' / 'bootstrap'))
  217. get_logger().info('Removing uneeded files')
  218. # Match removals for the tarball:
  219. # https://source.chromium.org/chromium/chromium/tools/build/+/main:recipes/recipe_modules/chromium/resources/export_tarball.py
  220. remove_dirs = (
  221. (args.output / 'chrome' / 'test' / 'data'),
  222. (args.output / 'content' / 'test' / 'data'),
  223. (args.output / 'courgette' / 'testdata'),
  224. (args.output / 'extensions' / 'test' / 'data'),
  225. (args.output / 'media' / 'test' / 'data'),
  226. (args.output / 'native_client' / 'src' / 'trusted' / 'service_runtime' / 'testdata'),
  227. (args.output / 'third_party' / 'blink' / 'tools'),
  228. (args.output / 'third_party' / 'blink' / 'web_tests'),
  229. (args.output / 'third_party' / 'breakpad' / 'breakpad' / 'src' / 'processor' / 'testdata'),
  230. (args.output / 'third_party' / 'catapult' / 'tracing' / 'test_data'),
  231. (args.output / 'third_party' / 'hunspell' / 'tests'),
  232. (args.output / 'third_party' / 'hunspell_dictionaries'),
  233. (args.output / 'third_party' / 'jdk' / 'current'),
  234. (args.output / 'third_party' / 'jdk' / 'extras'),
  235. (args.output / 'third_party' / 'liblouis' / 'src' / 'tests' / 'braille-specs'),
  236. (args.output / 'third_party' / 'xdg-utils' / 'tests'),
  237. (args.output / 'v8' / 'test'),
  238. )
  239. keep_files = (
  240. (args.output / 'chrome' / 'test' / 'data' / 'webui' / 'i18n_process_css_test.html'),
  241. (args.output / 'chrome' / 'test' / 'data' / 'webui' / 'mojo' / 'foobar.mojom'),
  242. (args.output / 'chrome' / 'test' / 'data' / 'webui' / 'web_ui_test.mojom'),
  243. (args.output / 'v8' / 'test' / 'torque' / 'test-torque.tq'),
  244. )
  245. keep_suffix = ('.gn', '.gni', '.grd', '.gyp', '.isolate', '.pydeps')
  246. # Include Contingent Paths
  247. for cpath in CONTINGENT_PATHS:
  248. if args.sysroot and f'{args.sysroot}-sysroot' in cpath:
  249. continue
  250. remove_dirs += (args.output / Path(cpath), )
  251. for remove_dir in remove_dirs:
  252. for path in sorted(remove_dir.rglob('*'), key=lambda l: len(str(l)), reverse=True):
  253. if path.is_file() and path not in keep_files and path.suffix not in keep_suffix:
  254. try:
  255. path.unlink()
  256. # read-only files can't be deleted on Windows
  257. # so remove the flag and try again.
  258. except PermissionError:
  259. path.chmod(S_IWRITE)
  260. path.unlink()
  261. elif path.is_dir() and not any(path.iterdir()):
  262. try:
  263. path.rmdir()
  264. except PermissionError:
  265. path.chmod(S_IWRITE)
  266. path.rmdir()
  267. for path in sorted(args.output.rglob('*'), key=lambda l: len(str(l)), reverse=True):
  268. if not path.is_symlink() and '.git' not in path.parts:
  269. if path.is_file() and ('out' in path.parts or path.name.startswith('ChangeLog')):
  270. try:
  271. path.unlink()
  272. except PermissionError:
  273. path.chmod(S_IWRITE)
  274. path.unlink()
  275. elif path.is_dir() and not any(path.iterdir()):
  276. try:
  277. path.rmdir()
  278. except PermissionError:
  279. path.chmod(S_IWRITE)
  280. path.rmdir()
  281. get_logger().info('Source cloning complete')
  282. def main():
  283. """CLI Entrypoint"""
  284. parser = ArgumentParser(description=__doc__)
  285. parser.add_argument('-o',
  286. '--output',
  287. type=Path,
  288. metavar='DIRECTORY',
  289. default='chromium',
  290. help='Output directory for the cloned sources. Default: %(default)s')
  291. parser.add_argument('-c',
  292. '--custom-config',
  293. type=Path,
  294. metavar='FILE',
  295. help='Supply a replacement for the default gclient config.')
  296. parser.add_argument('-p',
  297. '--pgo',
  298. default='linux',
  299. choices=('linux', 'mac', 'mac-arm', 'win32', 'win64'),
  300. help='Specifiy which pgo profile to download. Default: %(default)s')
  301. parser.add_argument('-s',
  302. '--sysroot',
  303. choices=('amd64', 'arm64', 'armhf', 'i386', 'mips64el', 'mipsel'),
  304. help='Download a linux sysroot for the given architecture')
  305. add_common_params(parser)
  306. args = parser.parse_args()
  307. clone(args)
  308. if __name__ == '__main__':
  309. main()