gclient_scm_test.py 61 KB

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