gclient_scm_test.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2012 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. """Unit tests for gclient_scm.py."""
  6. # pylint: disable=E1103
  7. from io import StringIO
  8. import json
  9. import logging
  10. import os
  11. import re
  12. from subprocess import Popen, PIPE, STDOUT
  13. import sys
  14. import tempfile
  15. import unittest
  16. from unittest import mock
  17. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  18. import gclient_scm
  19. import gclient_utils
  20. import git_cache
  21. import subprocess2
  22. from testing_support import fake_repos
  23. from testing_support import test_case_utils
  24. # TODO: Should fix these warnings.
  25. # pylint: disable=line-too-long
  26. GIT = 'git' if sys.platform != 'win32' else 'git.bat'
  27. # Disable global git cache
  28. git_cache.Mirror.SetCachePath(None)
  29. # Shortcut since this function is used often
  30. join = gclient_scm.os.path.join
  31. TIMESTAMP_RE = re.compile(r'\[[0-9]{1,2}:[0-9]{2}:[0-9]{2}\] (.*)', re.DOTALL)
  32. def strip_timestamps(value):
  33. lines = value.splitlines(True)
  34. for i in range(len(lines)):
  35. m = TIMESTAMP_RE.match(lines[i])
  36. if m:
  37. lines[i] = m.group(1)
  38. return ''.join(lines)
  39. class BasicTests(unittest.TestCase):
  40. @mock.patch('gclient_scm.scm.GIT.Capture')
  41. def testGetFirstRemoteUrl(self, mockCapture):
  42. REMOTE_STRINGS = [
  43. ('remote.origin.url E:\\foo\\bar', 'E:\\foo\\bar'),
  44. ('remote.origin.url /b/foo/bar', '/b/foo/bar'),
  45. ('remote.origin.url https://foo/bar', 'https://foo/bar'),
  46. ('remote.origin.url E:\\Fo Bar\\bax', 'E:\\Fo Bar\\bax'),
  47. ('remote.origin.url git://what/"do', 'git://what/"do')
  48. ]
  49. FAKE_PATH = '/fake/path'
  50. mockCapture.side_effect = [question for question, _ in REMOTE_STRINGS]
  51. for _, answer in REMOTE_STRINGS:
  52. self.assertEqual(
  53. gclient_scm.SCMWrapper._get_first_remote_url(FAKE_PATH), answer)
  54. expected_calls = [
  55. mock.call(['config', '--local', '--get-regexp', r'remote.*.url'],
  56. cwd=FAKE_PATH) for _ in REMOTE_STRINGS
  57. ]
  58. self.assertEqual(mockCapture.mock_calls, expected_calls)
  59. class BaseGitWrapperTestCase(unittest.TestCase, test_case_utils.TestCaseUtils):
  60. """This class doesn't use pymox."""
  61. class OptionsObject(object):
  62. def __init__(self, verbose=False, revision=None):
  63. self.auto_rebase = False
  64. self.verbose = verbose
  65. self.revision = revision
  66. self.deps_os = None
  67. self.force = False
  68. self.reset = False
  69. self.nohooks = False
  70. self.no_history = False
  71. self.upstream = False
  72. self.cache_dir = None
  73. self.merge = False
  74. self.jobs = 1
  75. self.break_repo_locks = False
  76. self.delete_unversioned_trees = False
  77. self.patch_ref = None
  78. self.patch_repo = None
  79. self.rebase_patch_ref = True
  80. self.reset_patch_ref = True
  81. sample_git_import = """blob
  82. mark :1
  83. data 6
  84. Hello
  85. blob
  86. mark :2
  87. data 4
  88. Bye
  89. reset refs/heads/main
  90. commit refs/heads/main
  91. mark :3
  92. author Bob <bob@example.com> 1253744361 -0700
  93. committer Bob <bob@example.com> 1253744361 -0700
  94. data 8
  95. A and B
  96. M 100644 :1 a
  97. M 100644 :2 b
  98. blob
  99. mark :4
  100. data 10
  101. Hello
  102. You
  103. blob
  104. mark :5
  105. data 8
  106. Bye
  107. You
  108. commit refs/heads/origin
  109. mark :6
  110. author Alice <alice@example.com> 1253744424 -0700
  111. committer Alice <alice@example.com> 1253744424 -0700
  112. data 13
  113. Personalized
  114. from :3
  115. M 100644 :4 a
  116. M 100644 :5 b
  117. blob
  118. mark :7
  119. data 5
  120. Mooh
  121. commit refs/heads/feature
  122. mark :8
  123. author Bob <bob@example.com> 1390311986 -0000
  124. committer Bob <bob@example.com> 1390311986 -0000
  125. data 6
  126. Add C
  127. from :3
  128. M 100644 :7 c
  129. reset refs/heads/main
  130. from :3
  131. """
  132. def Options(self, *args, **kwargs):
  133. return self.OptionsObject(*args, **kwargs)
  134. def checkstdout(self, expected):
  135. # pylint: disable=no-member
  136. value = sys.stdout.getvalue()
  137. sys.stdout.close()
  138. # Check that the expected output appears.
  139. self.assertIn(expected, strip_timestamps(value))
  140. @staticmethod
  141. def CreateGitRepo(git_import, path):
  142. """Do it for real."""
  143. try:
  144. Popen([GIT, 'init', '-q'], stdout=PIPE, stderr=STDOUT,
  145. cwd=path).communicate()
  146. except OSError:
  147. # git is not available, skip this test.
  148. return False
  149. Popen([GIT, 'fast-import', '--quiet'],
  150. stdin=PIPE,
  151. stdout=PIPE,
  152. stderr=STDOUT,
  153. cwd=path).communicate(input=git_import.encode())
  154. Popen([GIT, 'checkout', '-q'], stdout=PIPE, stderr=STDOUT,
  155. cwd=path).communicate()
  156. Popen([GIT, 'remote', 'add', '-f', 'origin', '.'],
  157. stdout=PIPE,
  158. stderr=STDOUT,
  159. cwd=path).communicate()
  160. Popen([GIT, 'checkout', '-b', 'new', 'origin/main', '-q'],
  161. stdout=PIPE,
  162. stderr=STDOUT,
  163. cwd=path).communicate()
  164. Popen([GIT, 'push', 'origin', 'origin/origin:origin/main', '-q'],
  165. stdout=PIPE,
  166. stderr=STDOUT,
  167. cwd=path).communicate()
  168. Popen([GIT, 'config', '--unset', 'remote.origin.fetch'],
  169. stdout=PIPE,
  170. stderr=STDOUT,
  171. cwd=path).communicate()
  172. Popen([GIT, 'config', 'user.email', 'someuser@chromium.org'],
  173. stdout=PIPE,
  174. stderr=STDOUT,
  175. cwd=path).communicate()
  176. Popen([GIT, 'config', 'user.name', 'Some User'],
  177. stdout=PIPE,
  178. stderr=STDOUT,
  179. cwd=path).communicate()
  180. # Set HEAD back to main
  181. Popen([GIT, 'checkout', 'main', '-q'],
  182. stdout=PIPE,
  183. stderr=STDOUT,
  184. cwd=path).communicate()
  185. return True
  186. def _GetAskForDataCallback(self, expected_prompt, return_value):
  187. def AskForData(prompt, options):
  188. self.assertEqual(prompt, expected_prompt)
  189. return return_value
  190. return AskForData
  191. def setUp(self):
  192. unittest.TestCase.setUp(self)
  193. test_case_utils.TestCaseUtils.setUp(self)
  194. self.url = 'git://foo'
  195. # The .git suffix allows gclient_scm to recognize the dir as a git repo
  196. # when cloning it locally
  197. self.root_dir = tempfile.mkdtemp('.git')
  198. self.relpath = '.'
  199. self.base_path = join(self.root_dir, self.relpath)
  200. self.enabled = self.CreateGitRepo(self.sample_git_import,
  201. self.base_path)
  202. mock.patch('sys.stdout', StringIO()).start()
  203. self.addCleanup(mock.patch.stopall)
  204. self.addCleanup(gclient_utils.rmtree, self.root_dir)
  205. class ManagedGitWrapperTestCase(BaseGitWrapperTestCase):
  206. @mock.patch('gclient_scm.GitWrapper._IsCog')
  207. @mock.patch('gclient_scm.GitWrapper._Run', return_value=True)
  208. @mock.patch('gclient_scm.GitWrapper._SetFetchConfig')
  209. @mock.patch('gclient_scm.GitWrapper._GetCurrentBranch')
  210. def testCloneInCog(self, mockGetCurrentBranch, mockSetFetchConfig, mockRun,
  211. _mockIsCog):
  212. """Test that we call the correct commands when in a cog workspace."""
  213. if not self.enabled:
  214. return
  215. options = self.Options()
  216. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  217. scm._Clone('123123ab', self.url, options)
  218. mockRun.assert_called_once_with(
  219. ['citc', 'clone-repo', self.url, scm.checkout_path, '123123ab'],
  220. options,
  221. cwd=scm._root_dir,
  222. retry=True,
  223. print_stdout=False,
  224. filter_fn=scm.filter)
  225. mockSetFetchConfig.assert_called_once()
  226. mockGetCurrentBranch.assert_called_once()
  227. def testRevertMissing(self):
  228. if not self.enabled:
  229. return
  230. options = self.Options()
  231. file_path = join(self.base_path, 'a')
  232. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  233. file_list = []
  234. scm.update(options, None, file_list)
  235. gclient_scm.os.remove(file_path)
  236. file_list = []
  237. scm.revert(options, self.args, file_list)
  238. self.assertEqual(file_list, [file_path])
  239. file_list = []
  240. scm.diff(options, self.args, file_list)
  241. self.assertEqual(file_list, [])
  242. sys.stdout.close()
  243. def testRevertNone(self):
  244. if not self.enabled:
  245. return
  246. options = self.Options()
  247. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  248. file_list = []
  249. scm.update(options, None, file_list)
  250. file_list = []
  251. scm.revert(options, self.args, file_list)
  252. self.assertEqual(file_list, [])
  253. self.assertEqual(scm.revinfo(options, self.args, None),
  254. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  255. sys.stdout.close()
  256. def testRevertModified(self):
  257. if not self.enabled:
  258. return
  259. options = self.Options()
  260. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  261. file_list = []
  262. scm.update(options, None, file_list)
  263. file_path = join(self.base_path, 'a')
  264. with open(file_path, 'a') as f:
  265. f.writelines('touched\n')
  266. file_list = []
  267. scm.revert(options, self.args, file_list)
  268. self.assertEqual(file_list, [file_path])
  269. file_list = []
  270. scm.diff(options, self.args, file_list)
  271. self.assertEqual(file_list, [])
  272. self.assertEqual(scm.revinfo(options, self.args, None),
  273. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  274. sys.stdout.close()
  275. def testRevertNew(self):
  276. if not self.enabled:
  277. return
  278. options = self.Options()
  279. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  280. file_list = []
  281. scm.update(options, None, file_list)
  282. file_path = join(self.base_path, 'c')
  283. with open(file_path, 'w') as f:
  284. f.writelines('new\n')
  285. Popen([GIT, 'add', 'c'], stdout=PIPE, stderr=STDOUT,
  286. cwd=self.base_path).communicate()
  287. file_list = []
  288. scm.revert(options, self.args, file_list)
  289. self.assertEqual(file_list, [file_path])
  290. file_list = []
  291. scm.diff(options, self.args, file_list)
  292. self.assertEqual(file_list, [])
  293. self.assertEqual(scm.revinfo(options, self.args, None),
  294. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  295. sys.stdout.close()
  296. def testStatusRef(self):
  297. if not self.enabled:
  298. return
  299. options = self.Options()
  300. file_paths = [join(self.base_path, 'a')]
  301. with open(file_paths[0], 'a') as f:
  302. f.writelines('touched\n')
  303. scm = gclient_scm.GitWrapper(self.url + '@refs/heads/feature',
  304. self.root_dir, self.relpath)
  305. file_paths.append(join(self.base_path, 'c')) # feature branch touches c
  306. file_list = []
  307. scm.status(options, self.args, file_list)
  308. self.assertEqual(file_list, file_paths)
  309. self.checkstdout((
  310. '\n________ running \'git -c core.quotePath=false diff --name-status '
  311. 'refs/remotes/origin/feature\' in \'%s\'\n\nM\ta\n') %
  312. join(self.root_dir, '.'))
  313. def testStatusNew(self):
  314. if not self.enabled:
  315. return
  316. options = self.Options()
  317. file_path = join(self.base_path, 'a')
  318. with open(file_path, 'a') as f:
  319. f.writelines('touched\n')
  320. scm = gclient_scm.GitWrapper(
  321. self.url + '@069c602044c5388d2d15c3f875b057c852003458',
  322. self.root_dir, self.relpath)
  323. file_list = []
  324. scm.status(options, self.args, file_list)
  325. self.assertEqual(file_list, [file_path])
  326. self.checkstdout((
  327. '\n________ running \'git -c core.quotePath=false diff --name-status '
  328. '069c602044c5388d2d15c3f875b057c852003458\' in \'%s\'\n\nM\ta\n') %
  329. join(self.root_dir, '.'))
  330. def testStatusNewNoBaseRev(self):
  331. if not self.enabled:
  332. return
  333. options = self.Options()
  334. file_path = join(self.base_path, 'a')
  335. with open(file_path, 'a') as f:
  336. f.writelines('touched\n')
  337. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  338. file_list = []
  339. scm.status(options, self.args, file_list)
  340. self.assertEqual(file_list, [file_path])
  341. self.checkstdout((
  342. '\n________ running \'git -c core.quotePath=false diff --name-status'
  343. '\' in \'%s\'\n\nM\ta\n') % join(self.root_dir, '.'))
  344. def testStatus2New(self):
  345. if not self.enabled:
  346. return
  347. options = self.Options()
  348. expected_file_list = []
  349. for f in ['a', 'b']:
  350. file_path = join(self.base_path, f)
  351. with open(file_path, 'a') as f:
  352. f.writelines('touched\n')
  353. expected_file_list.extend([file_path])
  354. scm = gclient_scm.GitWrapper(
  355. self.url + '@069c602044c5388d2d15c3f875b057c852003458',
  356. self.root_dir, self.relpath)
  357. file_list = []
  358. scm.status(options, self.args, file_list)
  359. expected_file_list = [join(self.base_path, x) for x in ['a', 'b']]
  360. self.assertEqual(sorted(file_list), expected_file_list)
  361. self.checkstdout((
  362. '\n________ running \'git -c core.quotePath=false diff --name-status '
  363. '069c602044c5388d2d15c3f875b057c852003458\' in \'%s\'\n\nM\ta\nM\tb\n'
  364. ) % join(self.root_dir, '.'))
  365. def testUpdateUpdate(self):
  366. if not self.enabled:
  367. return
  368. options = self.Options()
  369. expected_file_list = [join(self.base_path, x) for x in ['a', 'b']]
  370. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  371. file_list = []
  372. scm.update(options, (), file_list)
  373. self.assertEqual(file_list, expected_file_list)
  374. self.assertEqual(scm.revinfo(options, (), None),
  375. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  376. self.assertEqual(
  377. scm._Capture(['config', '--get', 'diff.ignoreSubmodules']), 'dirty')
  378. self.assertEqual(
  379. scm._Capture(['config', '--get', 'fetch.recurseSubmodules']), 'off')
  380. self.assertEqual(
  381. scm._Capture(['config', '--get', 'push.recurseSubmodules']), 'off')
  382. sys.stdout.close()
  383. def testUpdateMerge(self):
  384. if not self.enabled:
  385. return
  386. options = self.Options()
  387. options.merge = True
  388. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  389. scm._Run(['checkout', '-q', 'feature'], options)
  390. rev = scm.revinfo(options, (), None)
  391. file_list = []
  392. scm.update(options, (), file_list)
  393. self.assertEqual(file_list,
  394. [join(self.base_path, x) for x in ['a', 'b', 'c']])
  395. # The actual commit that is created is unstable, so we verify its tree
  396. # and parents instead.
  397. self.assertEqual(scm._Capture(['rev-parse', 'HEAD:']),
  398. 'd2e35c10ac24d6c621e14a1fcadceb533155627d')
  399. parent = 'HEAD^' if sys.platform != 'win32' else 'HEAD^^'
  400. self.assertEqual(scm._Capture(['rev-parse', parent + '1']), rev)
  401. self.assertEqual(scm._Capture(['rev-parse', parent + '2']),
  402. scm._Capture(['rev-parse', 'origin/main']))
  403. sys.stdout.close()
  404. def testUpdateRebase(self):
  405. if not self.enabled:
  406. return
  407. options = self.Options()
  408. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  409. scm._Run(['checkout', '-q', 'feature'], options)
  410. file_list = []
  411. # Fake a 'y' key press.
  412. scm._AskForData = self._GetAskForDataCallback(
  413. 'Cannot fast-forward merge, attempt to rebase? '
  414. '(y)es / (q)uit / (s)kip : ', 'y')
  415. scm.update(options, (), file_list)
  416. self.assertEqual(file_list,
  417. [join(self.base_path, x) for x in ['a', 'b', 'c']])
  418. # The actual commit that is created is unstable, so we verify its tree
  419. # and parent instead.
  420. self.assertEqual(scm._Capture(['rev-parse', 'HEAD:']),
  421. 'd2e35c10ac24d6c621e14a1fcadceb533155627d')
  422. parent = 'HEAD^' if sys.platform != 'win32' else 'HEAD^^'
  423. self.assertEqual(scm._Capture(['rev-parse', parent + '1']),
  424. scm._Capture(['rev-parse', 'origin/main']))
  425. sys.stdout.close()
  426. def testUpdateReset(self):
  427. if not self.enabled:
  428. return
  429. options = self.Options()
  430. options.reset = True
  431. dir_path = join(self.base_path, 'c')
  432. os.mkdir(dir_path)
  433. with open(join(dir_path, 'nested'), 'w') as f:
  434. f.writelines('new\n')
  435. file_path = join(self.base_path, 'file')
  436. with open(file_path, 'w') as f:
  437. f.writelines('new\n')
  438. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  439. file_list = []
  440. scm.update(options, (), file_list)
  441. self.assert_(gclient_scm.os.path.isdir(dir_path))
  442. self.assert_(gclient_scm.os.path.isfile(file_path))
  443. sys.stdout.close()
  444. def testUpdateResetUnsetsFetchConfig(self):
  445. if not self.enabled:
  446. return
  447. options = self.Options()
  448. options.reset = True
  449. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  450. scm._Run([
  451. 'config', 'remote.origin.fetch',
  452. '+refs/heads/bad/ref:refs/remotes/origin/bad/ref'
  453. ], options)
  454. file_list = []
  455. scm.update(options, (), file_list)
  456. self.assertEqual(scm.revinfo(options, (), None),
  457. '069c602044c5388d2d15c3f875b057c852003458')
  458. sys.stdout.close()
  459. def testUpdateResetDeleteUnversionedTrees(self):
  460. if not self.enabled:
  461. return
  462. options = self.Options()
  463. options.reset = True
  464. options.delete_unversioned_trees = True
  465. dir_path = join(self.base_path, 'dir')
  466. os.mkdir(dir_path)
  467. with open(join(dir_path, 'nested'), 'w') as f:
  468. f.writelines('new\n')
  469. file_path = join(self.base_path, 'file')
  470. with open(file_path, 'w') as f:
  471. f.writelines('new\n')
  472. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  473. file_list = []
  474. scm.update(options, (), file_list)
  475. self.assert_(not gclient_scm.os.path.isdir(dir_path))
  476. self.assert_(gclient_scm.os.path.isfile(file_path))
  477. sys.stdout.close()
  478. def testUpdateUnstagedConflict(self):
  479. if not self.enabled:
  480. return
  481. options = self.Options()
  482. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  483. file_path = join(self.base_path, 'b')
  484. with open(file_path, 'w') as f:
  485. f.writelines('conflict\n')
  486. try:
  487. scm.update(options, (), [])
  488. self.fail()
  489. except (gclient_scm.gclient_utils.Error,
  490. subprocess2.CalledProcessError):
  491. # The exact exception text varies across git versions so it's not
  492. # worth verifying it. It's fine as long as it throws.
  493. pass
  494. # Manually flush stdout since we can't verify it's content accurately
  495. # across git versions.
  496. sys.stdout.getvalue()
  497. sys.stdout.close()
  498. @unittest.skip('Skipping until crbug.com/670884 is resolved.')
  499. def testUpdateLocked(self):
  500. if not self.enabled:
  501. return
  502. options = self.Options()
  503. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  504. file_path = join(self.base_path, '.git', 'index.lock')
  505. with open(file_path, 'w'):
  506. pass
  507. with self.assertRaises(subprocess2.CalledProcessError):
  508. scm.update(options, (), [])
  509. sys.stdout.close()
  510. def testUpdateLockedBreak(self):
  511. if not self.enabled:
  512. return
  513. options = self.Options()
  514. options.break_repo_locks = True
  515. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  516. file_path = join(self.base_path, '.git', 'index.lock')
  517. with open(file_path, 'w'):
  518. pass
  519. scm.update(options, (), [])
  520. self.assertRegexpMatches(sys.stdout.getvalue(),
  521. r'breaking lock.*\.git[/|\\]index\.lock')
  522. self.assertFalse(os.path.exists(file_path))
  523. sys.stdout.close()
  524. def testUpdateConflict(self):
  525. if not self.enabled:
  526. return
  527. options = self.Options()
  528. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  529. file_path = join(self.base_path, 'b')
  530. with open(file_path, 'w') as f:
  531. f.writelines('conflict\n')
  532. scm._Run(['commit', '-am', 'test'], options)
  533. scm._AskForData = self._GetAskForDataCallback(
  534. 'Cannot fast-forward merge, attempt to rebase? '
  535. '(y)es / (q)uit / (s)kip : ', 'y')
  536. with self.assertRaises(gclient_scm.gclient_utils.Error) as e:
  537. scm.update(options, (), [])
  538. self.assertEqual(
  539. e.exception.args[0], 'Conflict while rebasing this branch.\n'
  540. 'Fix the conflict and run gclient again.\n'
  541. 'See \'man git-rebase\' for details.\n')
  542. with self.assertRaises(gclient_scm.gclient_utils.Error) as e:
  543. scm.update(options, (), [])
  544. self.assertEqual(
  545. e.exception.args[0], '\n____ . at refs/remotes/origin/main\n'
  546. '\tYou have unstaged changes.\n'
  547. '\tcd into ., run git status to see changes,\n'
  548. '\tand commit, stash, or reset.\n')
  549. sys.stdout.close()
  550. def testRevinfo(self):
  551. if not self.enabled:
  552. return
  553. options = self.Options()
  554. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  555. rev_info = scm.revinfo(options, (), None)
  556. self.assertEqual(rev_info, '069c602044c5388d2d15c3f875b057c852003458')
  557. class ManagedGitWrapperTestCaseMock(unittest.TestCase):
  558. class OptionsObject(object):
  559. def __init__(self, verbose=False, revision=None, force=False):
  560. self.verbose = verbose
  561. self.revision = revision
  562. self.deps_os = None
  563. self.force = force
  564. self.reset = False
  565. self.nohooks = False
  566. self.break_repo_locks = False
  567. # TODO(maruel): Test --jobs > 1.
  568. self.jobs = 1
  569. self.patch_ref = None
  570. self.patch_repo = None
  571. self.rebase_patch_ref = True
  572. def Options(self, *args, **kwargs):
  573. return self.OptionsObject(*args, **kwargs)
  574. def checkstdout(self, expected):
  575. # pylint: disable=no-member
  576. value = sys.stdout.getvalue()
  577. sys.stdout.close()
  578. # Check that the expected output appears.
  579. self.assertIn(expected, strip_timestamps(value))
  580. def setUp(self):
  581. self.fake_hash_1 = 't0ta11yf4k3'
  582. self.fake_hash_2 = '3v3nf4k3r'
  583. self.url = 'git://foo'
  584. self.root_dir = '/tmp' if sys.platform != 'win32' else 't:\\tmp'
  585. self.relpath = 'fake'
  586. self.base_path = os.path.join(self.root_dir, self.relpath)
  587. self.backup_base_path = os.path.join(self.root_dir,
  588. 'old_%s.git' % self.relpath)
  589. mock.patch('gclient_scm.scm.GIT.ApplyEnvVars').start()
  590. mock.patch('gclient_scm.GitWrapper._CheckMinVersion').start()
  591. mock.patch('gclient_scm.GitWrapper._Fetch').start()
  592. mock.patch('gclient_scm.GitWrapper._DeleteOrMove').start()
  593. mock.patch('sys.stdout', StringIO()).start()
  594. self.addCleanup(mock.patch.stopall)
  595. @mock.patch('scm.GIT.IsValidRevision')
  596. @mock.patch('os.path.isdir', lambda _: True)
  597. def testGetUsableRevGit(self, mockIsValidRevision):
  598. # pylint: disable=no-member
  599. options = self.Options(verbose=True)
  600. mockIsValidRevision.side_effect = lambda cwd, rev: rev != '1'
  601. git_scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  602. # A [fake] git sha1 with a git repo should work (this is in the case
  603. # that the LKGR gets flipped to git sha1's some day).
  604. self.assertEqual(git_scm.GetUsableRev(self.fake_hash_1, options),
  605. self.fake_hash_1)
  606. # An SVN rev with an existing purely git repo should raise an exception.
  607. self.assertRaises(gclient_scm.gclient_utils.Error, git_scm.GetUsableRev,
  608. '1', options)
  609. @mock.patch('gclient_scm.GitWrapper._Clone')
  610. @mock.patch('os.path.isdir')
  611. @mock.patch('os.path.exists')
  612. @mock.patch('subprocess2.check_output')
  613. def testUpdateNoDotGit(self, mockCheckOutput, mockExists, mockIsdir,
  614. mockClone):
  615. mockIsdir.side_effect = lambda path: path == self.base_path
  616. mockExists.side_effect = lambda path: path == self.base_path
  617. mockCheckOutput.side_effect = [b'refs/remotes/origin/main', b'', b'']
  618. options = self.Options()
  619. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  620. scm.update(options, None, [])
  621. env = gclient_scm.scm.GIT.ApplyEnvVars({})
  622. self.assertEqual(mockCheckOutput.mock_calls, [
  623. mock.call(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD'],
  624. cwd=self.base_path,
  625. env=env,
  626. stderr=-1),
  627. mock.call(['git', '-c', 'core.quotePath=false', 'ls-files'],
  628. cwd=self.base_path,
  629. env=env,
  630. stderr=-1),
  631. mock.call(['git', 'rev-parse', '--verify', 'HEAD'],
  632. cwd=self.base_path,
  633. env=env,
  634. stderr=-1),
  635. ])
  636. mockClone.assert_called_with('refs/remotes/origin/main', self.url,
  637. options)
  638. self.checkstdout('\n')
  639. @mock.patch('gclient_scm.GitWrapper._Clone')
  640. @mock.patch('os.path.isdir')
  641. @mock.patch('os.path.exists')
  642. @mock.patch('subprocess2.check_output')
  643. def testUpdateConflict(self, mockCheckOutput, mockExists, mockIsdir,
  644. mockClone):
  645. mockIsdir.side_effect = lambda path: path == self.base_path
  646. mockExists.side_effect = lambda path: path == self.base_path
  647. mockCheckOutput.side_effect = [b'refs/remotes/origin/main', b'', b'']
  648. mockClone.side_effect = [
  649. gclient_scm.subprocess2.CalledProcessError(None, None, None, None,
  650. None),
  651. None,
  652. ]
  653. options = self.Options()
  654. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  655. scm.update(options, None, [])
  656. env = gclient_scm.scm.GIT.ApplyEnvVars({})
  657. self.assertEqual(mockCheckOutput.mock_calls, [
  658. mock.call(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD'],
  659. cwd=self.base_path,
  660. env=env,
  661. stderr=-1),
  662. mock.call(['git', '-c', 'core.quotePath=false', 'ls-files'],
  663. cwd=self.base_path,
  664. env=env,
  665. stderr=-1),
  666. mock.call(['git', 'rev-parse', '--verify', 'HEAD'],
  667. cwd=self.base_path,
  668. env=env,
  669. stderr=-1),
  670. ])
  671. mockClone.assert_called_with('refs/remotes/origin/main', self.url,
  672. options)
  673. self.checkstdout('\n')
  674. class UnmanagedGitWrapperTestCase(BaseGitWrapperTestCase):
  675. def checkInStdout(self, expected):
  676. # pylint: disable=no-member
  677. value = sys.stdout.getvalue()
  678. sys.stdout.close()
  679. self.assertIn(expected, value)
  680. def checkNotInStdout(self, expected):
  681. # pylint: disable=no-member
  682. value = sys.stdout.getvalue()
  683. sys.stdout.close()
  684. self.assertNotIn(expected, value)
  685. def getCurrentBranch(self):
  686. # Returns name of current branch or HEAD for detached HEAD
  687. branch = gclient_scm.scm.GIT.Capture(
  688. ['rev-parse', '--abbrev-ref', 'HEAD'], cwd=self.base_path)
  689. if branch == 'HEAD':
  690. return None
  691. return branch
  692. def testUpdateClone(self):
  693. if not self.enabled:
  694. return
  695. options = self.Options()
  696. origin_root_dir = self.root_dir
  697. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  698. self.root_dir = tempfile.mkdtemp()
  699. self.relpath = '.'
  700. self.base_path = join(self.root_dir, self.relpath)
  701. scm = gclient_scm.GitWrapper(origin_root_dir, self.root_dir,
  702. self.relpath)
  703. expected_file_list = [
  704. join(self.base_path, "a"),
  705. join(self.base_path, "b")
  706. ]
  707. file_list = []
  708. options.revision = 'unmanaged'
  709. scm.update(options, (), file_list)
  710. self.assertEqual(file_list, expected_file_list)
  711. self.assertEqual(scm.revinfo(options, (), None),
  712. '069c602044c5388d2d15c3f875b057c852003458')
  713. # indicates detached HEAD
  714. self.assertEqual(self.getCurrentBranch(), None)
  715. self.checkInStdout(
  716. 'Checked out refs/remotes/origin/main to a detached HEAD')
  717. def testUpdateCloneOnCommit(self):
  718. if not self.enabled:
  719. return
  720. options = self.Options()
  721. origin_root_dir = self.root_dir
  722. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  723. self.root_dir = tempfile.mkdtemp()
  724. self.relpath = '.'
  725. self.base_path = join(self.root_dir, self.relpath)
  726. url_with_commit_ref = origin_root_dir +\
  727. '@a7142dc9f0009350b96a11f372b6ea658592aa95'
  728. scm = gclient_scm.GitWrapper(url_with_commit_ref, self.root_dir,
  729. self.relpath)
  730. expected_file_list = [
  731. join(self.base_path, "a"),
  732. join(self.base_path, "b")
  733. ]
  734. file_list = []
  735. options.revision = 'unmanaged'
  736. scm.update(options, (), file_list)
  737. self.assertEqual(file_list, expected_file_list)
  738. self.assertEqual(scm.revinfo(options, (), None),
  739. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  740. # indicates detached HEAD
  741. self.assertEqual(self.getCurrentBranch(), None)
  742. self.checkInStdout(
  743. 'Checked out a7142dc9f0009350b96a11f372b6ea658592aa95 to a detached HEAD'
  744. )
  745. def testUpdateCloneOnBranch(self):
  746. if not self.enabled:
  747. return
  748. options = self.Options()
  749. origin_root_dir = self.root_dir
  750. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  751. self.root_dir = tempfile.mkdtemp()
  752. self.relpath = '.'
  753. self.base_path = join(self.root_dir, self.relpath)
  754. url_with_branch_ref = origin_root_dir + '@feature'
  755. scm = gclient_scm.GitWrapper(url_with_branch_ref, self.root_dir,
  756. self.relpath)
  757. expected_file_list = [
  758. join(self.base_path, "a"),
  759. join(self.base_path, "b"),
  760. join(self.base_path, "c")
  761. ]
  762. file_list = []
  763. options.revision = 'unmanaged'
  764. scm.update(options, (), file_list)
  765. self.assertEqual(file_list, expected_file_list)
  766. self.assertEqual(scm.revinfo(options, (), None),
  767. '9a51244740b25fa2ded5252ca00a3178d3f665a9')
  768. # indicates detached HEAD
  769. self.assertEqual(self.getCurrentBranch(), None)
  770. self.checkInStdout(
  771. 'Checked out 9a51244740b25fa2ded5252ca00a3178d3f665a9 '
  772. 'to a detached HEAD')
  773. def testUpdateCloneOnFetchedRemoteBranch(self):
  774. if not self.enabled:
  775. return
  776. options = self.Options()
  777. origin_root_dir = self.root_dir
  778. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  779. self.root_dir = tempfile.mkdtemp()
  780. self.relpath = '.'
  781. self.base_path = join(self.root_dir, self.relpath)
  782. url_with_branch_ref = origin_root_dir + '@refs/remotes/origin/feature'
  783. scm = gclient_scm.GitWrapper(url_with_branch_ref, self.root_dir,
  784. self.relpath)
  785. expected_file_list = [
  786. join(self.base_path, "a"),
  787. join(self.base_path, "b"),
  788. join(self.base_path, "c")
  789. ]
  790. file_list = []
  791. options.revision = 'unmanaged'
  792. scm.update(options, (), file_list)
  793. self.assertEqual(file_list, expected_file_list)
  794. self.assertEqual(scm.revinfo(options, (), None),
  795. '9a51244740b25fa2ded5252ca00a3178d3f665a9')
  796. # indicates detached HEAD
  797. self.assertEqual(self.getCurrentBranch(), None)
  798. self.checkInStdout(
  799. 'Checked out refs/remotes/origin/feature to a detached HEAD')
  800. def testUpdateCloneOnTrueRemoteBranch(self):
  801. if not self.enabled:
  802. return
  803. options = self.Options()
  804. origin_root_dir = self.root_dir
  805. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  806. self.root_dir = tempfile.mkdtemp()
  807. self.relpath = '.'
  808. self.base_path = join(self.root_dir, self.relpath)
  809. url_with_branch_ref = origin_root_dir + '@refs/heads/feature'
  810. scm = gclient_scm.GitWrapper(url_with_branch_ref, self.root_dir,
  811. self.relpath)
  812. expected_file_list = [
  813. join(self.base_path, "a"),
  814. join(self.base_path, "b"),
  815. join(self.base_path, "c")
  816. ]
  817. file_list = []
  818. options.revision = 'unmanaged'
  819. scm.update(options, (), file_list)
  820. self.assertEqual(file_list, expected_file_list)
  821. self.assertEqual(scm.revinfo(options, (), None),
  822. '9a51244740b25fa2ded5252ca00a3178d3f665a9')
  823. # @refs/heads/feature is AKA @refs/remotes/origin/feature in the clone,
  824. # so should be treated as such by gclient. TODO(mmoss): Though really,
  825. # we should only allow DEPS to specify branches as they are known in the
  826. # upstream repo, since the mapping into the local repo can be modified
  827. # by users (or we might even want to change the gclient defaults at some
  828. # point). But that will take more work to stop using refs/remotes/
  829. # everywhere that we do (and to stop assuming a DEPS ref will always
  830. # resolve locally, like when passing them to show-ref or rev-list).
  831. self.assertEqual(self.getCurrentBranch(), None)
  832. self.checkInStdout(
  833. 'Checked out refs/remotes/origin/feature to a detached HEAD')
  834. def testUpdateUpdate(self):
  835. if not self.enabled:
  836. return
  837. options = self.Options()
  838. expected_file_list = []
  839. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  840. file_list = []
  841. options.revision = 'unmanaged'
  842. scm.update(options, (), file_list)
  843. self.assertEqual(file_list, expected_file_list)
  844. self.assertEqual(scm.revinfo(options, (), None),
  845. '069c602044c5388d2d15c3f875b057c852003458')
  846. self.checkstdout('________ unmanaged solution; skipping .\n')
  847. class CipdWrapperTestCase(unittest.TestCase):
  848. def setUp(self):
  849. # Create this before setting up mocks.
  850. self._cipd_root_dir = tempfile.mkdtemp()
  851. self._workdir = tempfile.mkdtemp()
  852. self._cipd_instance_url = 'https://chrome-infra-packages.appspot.com'
  853. self._cipd_root = gclient_scm.CipdRoot(self._cipd_root_dir,
  854. self._cipd_instance_url)
  855. self._cipd_packages = [
  856. self._cipd_root.add_package('f', 'foo_package', 'foo_version'),
  857. self._cipd_root.add_package('b', 'bar_package', 'bar_version'),
  858. self._cipd_root.add_package('b', 'baz_package', 'baz_version'),
  859. ]
  860. mock.patch('tempfile.mkdtemp', lambda: self._workdir).start()
  861. mock.patch('gclient_scm.CipdRoot.add_package').start()
  862. mock.patch('gclient_scm.CipdRoot.clobber').start()
  863. mock.patch('gclient_scm.CipdRoot.ensure_file_resolve').start()
  864. mock.patch('gclient_scm.CipdRoot.ensure').start()
  865. self.addCleanup(mock.patch.stopall)
  866. self.addCleanup(gclient_utils.rmtree, self._cipd_root_dir)
  867. self.addCleanup(gclient_utils.rmtree, self._workdir)
  868. def createScmWithPackageThatSatisfies(self, condition):
  869. return gclient_scm.CipdWrapper(
  870. url=self._cipd_instance_url,
  871. root_dir=self._cipd_root_dir,
  872. relpath='fake_relpath',
  873. root=self._cipd_root,
  874. package=self.getPackageThatSatisfies(condition))
  875. def getPackageThatSatisfies(self, condition):
  876. for p in self._cipd_packages:
  877. if condition(p):
  878. return p
  879. self.fail('Unable to find a satisfactory package.')
  880. def testRevert(self):
  881. """Checks that revert does nothing."""
  882. scm = self.createScmWithPackageThatSatisfies(lambda _: True)
  883. scm.revert(None, (), [])
  884. @mock.patch('gclient_scm.gclient_utils.CheckCallAndFilter')
  885. @mock.patch('gclient_scm.gclient_utils.rmtree')
  886. def testRevinfo(self, mockRmtree, mockCheckCallAndFilter):
  887. """Checks that revinfo uses the JSON from cipd describe."""
  888. scm = self.createScmWithPackageThatSatisfies(lambda _: True)
  889. expected_revinfo = '0123456789abcdef0123456789abcdef01234567'
  890. json_contents = {
  891. 'result': {
  892. 'pin': {
  893. 'instance_id': expected_revinfo,
  894. }
  895. }
  896. }
  897. describe_json_path = join(self._workdir, 'describe.json')
  898. with open(describe_json_path, 'w') as describe_json:
  899. json.dump(json_contents, describe_json)
  900. revinfo = scm.revinfo(None, (), [])
  901. self.assertEqual(revinfo, expected_revinfo)
  902. mockRmtree.assert_called_with(self._workdir)
  903. mockCheckCallAndFilter.assert_called_with([
  904. 'cipd',
  905. 'describe',
  906. 'foo_package',
  907. '-log-level',
  908. 'error',
  909. '-version',
  910. 'foo_version',
  911. '-json-output',
  912. describe_json_path,
  913. ])
  914. def testUpdate(self):
  915. """Checks that update does nothing."""
  916. scm = self.createScmWithPackageThatSatisfies(lambda _: True)
  917. scm.update(None, (), [])
  918. class BranchHeadsFakeRepo(fake_repos.FakeReposBase):
  919. def populateGit(self):
  920. # Creates a tree that looks like this:
  921. #
  922. # 5 refs/branch-heads/5
  923. # |
  924. # 4
  925. # |
  926. # 1--2--3 refs/heads/main
  927. self._commit_git('repo_1', {'commit 1': 'touched'})
  928. self._commit_git('repo_1', {'commit 2': 'touched'})
  929. self._commit_git('repo_1', {'commit 3': 'touched'})
  930. self._create_ref('repo_1', 'refs/heads/main', 3)
  931. self._commit_git('repo_1', {'commit 4': 'touched'}, base=2)
  932. self._commit_git('repo_1', {'commit 5': 'touched'}, base=2)
  933. self._create_ref('repo_1', 'refs/branch-heads/5', 5)
  934. class BranchHeadsTest(fake_repos.FakeReposTestBase):
  935. FAKE_REPOS_CLASS = BranchHeadsFakeRepo
  936. def setUp(self):
  937. super(BranchHeadsTest, self).setUp()
  938. self.enabled = self.FAKE_REPOS.set_up_git()
  939. self.options = BaseGitWrapperTestCase.OptionsObject()
  940. self.url = self.git_base + 'repo_1'
  941. self.mirror = None
  942. mock.patch('sys.stdout', StringIO()).start()
  943. self.addCleanup(mock.patch.stopall)
  944. def setUpMirror(self):
  945. self.mirror = tempfile.mkdtemp('mirror')
  946. git_cache.Mirror.SetCachePath(self.mirror)
  947. self.addCleanup(gclient_utils.rmtree, self.mirror)
  948. self.addCleanup(git_cache.Mirror.SetCachePath, None)
  949. def testCheckoutBranchHeads(self):
  950. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  951. file_list = []
  952. self.options.revision = 'refs/branch-heads/5'
  953. scm.update(self.options, None, file_list)
  954. self.assertEqual(self.githash('repo_1', 5),
  955. self.gitrevparse(self.root_dir))
  956. def testCheckoutUpdatedBranchHeads(self):
  957. # Travel back in time, and set refs/branch-heads/5 to its parent.
  958. subprocess2.check_call([
  959. 'git', 'update-ref', 'refs/branch-heads/5',
  960. self.githash('repo_1', 4)
  961. ],
  962. cwd=self.url)
  963. # Sync to refs/branch-heads/5
  964. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  965. self.options.revision = 'refs/branch-heads/5'
  966. scm.update(self.options, None, [])
  967. # Set refs/branch-heads/5 back to its original value.
  968. subprocess2.check_call([
  969. 'git', 'update-ref', 'refs/branch-heads/5',
  970. self.githash('repo_1', 5)
  971. ],
  972. cwd=self.url)
  973. # Attempt to sync to refs/branch-heads/5 again.
  974. self.testCheckoutBranchHeads()
  975. def testCheckoutBranchHeadsMirror(self):
  976. self.setUpMirror()
  977. self.testCheckoutBranchHeads()
  978. def testCheckoutUpdatedBranchHeadsMirror(self):
  979. self.setUpMirror()
  980. self.testCheckoutUpdatedBranchHeads()
  981. class GerritChangesFakeRepo(fake_repos.FakeReposBase):
  982. def populateGit(self):
  983. # Creates a tree that looks like this:
  984. #
  985. # 6 refs/changes/35/1235/1
  986. # |
  987. # 5 refs/changes/34/1234/1
  988. # |
  989. # 1--2--3--4 refs/heads/main
  990. # | |
  991. # | 11(5)--12 refs/heads/main-with-5
  992. # |
  993. # 7--8--9 refs/heads/feature
  994. # |
  995. # 10 refs/changes/36/1236/1
  996. #
  997. self._commit_git('repo_1', {'commit 1': 'touched'})
  998. self._commit_git('repo_1', {'commit 2': 'touched'})
  999. self._commit_git('repo_1', {'commit 3': 'touched'})
  1000. self._commit_git('repo_1', {'commit 4': 'touched'})
  1001. self._create_ref('repo_1', 'refs/heads/main', 4)
  1002. # Create a change on top of commit 3 that consists of two commits.
  1003. self._commit_git('repo_1', {
  1004. 'commit 5': 'touched',
  1005. 'change': '1234'
  1006. },
  1007. base=3)
  1008. self._create_ref('repo_1', 'refs/changes/34/1234/1', 5)
  1009. self._commit_git('repo_1', {'commit 6': 'touched', 'change': '1235'})
  1010. self._create_ref('repo_1', 'refs/changes/35/1235/1', 6)
  1011. # Create a refs/heads/feature branch on top of commit 2, consisting of
  1012. # three commits.
  1013. self._commit_git('repo_1', {'commit 7': 'touched'}, base=2)
  1014. self._commit_git('repo_1', {'commit 8': 'touched'})
  1015. self._commit_git('repo_1', {'commit 9': 'touched'})
  1016. self._create_ref('repo_1', 'refs/heads/feature', 9)
  1017. # Create a change of top of commit 8.
  1018. self._commit_git('repo_1', {
  1019. 'commit 10': 'touched',
  1020. 'change': '1236'
  1021. },
  1022. base=8)
  1023. self._create_ref('repo_1', 'refs/changes/36/1236/1', 10)
  1024. # Create a refs/heads/main-with-5 on top of commit 3 which is a branch
  1025. # where refs/changes/34/1234/1 (commit 5) has already landed as commit
  1026. # 11.
  1027. self._commit_git(
  1028. 'repo_1',
  1029. # This is really commit 11, but has the changes of commit 5
  1030. {
  1031. 'commit 5': 'touched',
  1032. 'change': '1234'
  1033. },
  1034. base=3)
  1035. self._commit_git('repo_1', {'commit 12': 'touched'})
  1036. self._create_ref('repo_1', 'refs/heads/main-with-5', 12)
  1037. class GerritChangesTest(fake_repos.FakeReposTestBase):
  1038. FAKE_REPOS_CLASS = GerritChangesFakeRepo
  1039. def setUp(self):
  1040. super(GerritChangesTest, self).setUp()
  1041. self.enabled = self.FAKE_REPOS.set_up_git()
  1042. self.options = BaseGitWrapperTestCase.OptionsObject()
  1043. self.url = self.git_base + 'repo_1'
  1044. self.mirror = None
  1045. mock.patch('sys.stdout', StringIO()).start()
  1046. self.addCleanup(mock.patch.stopall)
  1047. def setUpMirror(self):
  1048. self.mirror = tempfile.mkdtemp()
  1049. git_cache.Mirror.SetCachePath(self.mirror)
  1050. self.addCleanup(gclient_utils.rmtree, self.mirror)
  1051. self.addCleanup(git_cache.Mirror.SetCachePath, None)
  1052. def assertCommits(self, commits):
  1053. """Check that all, and only |commits| are present in the current checkout.
  1054. """
  1055. for i in commits:
  1056. name = os.path.join(self.root_dir, 'commit ' + str(i))
  1057. self.assertTrue(os.path.exists(name), 'Commit not found: %s' % name)
  1058. all_commits = set(range(1, len(self.FAKE_REPOS.git_hashes['repo_1'])))
  1059. for i in all_commits - set(commits):
  1060. name = os.path.join(self.root_dir, 'commit ' + str(i))
  1061. self.assertFalse(os.path.exists(name),
  1062. 'Unexpected commit: %s' % name)
  1063. def testCanCloneGerritChange(self):
  1064. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1065. file_list = []
  1066. self.options.revision = 'refs/changes/35/1235/1'
  1067. scm.update(self.options, None, file_list)
  1068. self.assertEqual(self.githash('repo_1', 6),
  1069. self.gitrevparse(self.root_dir))
  1070. def testCanSyncToGerritChange(self):
  1071. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1072. file_list = []
  1073. self.options.revision = self.githash('repo_1', 1)
  1074. scm.update(self.options, None, file_list)
  1075. self.assertEqual(self.githash('repo_1', 1),
  1076. self.gitrevparse(self.root_dir))
  1077. self.options.revision = 'refs/changes/35/1235/1'
  1078. scm.update(self.options, None, file_list)
  1079. self.assertEqual(self.githash('repo_1', 6),
  1080. self.gitrevparse(self.root_dir))
  1081. def testCanCloneGerritChangeMirror(self):
  1082. self.setUpMirror()
  1083. self.testCanCloneGerritChange()
  1084. def testCanSyncToGerritChangeMirror(self):
  1085. self.setUpMirror()
  1086. self.testCanSyncToGerritChange()
  1087. def testMirrorPushUrl(self):
  1088. self.setUpMirror()
  1089. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1090. file_list = []
  1091. self.assertIsNotNone(scm._GetMirror(self.url, self.options))
  1092. scm.update(self.options, None, file_list)
  1093. fetch_url = scm._Capture(['remote', 'get-url', 'origin'])
  1094. self.assertTrue(
  1095. fetch_url.startswith(self.mirror),
  1096. msg='\n'.join([
  1097. 'Repository fetch url should be in the git cache mirror directory.',
  1098. ' fetch_url: %s' % fetch_url,
  1099. ' mirror: %s' % self.mirror
  1100. ]))
  1101. push_url = scm._Capture(['remote', 'get-url', '--push', 'origin'])
  1102. self.assertEqual(push_url, self.url)
  1103. def testAppliesPatchOnTopOfMasterByDefault(self):
  1104. """Test the default case, where we apply a patch on top of main."""
  1105. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1106. file_list = []
  1107. # Make sure we don't specify a revision.
  1108. self.options.revision = None
  1109. scm.update(self.options, None, file_list)
  1110. self.assertEqual(self.githash('repo_1', 4),
  1111. self.gitrevparse(self.root_dir))
  1112. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1113. 'refs/heads/main', self.options, file_list)
  1114. self.assertCommits([1, 2, 3, 4, 5, 6])
  1115. self.assertEqual(self.githash('repo_1', 4),
  1116. self.gitrevparse(self.root_dir))
  1117. def testCheckoutOlderThanPatchBase(self):
  1118. """Test applying a patch on an old checkout.
  1119. We first checkout commit 1, and try to patch refs/changes/35/1235/1, which
  1120. contains commits 5 and 6, and is based on top of commit 3.
  1121. The final result should contain commits 1, 5 and 6, but not commits 2 or 3.
  1122. """
  1123. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1124. file_list = []
  1125. # Sync to commit 1
  1126. self.options.revision = self.githash('repo_1', 1)
  1127. scm.update(self.options, None, file_list)
  1128. self.assertEqual(self.githash('repo_1', 1),
  1129. self.gitrevparse(self.root_dir))
  1130. # Apply the change on top of that.
  1131. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1132. 'refs/heads/main', self.options, file_list)
  1133. self.assertCommits([1, 5, 6])
  1134. self.assertEqual(self.githash('repo_1', 1),
  1135. self.gitrevparse(self.root_dir))
  1136. def testCheckoutOriginFeature(self):
  1137. """Tests that we can apply a patch on a branch other than main."""
  1138. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1139. file_list = []
  1140. # Sync to remote's refs/heads/feature
  1141. self.options.revision = 'refs/heads/feature'
  1142. scm.update(self.options, None, file_list)
  1143. self.assertEqual(self.githash('repo_1', 9),
  1144. self.gitrevparse(self.root_dir))
  1145. # Apply the change on top of that.
  1146. scm.apply_patch_ref(self.url, 'refs/changes/36/1236/1',
  1147. 'refs/heads/feature', self.options, file_list)
  1148. self.assertCommits([1, 2, 7, 8, 9, 10])
  1149. self.assertEqual(self.githash('repo_1', 9),
  1150. self.gitrevparse(self.root_dir))
  1151. def testCheckoutOriginFeatureOnOldRevision(self):
  1152. """Tests that we can apply a patch on an old checkout, on a branch other
  1153. than main."""
  1154. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1155. file_list = []
  1156. # Sync to remote's refs/heads/feature on an old revision
  1157. self.options.revision = self.githash('repo_1', 7)
  1158. scm.update(self.options, None, file_list)
  1159. self.assertEqual(self.githash('repo_1', 7),
  1160. self.gitrevparse(self.root_dir))
  1161. # Apply the change on top of that.
  1162. scm.apply_patch_ref(self.url, 'refs/changes/36/1236/1',
  1163. 'refs/heads/feature', self.options, file_list)
  1164. # We shouldn't have rebased on top of 2 (which is the merge base between
  1165. # remote's main branch and the change) but on top of 7 (which is the
  1166. # merge base between remote's feature branch and the change).
  1167. self.assertCommits([1, 2, 7, 10])
  1168. self.assertEqual(self.githash('repo_1', 7),
  1169. self.gitrevparse(self.root_dir))
  1170. def testCheckoutOriginFeaturePatchBranch(self):
  1171. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1172. file_list = []
  1173. # Sync to the hash instead of remote's refs/heads/feature.
  1174. self.options.revision = self.githash('repo_1', 9)
  1175. scm.update(self.options, None, file_list)
  1176. self.assertEqual(self.githash('repo_1', 9),
  1177. self.gitrevparse(self.root_dir))
  1178. # Apply refs/changes/34/1234/1, created for remote's main branch on top
  1179. # of remote's feature branch.
  1180. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1181. 'refs/heads/main', self.options, file_list)
  1182. # Commits 5 and 6 are part of the patch, and commits 1, 2, 7, 8 and 9
  1183. # are part of remote's feature branch.
  1184. self.assertCommits([1, 2, 5, 6, 7, 8, 9])
  1185. self.assertEqual(self.githash('repo_1', 9),
  1186. self.gitrevparse(self.root_dir))
  1187. def testDoesntRebasePatchMaster(self):
  1188. """Tests that we can apply a patch without rebasing it.
  1189. """
  1190. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1191. file_list = []
  1192. self.options.rebase_patch_ref = False
  1193. scm.update(self.options, None, file_list)
  1194. self.assertEqual(self.githash('repo_1', 4),
  1195. self.gitrevparse(self.root_dir))
  1196. # Apply the change on top of that.
  1197. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1198. 'refs/heads/main', self.options, file_list)
  1199. self.assertCommits([1, 2, 3, 5, 6])
  1200. self.assertEqual(self.githash('repo_1', 5),
  1201. self.gitrevparse(self.root_dir))
  1202. def testDoesntRebasePatchOldCheckout(self):
  1203. """Tests that we can apply a patch without rebasing it on an old checkout.
  1204. """
  1205. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1206. file_list = []
  1207. # Sync to commit 1
  1208. self.options.revision = self.githash('repo_1', 1)
  1209. self.options.rebase_patch_ref = False
  1210. scm.update(self.options, None, file_list)
  1211. self.assertEqual(self.githash('repo_1', 1),
  1212. self.gitrevparse(self.root_dir))
  1213. # Apply the change on top of that.
  1214. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1215. 'refs/heads/main', self.options, file_list)
  1216. self.assertCommits([1, 2, 3, 5, 6])
  1217. self.assertEqual(self.githash('repo_1', 5),
  1218. self.gitrevparse(self.root_dir))
  1219. def testDoesntSoftResetIfNotAskedTo(self):
  1220. """Test that we can apply a patch without doing a soft reset."""
  1221. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1222. file_list = []
  1223. self.options.reset_patch_ref = False
  1224. scm.update(self.options, None, file_list)
  1225. self.assertEqual(self.githash('repo_1', 4),
  1226. self.gitrevparse(self.root_dir))
  1227. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1228. 'refs/heads/main', self.options, file_list)
  1229. self.assertCommits([1, 2, 3, 4, 5, 6])
  1230. # The commit hash after cherry-picking is not known, but it must be
  1231. # different from what the repo was synced at before patching.
  1232. self.assertNotEqual(self.githash('repo_1', 4),
  1233. self.gitrevparse(self.root_dir))
  1234. @mock.patch('gerrit_util.GetChange', return_value={'topic': 'test_topic'})
  1235. @mock.patch('gerrit_util.QueryChanges',
  1236. return_value=[{
  1237. '_number': 1234
  1238. }, {
  1239. '_number': 1235,
  1240. 'current_revision': 'abc',
  1241. 'revisions': {
  1242. 'abc': {
  1243. 'ref': 'refs/changes/35/1235/1'
  1244. }
  1245. }
  1246. }])
  1247. def testDownloadTopics(self, query_changes_mock, get_change_mock):
  1248. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1249. file_list = []
  1250. self.options.revision = 'refs/changes/34/1234/1'
  1251. scm.update(self.options, None, file_list)
  1252. self.assertEqual(self.githash('repo_1', 5),
  1253. self.gitrevparse(self.root_dir))
  1254. # pylint: disable=attribute-defined-outside-init
  1255. self.options.download_topics = True
  1256. scm.url = 'https://test-repo.googlesource.com/repo_1.git'
  1257. scm.apply_patch_ref(self.url, 'refs/changes/34/1234/1',
  1258. 'refs/heads/main', self.options, file_list)
  1259. get_change_mock.assert_called_once_with(mock.ANY, '1234')
  1260. query_changes_mock.assert_called_once_with(mock.ANY,
  1261. [('topic', 'test_topic'),
  1262. ('status', 'open'),
  1263. ('repo', 'repo_1')],
  1264. o_params=['ALL_REVISIONS'])
  1265. self.assertCommits([1, 2, 3, 5, 6])
  1266. # The commit hash after the two cherry-picks is not known, but it must
  1267. # be different from what the repo was synced at before patching.
  1268. self.assertNotEqual(self.githash('repo_1', 4),
  1269. self.gitrevparse(self.root_dir))
  1270. def testRecoversAfterPatchFailure(self):
  1271. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1272. file_list = []
  1273. self.options.revision = 'refs/changes/34/1234/1'
  1274. scm.update(self.options, None, file_list)
  1275. self.assertEqual(self.githash('repo_1', 5),
  1276. self.gitrevparse(self.root_dir))
  1277. # Checkout 'refs/changes/34/1234/1' modifies the 'change' file, so
  1278. # trying to patch 'refs/changes/36/1236/1' creates a patch failure.
  1279. with self.assertRaises(subprocess2.CalledProcessError) as cm:
  1280. scm.apply_patch_ref(self.url, 'refs/changes/36/1236/1',
  1281. 'refs/heads/main', self.options, file_list)
  1282. self.assertEqual(cm.exception.cmd[:2], ['git', 'cherry-pick'])
  1283. self.assertIn(b'error: could not apply', cm.exception.stderr)
  1284. # Try to apply 'refs/changes/35/1235/1', which doesn't have a merge
  1285. # conflict.
  1286. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1287. 'refs/heads/main', self.options, file_list)
  1288. self.assertCommits([1, 2, 3, 5, 6])
  1289. self.assertEqual(self.githash('repo_1', 5),
  1290. self.gitrevparse(self.root_dir))
  1291. def testIgnoresAlreadyMergedCommits(self):
  1292. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1293. file_list = []
  1294. self.options.revision = 'refs/heads/main-with-5'
  1295. scm.update(self.options, None, file_list)
  1296. self.assertEqual(self.githash('repo_1', 12),
  1297. self.gitrevparse(self.root_dir))
  1298. # When we try 'refs/changes/35/1235/1' on top of 'refs/heads/feature',
  1299. # 'refs/changes/34/1234/1' will be an empty commit, since the changes
  1300. # were already present in the tree as commit 11. Make sure we deal with
  1301. # this gracefully.
  1302. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1303. 'refs/heads/feature', self.options, file_list)
  1304. self.assertCommits([1, 2, 3, 5, 6, 12])
  1305. self.assertEqual(self.githash('repo_1', 12),
  1306. self.gitrevparse(self.root_dir))
  1307. def testRecoversFromExistingCherryPick(self):
  1308. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1309. file_list = []
  1310. self.options.revision = 'refs/changes/34/1234/1'
  1311. scm.update(self.options, None, file_list)
  1312. self.assertEqual(self.githash('repo_1', 5),
  1313. self.gitrevparse(self.root_dir))
  1314. # Checkout 'refs/changes/34/1234/1' modifies the 'change' file, so
  1315. # trying to cherry-pick 'refs/changes/36/1236/1' raises an error.
  1316. scm._Run(['fetch', 'origin', 'refs/changes/36/1236/1'], self.options)
  1317. with self.assertRaises(subprocess2.CalledProcessError) as cm:
  1318. scm._Run(['cherry-pick', 'FETCH_HEAD'], self.options)
  1319. self.assertEqual(cm.exception.cmd[:2], ['git', 'cherry-pick'])
  1320. # Try to apply 'refs/changes/35/1235/1', which doesn't have a merge
  1321. # conflict.
  1322. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1323. 'refs/heads/main', self.options, file_list)
  1324. self.assertCommits([1, 2, 3, 5, 6])
  1325. self.assertEqual(self.githash('repo_1', 5),
  1326. self.gitrevparse(self.root_dir))
  1327. class DepsChangesFakeRepo(fake_repos.FakeReposBase):
  1328. def populateGit(self):
  1329. self._commit_git('repo_1', {'DEPS': 'versionA', 'doesnotmatter': 'B'})
  1330. self._commit_git('repo_1', {'DEPS': 'versionA', 'doesnotmatter': 'C'})
  1331. self._commit_git('repo_1', {'DEPS': 'versionB'})
  1332. self._commit_git('repo_1', {'DEPS': 'versionA', 'doesnotmatter': 'C'})
  1333. self._create_ref('repo_1', 'refs/heads/main', 4)
  1334. class CheckDiffTest(fake_repos.FakeReposTestBase):
  1335. FAKE_REPOS_CLASS = DepsChangesFakeRepo
  1336. def setUp(self):
  1337. super(CheckDiffTest, self).setUp()
  1338. self.enabled = self.FAKE_REPOS.set_up_git()
  1339. self.options = BaseGitWrapperTestCase.OptionsObject()
  1340. self.url = self.git_base + 'repo_1'
  1341. self.mirror = None
  1342. mock.patch('sys.stdout', StringIO()).start()
  1343. self.addCleanup(mock.patch.stopall)
  1344. def setUpMirror(self):
  1345. self.mirror = tempfile.mkdtemp()
  1346. git_cache.Mirror.SetCachePath(self.mirror)
  1347. self.addCleanup(gclient_utils.rmtree, self.mirror)
  1348. self.addCleanup(git_cache.Mirror.SetCachePath, None)
  1349. def testCheckDiff(self):
  1350. """Correctly check for diffs."""
  1351. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1352. file_list = []
  1353. # Make sure we don't specify a revision.
  1354. self.options.revision = None
  1355. scm.update(self.options, None, file_list)
  1356. self.assertEqual(self.githash('repo_1', 4),
  1357. self.gitrevparse(self.root_dir))
  1358. self.assertFalse(
  1359. scm.check_diff(self.githash('repo_1', 1), files=['DEPS']))
  1360. self.assertTrue(scm.check_diff(self.githash('repo_1', 1)))
  1361. self.assertTrue(
  1362. scm.check_diff(self.githash('repo_1', 3), files=['DEPS']))
  1363. self.assertFalse(
  1364. scm.check_diff(self.githash('repo_1', 2),
  1365. files=['DEPS', 'doesnotmatter']))
  1366. self.assertFalse(scm.check_diff(self.githash('repo_1', 2)))
  1367. if 'unittest.util' in __import__('sys').modules:
  1368. # Show full diff in self.assertEqual.
  1369. __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
  1370. if __name__ == '__main__':
  1371. level = logging.DEBUG if '-v' in sys.argv else logging.FATAL
  1372. logging.basicConfig(level=level,
  1373. format='%(asctime).19s %(levelname)s %(filename)s:'
  1374. '%(lineno)s %(message)s')
  1375. unittest.main()
  1376. # vim: ts=2:sw=2:tw=80:et: