gclient_scm_test.py 66 KB

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