fake_repos.py 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2011 The 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. """Generate fake repositories for testing."""
  7. import atexit
  8. import datetime
  9. import errno
  10. import io
  11. import logging
  12. import os
  13. import pprint
  14. import random
  15. import re
  16. import socket
  17. import sys
  18. import tempfile
  19. import textwrap
  20. import time
  21. # trial_dir must be first for non-system libraries.
  22. from testing_support import trial_dir
  23. import gclient_utils
  24. import scm
  25. import subprocess2
  26. DEFAULT_BRANCH = 'main'
  27. def write(path, content):
  28. f = open(path, 'wb')
  29. f.write(content.encode())
  30. f.close()
  31. join = os.path.join
  32. def read_tree(tree_root):
  33. """Returns a dict of all the files in a tree. Defaults to self.root_dir."""
  34. tree = {}
  35. for root, dirs, files in os.walk(tree_root):
  36. for d in filter(lambda x: x.startswith('.'), dirs):
  37. dirs.remove(d)
  38. for f in [join(root, f) for f in files if not f.startswith('.')]:
  39. filepath = f[len(tree_root) + 1:].replace(os.sep, '/')
  40. assert len(filepath) > 0, f
  41. with io.open(join(root, f), encoding='utf-8') as f:
  42. tree[filepath] = f.read()
  43. return tree
  44. def dict_diff(dict1, dict2):
  45. diff = {}
  46. for k, v in dict1.items():
  47. if k not in dict2:
  48. diff[k] = v
  49. elif v != dict2[k]:
  50. diff[k] = (v, dict2[k])
  51. for k, v in dict2.items():
  52. if k not in dict1:
  53. diff[k] = v
  54. return diff
  55. def commit_git(repo):
  56. """Commits the changes and returns the new hash."""
  57. subprocess2.check_call(['git', 'add', '-A', '-f'], cwd=repo)
  58. subprocess2.check_call(['git', 'commit', '-q', '--message', 'foo'],
  59. cwd=repo)
  60. rev = subprocess2.check_output(['git', 'show-ref', '--head', 'HEAD'],
  61. cwd=repo).split(b' ', 1)[0]
  62. rev = rev.decode('utf-8')
  63. logging.debug('At revision %s' % rev)
  64. return rev
  65. class FakeReposBase(object):
  66. """Generate git repositories to test gclient functionality.
  67. Many DEPS functionalities need to be tested: Var, deps_os, hooks,
  68. use_relative_paths.
  69. And types of dependencies: Relative urls, Full urls, git.
  70. populateGit() needs to be implemented by the subclass.
  71. """
  72. # Hostname
  73. NB_GIT_REPOS = 1
  74. USERS = [
  75. ('user1@example.com', 'foo Fuß'),
  76. ('user2@example.com', 'bar'),
  77. ]
  78. def __init__(self, host=None):
  79. self.trial = trial_dir.TrialDir('repos')
  80. self.host = host or '127.0.0.1'
  81. # Format is { repo: [ None, (hash, tree), (hash, tree), ... ], ... }
  82. # so reference looks like self.git_hashes[repo][rev][0] for hash and
  83. # self.git_hashes[repo][rev][1] for it's tree snapshot.
  84. # It is 1-based too.
  85. self.git_hashes = {}
  86. self.git_pid_file_name = None
  87. self.git_base = None
  88. self.initialized = False
  89. @property
  90. def root_dir(self):
  91. return self.trial.root_dir
  92. def set_up(self):
  93. """All late initialization comes here."""
  94. if not self.root_dir:
  95. try:
  96. # self.root_dir is not set before this call.
  97. self.trial.set_up()
  98. self.git_base = join(self.root_dir, 'git') + os.sep
  99. finally:
  100. # Registers cleanup.
  101. atexit.register(self.tear_down)
  102. def tear_down(self):
  103. """Kills the servers and delete the directories."""
  104. self.tear_down_git()
  105. # This deletes the directories.
  106. self.trial.tear_down()
  107. self.trial = None
  108. def tear_down_git(self):
  109. if self.trial.SHOULD_LEAK:
  110. return False
  111. logging.debug('Removing %s' % self.git_base)
  112. gclient_utils.rmtree(self.git_base)
  113. return True
  114. @staticmethod
  115. def _genTree(root, tree_dict):
  116. """For a dictionary of file contents, generate a filesystem."""
  117. if not os.path.isdir(root):
  118. os.makedirs(root)
  119. for (k, v) in tree_dict.items():
  120. k_os = k.replace('/', os.sep)
  121. k_arr = k_os.split(os.sep)
  122. if len(k_arr) > 1:
  123. p = os.sep.join([root] + k_arr[:-1])
  124. if not os.path.isdir(p):
  125. os.makedirs(p)
  126. if v is None:
  127. os.remove(join(root, k))
  128. else:
  129. write(join(root, k), v)
  130. def set_up_git(self):
  131. """Creates git repositories and start the servers."""
  132. self.set_up()
  133. if self.initialized:
  134. return True
  135. try:
  136. subprocess2.check_output(['git', '--version'])
  137. except (OSError, subprocess2.CalledProcessError):
  138. return False
  139. for repo in ['repo_%d' % r for r in range(1, self.NB_GIT_REPOS + 1)]:
  140. # TODO(crbug.com/114712) use git.init -b and remove 'checkout' once
  141. # git is upgraded to 2.28 on all builders.
  142. subprocess2.check_call(
  143. ['git', 'init', '-q',
  144. join(self.git_base, repo)])
  145. subprocess2.check_call(
  146. ['git', 'checkout', '-q', '-b', DEFAULT_BRANCH],
  147. cwd=join(self.git_base, repo))
  148. self.git_hashes[repo] = [(None, None)]
  149. self.populateGit()
  150. self.initialized = True
  151. return True
  152. def _git_rev_parse(self, path):
  153. return subprocess2.check_output(['git', 'rev-parse', 'HEAD'],
  154. cwd=path).strip()
  155. def _commit_git(self, repo, tree, base=None):
  156. repo_root = join(self.git_base, repo)
  157. if base:
  158. base_commit = self.git_hashes[repo][base][0]
  159. subprocess2.check_call(['git', 'checkout', base_commit],
  160. cwd=repo_root)
  161. self._genTree(repo_root, tree)
  162. commit_hash = commit_git(repo_root)
  163. base = base or -1
  164. if self.git_hashes[repo][base][1]:
  165. new_tree = self.git_hashes[repo][base][1].copy()
  166. new_tree.update(tree)
  167. else:
  168. new_tree = tree.copy()
  169. self.git_hashes[repo].append((commit_hash, new_tree))
  170. def _create_ref(self, repo, ref, revision):
  171. repo_root = join(self.git_base, repo)
  172. subprocess2.check_call(
  173. ['git', 'update-ref', ref, self.git_hashes[repo][revision][0]],
  174. cwd=repo_root)
  175. def _fast_import_git(self, repo, data):
  176. repo_root = join(self.git_base, repo)
  177. logging.debug('%s: fast-import %s', repo, data)
  178. subprocess2.check_call(['git', 'fast-import', '--quiet'],
  179. cwd=repo_root,
  180. stdin=data.encode())
  181. def populateGit(self):
  182. raise NotImplementedError()
  183. class FakeRepos(FakeReposBase):
  184. """Implements populateGit()."""
  185. NB_GIT_REPOS = 20
  186. def populateGit(self):
  187. # Testing:
  188. # - dependency disappear
  189. # - dependency renamed
  190. # - versioned and unversioned reference
  191. # - relative and full reference
  192. # - deps_os
  193. # - var
  194. # - hooks
  195. # TODO(maruel):
  196. # - use_relative_paths
  197. self._commit_git('repo_3', {
  198. 'origin': 'git/repo_3@1\n',
  199. })
  200. self._commit_git('repo_3', {
  201. 'origin': 'git/repo_3@2\n',
  202. })
  203. self._commit_git(
  204. 'repo_1',
  205. {
  206. 'DEPS': """
  207. vars = {
  208. 'DummyVariable': 'repo',
  209. 'false_var': False,
  210. 'false_str_var': 'False',
  211. 'true_var': True,
  212. 'true_str_var': 'True',
  213. 'str_var': 'abc',
  214. 'cond_var': 'false_str_var and true_var',
  215. }
  216. # Nest the args file in a sub-repo, to make sure we don't try to
  217. # write it before we've cloned everything.
  218. gclient_gn_args_file = 'src/repo2/gclient.args'
  219. gclient_gn_args = [
  220. 'false_var',
  221. 'false_str_var',
  222. 'true_var',
  223. 'true_str_var',
  224. 'str_var',
  225. 'cond_var',
  226. ]
  227. deps = {
  228. 'src/repo2': {
  229. 'url': %(git_base)r + 'repo_2',
  230. 'condition': 'True',
  231. },
  232. 'src/repo2/repo3': '/' + Var('DummyVariable') + '_3@%(hash3)s',
  233. # Test that deps where condition evaluates to False are skipped.
  234. 'src/repo5': {
  235. 'url': '/repo_5',
  236. 'condition': 'False',
  237. },
  238. }
  239. deps_os = {
  240. 'mac': {
  241. 'src/repo4': '/repo_4',
  242. },
  243. }""" % {
  244. 'git_base': self.git_base,
  245. # See self.__init__() for the format. Grab's the hash of the
  246. # first commit in repo_2. Only keep the first 7 character
  247. # because of: TODO(maruel): http://crosbug.com/3591 We need
  248. # to strip the hash.. duh.
  249. 'hash3': self.git_hashes['repo_3'][1][0][:7]
  250. },
  251. 'origin': 'git/repo_1@1\n',
  252. 'foo bar': 'some file with a space',
  253. })
  254. self._commit_git(
  255. 'repo_2', {
  256. 'origin':
  257. 'git/repo_2@1\n',
  258. 'DEPS':
  259. """
  260. vars = {
  261. 'repo2_false_var': 'False',
  262. }
  263. deps = {
  264. 'foo/bar': {
  265. 'url': '/repo_3',
  266. 'condition': 'repo2_false_var',
  267. }
  268. }
  269. """,
  270. })
  271. self._commit_git('repo_2', {
  272. 'origin': 'git/repo_2@2\n',
  273. })
  274. self._commit_git('repo_4', {
  275. 'origin': 'git/repo_4@1\n',
  276. })
  277. self._commit_git('repo_4', {
  278. 'origin': 'git/repo_4@2\n',
  279. })
  280. self._commit_git(
  281. 'repo_1',
  282. {
  283. 'DEPS': """
  284. deps = {
  285. 'src/repo2': %(git_base)r + 'repo_2@%(hash)s',
  286. 'src/repo2/repo_renamed': '/repo_3',
  287. 'src/should_not_process': {
  288. 'url': '/repo_4',
  289. 'condition': 'False',
  290. }
  291. }
  292. # I think this is wrong to have the hooks run from the base of the gclient
  293. # checkout. It's maybe a bit too late to change that behavior.
  294. hooks = [
  295. {
  296. 'pattern': '.',
  297. 'action': ['python3', '-c',
  298. 'open(\\'src/git_hooked1\\', \\'w\\').write(\\'git_hooked1\\')'],
  299. },
  300. {
  301. # Should not be run.
  302. 'pattern': 'nonexistent',
  303. 'action': ['python3', '-c',
  304. 'open(\\'src/git_hooked2\\', \\'w\\').write(\\'git_hooked2\\')'],
  305. },
  306. ]
  307. """ % {
  308. 'git_base': self.git_base,
  309. # See self.__init__() for the format. Grab's the hash of the
  310. # first commit in repo_2. Only keep the first 7 character
  311. # because of: TODO(maruel): http://crosbug.com/3591 We need
  312. # to strip the hash.. duh.
  313. 'hash': self.git_hashes['repo_2'][1][0][:7]
  314. },
  315. 'origin': 'git/repo_1@2\n',
  316. })
  317. self._commit_git('repo_5', {'origin': 'git/repo_5@1\n'})
  318. self._commit_git(
  319. 'repo_5', {
  320. 'DEPS': """
  321. deps = {
  322. 'src/repo1': %(git_base)r + 'repo_1@%(hash1)s',
  323. 'src/repo2': %(git_base)r + 'repo_2@%(hash2)s',
  324. }
  325. # Hooks to run after a project is processed but before its dependencies are
  326. # processed.
  327. pre_deps_hooks = [
  328. {
  329. 'action': ['python3', '-c',
  330. 'print("pre-deps hook"); open(\\'src/git_pre_deps_hooked\\', \\'w\\').write(\\'git_pre_deps_hooked\\')'],
  331. }
  332. ]
  333. """ % {
  334. 'git_base': self.git_base,
  335. 'hash1': self.git_hashes['repo_1'][2][0][:7],
  336. 'hash2': self.git_hashes['repo_2'][1][0][:7],
  337. },
  338. 'origin': 'git/repo_5@2\n',
  339. })
  340. self._commit_git(
  341. 'repo_5', {
  342. 'DEPS': """
  343. deps = {
  344. 'src/repo1': %(git_base)r + 'repo_1@%(hash1)s',
  345. 'src/repo2': %(git_base)r + 'repo_2@%(hash2)s',
  346. }
  347. # Hooks to run after a project is processed but before its dependencies are
  348. # processed.
  349. pre_deps_hooks = [
  350. {
  351. 'action': ['python3', '-c',
  352. 'print("pre-deps hook"); open(\\'src/git_pre_deps_hooked\\', \\'w\\').write(\\'git_pre_deps_hooked\\')'],
  353. },
  354. {
  355. 'action': ['python3', '-c', 'import sys; sys.exit(1)'],
  356. }
  357. ]
  358. """ % {
  359. 'git_base': self.git_base,
  360. 'hash1': self.git_hashes['repo_1'][2][0][:7],
  361. 'hash2': self.git_hashes['repo_2'][1][0][:7],
  362. },
  363. 'origin': 'git/repo_5@3\n',
  364. })
  365. self._commit_git(
  366. 'repo_6', {
  367. 'DEPS': """
  368. vars = {
  369. 'DummyVariable': 'repo',
  370. 'git_base': %(git_base)r,
  371. 'hook1_contents': 'git_hooked1',
  372. 'repo5_var': '/repo_5',
  373. 'false_var': False,
  374. 'false_str_var': 'False',
  375. 'true_var': True,
  376. 'true_str_var': 'True',
  377. 'str_var': 'abc',
  378. 'cond_var': 'false_str_var and true_var',
  379. }
  380. gclient_gn_args_file = 'src/repo2/gclient.args'
  381. gclient_gn_args = [
  382. 'false_var',
  383. 'false_str_var',
  384. 'true_var',
  385. 'true_str_var',
  386. 'str_var',
  387. 'cond_var',
  388. ]
  389. allowed_hosts = [
  390. %(git_base)r,
  391. ]
  392. deps = {
  393. 'src/repo2': {
  394. 'url': Var('git_base') + 'repo_2@%(hash)s',
  395. 'condition': 'true_str_var',
  396. },
  397. 'src/repo4': {
  398. 'url': '/repo_4',
  399. 'condition': 'False',
  400. },
  401. # Entries can have a None repository, which has the effect of either:
  402. # - disabling a dep checkout (e.g. in a .gclient solution to prevent checking
  403. # out optional large repos, or in deps_os where some repos aren't used on some
  404. # platforms)
  405. # - allowing a completely local directory to be processed by gclient (handy
  406. # for dealing with "custom" DEPS, like buildspecs).
  407. '/repoLocal': {
  408. 'url': None,
  409. },
  410. 'src/repo8': '/repo_8',
  411. 'src/repo15': '/repo_15',
  412. 'src/repo16': '/repo_16',
  413. }
  414. deps_os ={
  415. 'mac': {
  416. # This entry should not appear in flattened DEPS' |deps|.
  417. 'src/mac_repo': '{repo5_var}',
  418. },
  419. 'unix': {
  420. # This entry should not appear in flattened DEPS' |deps|.
  421. 'src/unix_repo': '{repo5_var}',
  422. },
  423. 'win': {
  424. # This entry should not appear in flattened DEPS' |deps|.
  425. 'src/win_repo': '{repo5_var}',
  426. },
  427. }
  428. hooks = [
  429. {
  430. 'pattern': '.',
  431. 'condition': 'True',
  432. 'action': ['python3', '-c',
  433. 'open(\\'src/git_hooked1\\', \\'w\\').write(\\'{hook1_contents}\\')'],
  434. },
  435. {
  436. # Should not be run.
  437. 'pattern': 'nonexistent',
  438. 'action': ['python3', '-c',
  439. 'open(\\'src/git_hooked2\\', \\'w\\').write(\\'git_hooked2\\')'],
  440. },
  441. ]
  442. hooks_os = {
  443. 'mac': [
  444. {
  445. 'pattern': '.',
  446. 'action': ['python3', '-c',
  447. 'open(\\'src/git_hooked_mac\\', \\'w\\').write('
  448. '\\'git_hooked_mac\\')'],
  449. },
  450. ],
  451. }
  452. recursedeps = [
  453. 'src/repo2',
  454. 'src/repo8',
  455. 'src/repo15',
  456. 'src/repo16',
  457. ]""" % {
  458. 'git_base': self.git_base,
  459. 'hash': self.git_hashes['repo_2'][1][0][:7]
  460. },
  461. 'origin': 'git/repo_6@1\n',
  462. })
  463. self._commit_git(
  464. 'repo_7', {
  465. 'DEPS': """
  466. vars = {
  467. 'true_var': 'True',
  468. 'false_var': 'true_var and False',
  469. }
  470. hooks = [
  471. {
  472. 'action': ['python3', '-c',
  473. 'open(\\'src/should_run\\', \\'w\\').write(\\'should_run\\')'],
  474. 'condition': 'true_var or True',
  475. },
  476. {
  477. 'action': ['python3', '-c',
  478. 'open(\\'src/should_not_run\\', \\'w\\').write(\\'should_not_run\\')'],
  479. 'condition': 'false_var',
  480. },
  481. ]""",
  482. 'origin': 'git/repo_7@1\n',
  483. })
  484. self._commit_git(
  485. 'repo_8', {
  486. 'DEPS': """
  487. deps_os ={
  488. 'mac': {
  489. 'src/recursed_os_repo': '/repo_5',
  490. },
  491. 'unix': {
  492. 'src/recursed_os_repo': '/repo_5',
  493. },
  494. }""",
  495. 'origin': 'git/repo_8@1\n',
  496. })
  497. self._commit_git(
  498. 'repo_9', {
  499. 'DEPS': """
  500. vars = {
  501. 'str_var': 'xyz',
  502. }
  503. gclient_gn_args_file = 'src/repo8/gclient.args'
  504. gclient_gn_args = [
  505. 'str_var',
  506. ]
  507. deps = {
  508. 'src/repo8': '/repo_8',
  509. # This entry should appear in flattened file,
  510. # but not recursed into, since it's not
  511. # in recursedeps.
  512. 'src/repo7': '/repo_7',
  513. }
  514. deps_os = {
  515. 'android': {
  516. # This entry should only appear in flattened |deps_os|,
  517. # not |deps|, even when used with |recursedeps|.
  518. 'src/repo4': '/repo_4',
  519. }
  520. }
  521. recursedeps = [
  522. 'src/repo4',
  523. 'src/repo8',
  524. ]""",
  525. 'origin': 'git/repo_9@1\n',
  526. })
  527. self._commit_git(
  528. 'repo_10', {
  529. 'DEPS': """
  530. gclient_gn_args_from = 'src/repo9'
  531. deps = {
  532. 'src/repo9': '/repo_9',
  533. # This entry should appear in flattened file,
  534. # but not recursed into, since it's not
  535. # in recursedeps.
  536. 'src/repo6': '/repo_6',
  537. }
  538. deps_os = {
  539. 'mac': {
  540. 'src/repo11': '/repo_11',
  541. },
  542. 'ios': {
  543. 'src/repo11': '/repo_11',
  544. }
  545. }
  546. recursedeps = [
  547. 'src/repo9',
  548. 'src/repo11',
  549. ]""",
  550. 'origin': 'git/repo_10@1\n',
  551. })
  552. self._commit_git(
  553. 'repo_11', {
  554. 'DEPS': """
  555. deps = {
  556. 'src/repo12': '/repo_12',
  557. }""",
  558. 'origin': 'git/repo_11@1\n',
  559. })
  560. self._commit_git('repo_12', {
  561. 'origin': 'git/repo_12@1\n',
  562. })
  563. self._fast_import_git(
  564. 'repo_12', """blob
  565. mark :1
  566. data 6
  567. Hello
  568. blob
  569. mark :2
  570. data 4
  571. Bye
  572. reset refs/changes/1212
  573. commit refs/changes/1212
  574. mark :3
  575. author Bob <bob@example.com> 1253744361 -0700
  576. committer Bob <bob@example.com> 1253744361 -0700
  577. data 8
  578. A and B
  579. M 100644 :1 a
  580. M 100644 :2 b
  581. """)
  582. self._commit_git(
  583. 'repo_13', {
  584. 'DEPS': """
  585. deps = {
  586. 'src/repo12': '/repo_12',
  587. }""",
  588. 'origin': 'git/repo_13@1\n',
  589. })
  590. self._commit_git(
  591. 'repo_13', {
  592. 'DEPS': """
  593. deps = {
  594. 'src/repo12': '/repo_12@refs/changes/1212',
  595. }""",
  596. 'origin': 'git/repo_13@2\n',
  597. })
  598. # src/repo12 is now a CIPD dependency.
  599. self._commit_git(
  600. 'repo_13', {
  601. 'DEPS': """
  602. deps = {
  603. 'src/repo12': {
  604. 'packages': [
  605. {
  606. 'package': 'foo',
  607. 'version': '1.3',
  608. },
  609. ],
  610. 'dep_type': 'cipd',
  611. },
  612. }
  613. hooks = [{
  614. # make sure src/repo12 exists and is a CIPD dir.
  615. 'action': ['python3', '-c', 'with open("src/repo12/_cipd"): pass'],
  616. }]
  617. """,
  618. 'origin': 'git/repo_13@3\n'
  619. })
  620. self._commit_git(
  621. 'repo_14', {
  622. 'DEPS':
  623. textwrap.dedent("""\
  624. vars = {}
  625. deps = {
  626. 'src/cipd_dep': {
  627. 'packages': [
  628. {
  629. 'package': 'package0',
  630. 'version': '0.1',
  631. },
  632. ],
  633. 'dep_type': 'cipd',
  634. },
  635. 'src/another_cipd_dep': {
  636. 'packages': [
  637. {
  638. 'package': 'package1',
  639. 'version': '1.1-cr0',
  640. },
  641. {
  642. 'package': 'package2',
  643. 'version': '1.13',
  644. },
  645. ],
  646. 'dep_type': 'cipd',
  647. },
  648. 'src/cipd_dep_with_cipd_variable': {
  649. 'packages': [
  650. {
  651. 'package': 'package3/${{platform}}',
  652. 'version': '1.2',
  653. },
  654. ],
  655. 'dep_type': 'cipd',
  656. },
  657. }"""),
  658. 'origin':
  659. 'git/repo_14@2\n'
  660. })
  661. # A repo with a hook to be recursed in, without use_relative_paths
  662. self._commit_git(
  663. 'repo_15', {
  664. 'DEPS':
  665. textwrap.dedent("""\
  666. hooks = [{
  667. "name": "absolute_cwd",
  668. "pattern": ".",
  669. "action": ["python3", "-c", "pass"]
  670. }]"""),
  671. 'origin':
  672. 'git/repo_15@2\n'
  673. })
  674. # A repo with a hook to be recursed in, with use_relative_paths
  675. self._commit_git(
  676. 'repo_16', {
  677. 'DEPS':
  678. textwrap.dedent("""\
  679. use_relative_paths=True
  680. hooks = [{
  681. "name": "relative_cwd",
  682. "pattern": ".",
  683. "action": ["python3", "relative.py"]
  684. }]"""),
  685. 'relative.py':
  686. 'pass',
  687. 'origin':
  688. 'git/repo_16@2\n'
  689. })
  690. # A repo with a gclient_gn_args_file and use_relative_paths
  691. self._commit_git(
  692. 'repo_17', {
  693. 'DEPS':
  694. textwrap.dedent("""\
  695. use_relative_paths=True
  696. vars = {
  697. 'toto': 'tata',
  698. }
  699. gclient_gn_args_file = 'repo17_gclient.args'
  700. gclient_gn_args = [
  701. 'toto',
  702. ]"""),
  703. 'origin':
  704. 'git/repo_17@2\n'
  705. })
  706. self._commit_git(
  707. 'repo_18', {
  708. 'DEPS':
  709. textwrap.dedent("""\
  710. deps = {
  711. 'src/cipd_dep': {
  712. 'packages': [
  713. {
  714. 'package': 'package0',
  715. 'version': 'package0-fake-tag:1.0',
  716. },
  717. {
  718. 'package': 'package0/${{platform}}',
  719. 'version': 'package0/${{platform}}-fake-tag:1.0',
  720. },
  721. {
  722. 'package': 'package1/another',
  723. 'version': 'package1/another-fake-tag:1.0',
  724. },
  725. ],
  726. 'dep_type': 'cipd',
  727. },
  728. }"""),
  729. 'origin':
  730. 'git/repo_18@2\n'
  731. })
  732. # a relative path repo
  733. self._commit_git(
  734. 'repo_19', {
  735. 'DEPS': """
  736. git_dependencies = "SUBMODULES"
  737. use_relative_paths = True
  738. vars = {
  739. 'foo_checkout': True,
  740. }
  741. deps = {
  742. "some_repo": {
  743. "url": '/repo_2@%(hash_2)s',
  744. "condition": "not foo_checkout",
  745. },
  746. "chicken/dickens": {
  747. "url": '/repo_3@%(hash_3)s',
  748. },
  749. "weird/deps": {
  750. "url": '/repo_1'
  751. },
  752. "bar": {
  753. "packages": [{
  754. "package": "lemur",
  755. "version": "version:1234",
  756. }],
  757. "dep_type": "cipd",
  758. },
  759. }""" % {
  760. 'hash_2': self.git_hashes['repo_2'][1][0],
  761. 'hash_3': self.git_hashes['repo_3'][1][0],
  762. },
  763. })
  764. # a non-relative_path repo
  765. self._commit_git(
  766. 'repo_20', {
  767. 'DEPS': """
  768. git_dependencies = "SUBMODULES"
  769. vars = {
  770. 'foo_checkout': True,
  771. }
  772. deps = {
  773. "foo/some_repo": {
  774. "url": '/repo_2@%(hash_2)s',
  775. "condition": "not foo_checkout",
  776. },
  777. "foo/chicken/dickens": {
  778. "url": '/repo_3@%(hash_3)s',
  779. },
  780. "foo/weird/deps": {
  781. "url": '/repo_1'
  782. },
  783. "foo/bar": {
  784. "packages": [{
  785. "package": "lemur",
  786. "version": "version:1234",
  787. }],
  788. "dep_type": "cipd",
  789. },
  790. }""" % {
  791. 'hash_2': self.git_hashes['repo_2'][1][0],
  792. 'hash_3': self.git_hashes['repo_3'][1][0],
  793. },
  794. })
  795. class FakeRepoSkiaDEPS(FakeReposBase):
  796. """Simulates the Skia DEPS transition in Chrome."""
  797. NB_GIT_REPOS = 5
  798. DEPS_git_pre = """deps = {
  799. 'src/third_party/skia/gyp': %(git_base)r + 'repo_3',
  800. 'src/third_party/skia/include': %(git_base)r + 'repo_4',
  801. 'src/third_party/skia/src': %(git_base)r + 'repo_5',
  802. }"""
  803. DEPS_post = """deps = {
  804. 'src/third_party/skia': %(git_base)r + 'repo_1',
  805. }"""
  806. def populateGit(self):
  807. # Skia repo.
  808. self._commit_git(
  809. 'repo_1', {
  810. 'skia_base_file': 'root-level file.',
  811. 'gyp/gyp_file': 'file in the gyp directory',
  812. 'include/include_file': 'file in the include directory',
  813. 'src/src_file': 'file in the src directory',
  814. })
  815. self._commit_git(
  816. 'repo_3',
  817. { # skia/gyp
  818. 'gyp_file': 'file in the gyp directory',
  819. })
  820. self._commit_git('repo_4', { # skia/include
  821. 'include_file': 'file in the include directory',
  822. })
  823. self._commit_git(
  824. 'repo_5',
  825. { # skia/src
  826. 'src_file': 'file in the src directory',
  827. })
  828. # Chrome repo.
  829. self._commit_git(
  830. 'repo_2', {
  831. 'DEPS': self.DEPS_git_pre % {
  832. 'git_base': self.git_base
  833. },
  834. 'myfile': 'src/trunk/src@1'
  835. })
  836. self._commit_git(
  837. 'repo_2', {
  838. 'DEPS': self.DEPS_post % {
  839. 'git_base': self.git_base
  840. },
  841. 'myfile': 'src/trunk/src@2'
  842. })
  843. class FakeRepoBlinkDEPS(FakeReposBase):
  844. """Simulates the Blink DEPS transition in Chrome."""
  845. NB_GIT_REPOS = 2
  846. DEPS_pre = 'deps = {"src/third_party/WebKit": "%(git_base)srepo_2",}'
  847. DEPS_post = 'deps = {}'
  848. def populateGit(self):
  849. # Blink repo.
  850. self._commit_git(
  851. 'repo_2', {
  852. 'OWNERS': 'OWNERS-pre',
  853. 'Source/exists_always': '_ignored_',
  854. 'Source/exists_before_but_not_after': '_ignored_',
  855. })
  856. # Chrome repo.
  857. self._commit_git(
  858. 'repo_1', {
  859. 'DEPS': self.DEPS_pre % {
  860. 'git_base': self.git_base
  861. },
  862. 'myfile': 'myfile@1',
  863. '.gitignore': '/third_party/WebKit',
  864. })
  865. self._commit_git(
  866. 'repo_1', {
  867. 'DEPS': self.DEPS_post % {
  868. 'git_base': self.git_base
  869. },
  870. 'myfile': 'myfile@2',
  871. '.gitignore': '',
  872. 'third_party/WebKit/OWNERS': 'OWNERS-post',
  873. 'third_party/WebKit/Source/exists_always': '_ignored_',
  874. 'third_party/WebKit/Source/exists_after_but_not_before':
  875. '_ignored',
  876. })
  877. def populateSvn(self):
  878. raise NotImplementedError()
  879. class FakeRepoNoSyncDEPS(FakeReposBase):
  880. """Simulates a repo with some DEPS changes."""
  881. NB_GIT_REPOS = 2
  882. def populateGit(self):
  883. self._commit_git('repo_2', {'myfile': 'then egg'})
  884. self._commit_git('repo_2', {'myfile': 'before egg!'})
  885. self._commit_git(
  886. 'repo_1', {
  887. 'DEPS':
  888. textwrap.dedent(
  889. """\
  890. deps = {
  891. 'src/repo2': {
  892. 'url': %(git_base)r + 'repo_2@%(repo2hash)s',
  893. },
  894. }""" % {
  895. 'git_base': self.git_base,
  896. 'repo2hash': self.git_hashes['repo_2'][1][0][:7]
  897. })
  898. })
  899. self._commit_git(
  900. 'repo_1', {
  901. 'DEPS':
  902. textwrap.dedent(
  903. """\
  904. deps = {
  905. 'src/repo2': {
  906. 'url': %(git_base)r + 'repo_2@%(repo2hash)s',
  907. },
  908. }""" % {
  909. 'git_base': self.git_base,
  910. 'repo2hash': self.git_hashes['repo_2'][2][0][:7]
  911. })
  912. })
  913. self._commit_git(
  914. 'repo_1', {
  915. 'foo_file':
  916. 'chicken content',
  917. 'DEPS':
  918. textwrap.dedent(
  919. """\
  920. deps = {
  921. 'src/repo2': {
  922. 'url': %(git_base)r + 'repo_2@%(repo2hash)s',
  923. },
  924. }""" % {
  925. 'git_base': self.git_base,
  926. 'repo2hash': self.git_hashes['repo_2'][1][0][:7]
  927. })
  928. })
  929. self._commit_git('repo_1', {'foo_file': 'chicken content@4'})
  930. class FakeReposTestBase(trial_dir.TestCase):
  931. """This is vaguely inspired by twisted."""
  932. # Static FakeRepos instances. Lazy loaded.
  933. CACHED_FAKE_REPOS = {}
  934. # Override if necessary.
  935. FAKE_REPOS_CLASS = FakeRepos
  936. def setUp(self):
  937. super(FakeReposTestBase, self).setUp()
  938. if not self.FAKE_REPOS_CLASS in self.CACHED_FAKE_REPOS:
  939. self.CACHED_FAKE_REPOS[
  940. self.FAKE_REPOS_CLASS] = self.FAKE_REPOS_CLASS()
  941. self.FAKE_REPOS = self.CACHED_FAKE_REPOS[self.FAKE_REPOS_CLASS]
  942. # No need to call self.FAKE_REPOS.setUp(), it will be called by the
  943. # child class. Do not define tearDown(), since super's version does the
  944. # right thing and self.FAKE_REPOS is kept across tests.
  945. @property
  946. def git_base(self):
  947. """Shortcut."""
  948. return self.FAKE_REPOS.git_base
  949. def checkString(self, expected, result, msg=None):
  950. """Prints the diffs to ease debugging."""
  951. self.assertEqual(expected.splitlines(), result.splitlines(), msg)
  952. if expected != result:
  953. # Strip the beginning
  954. while expected and result and expected[0] == result[0]:
  955. expected = expected[1:]
  956. result = result[1:]
  957. # The exception trace makes it hard to read so dump it too.
  958. if '\n' in result:
  959. print(result)
  960. self.assertEqual(expected, result, msg)
  961. def check(self, expected, results):
  962. """Checks stdout, stderr, returncode."""
  963. self.checkString(expected[0], results[0])
  964. self.checkString(expected[1], results[1])
  965. self.assertEqual(expected[2], results[2])
  966. def assertTree(self, tree, tree_root=None):
  967. """Diff the checkout tree with a dict."""
  968. if not tree_root:
  969. tree_root = self.root_dir
  970. actual = read_tree(tree_root)
  971. self.assertEqual(sorted(tree.keys()), sorted(actual.keys()))
  972. self.assertEqual(tree, actual)
  973. def mangle_git_tree(self, *args):
  974. """Creates a 'virtual directory snapshot' to compare with the actual
  975. result on disk."""
  976. result = {}
  977. for item, new_root in args:
  978. repo, rev = item.split('@', 1)
  979. tree = self.gittree(repo, rev)
  980. for k, v in tree.items():
  981. path = join(new_root, k).replace(os.sep, '/')
  982. result[path] = v
  983. return result
  984. def githash(self, repo, rev):
  985. """Sort-hand: Returns the hash for a git 'revision'."""
  986. return self.FAKE_REPOS.git_hashes[repo][int(rev)][0]
  987. def gittree(self, repo, rev):
  988. """Sort-hand: returns the directory tree for a git 'revision'."""
  989. return self.FAKE_REPOS.git_hashes[repo][int(rev)][1]
  990. def gitrevparse(self, repo):
  991. """Returns the actual revision for a given repo."""
  992. return self.FAKE_REPOS._git_rev_parse(repo).decode('utf-8')
  993. def main(argv):
  994. fake = FakeRepos()
  995. print('Using %s' % fake.root_dir)
  996. try:
  997. fake.set_up_git()
  998. print(
  999. 'Fake setup, press enter to quit or Ctrl-C to keep the checkouts.')
  1000. sys.stdin.readline()
  1001. except KeyboardInterrupt:
  1002. trial_dir.TrialDir.SHOULD_LEAK.leak = True
  1003. return 0
  1004. if __name__ == '__main__':
  1005. sys.exit(main(sys.argv))