test_repository.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. # -*- coding: utf-8 -*-
  2. # test_repository.py -- tests for repository.py
  3. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for the repository."""
  22. import glob
  23. import locale
  24. import os
  25. import shutil
  26. import stat
  27. import sys
  28. import tempfile
  29. import warnings
  30. from dulwich import errors
  31. from dulwich import porcelain
  32. from dulwich.object_store import (
  33. tree_lookup_path,
  34. )
  35. from dulwich import objects
  36. from dulwich.config import Config
  37. from dulwich.errors import NotGitRepository
  38. from dulwich.repo import (
  39. InvalidUserIdentity,
  40. Repo,
  41. MemoryRepo,
  42. check_user_identity,
  43. UnsupportedVersion,
  44. UnsupportedExtension,
  45. )
  46. from dulwich.tests import (
  47. TestCase,
  48. skipIf,
  49. )
  50. from dulwich.tests.utils import (
  51. open_repo,
  52. tear_down_repo,
  53. setup_warning_catcher,
  54. )
  55. missing_sha = b"b91fa4d900e17e99b433218e988c4eb4a3e9a097"
  56. class CreateRepositoryTests(TestCase):
  57. def assertFileContentsEqual(self, expected, repo, path):
  58. f = repo.get_named_file(path)
  59. if not f:
  60. self.assertEqual(expected, None)
  61. else:
  62. with f:
  63. self.assertEqual(expected, f.read())
  64. def _check_repo_contents(self, repo, expect_bare):
  65. self.assertEqual(expect_bare, repo.bare)
  66. self.assertFileContentsEqual(b"Unnamed repository", repo, "description")
  67. self.assertFileContentsEqual(b"", repo, os.path.join("info", "exclude"))
  68. self.assertFileContentsEqual(None, repo, "nonexistent file")
  69. barestr = b"bare = " + str(expect_bare).lower().encode("ascii")
  70. with repo.get_named_file("config") as f:
  71. config_text = f.read()
  72. self.assertIn(barestr, config_text, "%r" % config_text)
  73. expect_filemode = sys.platform != "win32"
  74. barestr = b"filemode = " + str(expect_filemode).lower().encode("ascii")
  75. with repo.get_named_file("config") as f:
  76. config_text = f.read()
  77. self.assertIn(barestr, config_text, "%r" % config_text)
  78. if isinstance(repo, Repo):
  79. expected_mode = '0o100644' if expect_filemode else '0o100666'
  80. expected = {
  81. 'HEAD': expected_mode,
  82. 'config': expected_mode,
  83. 'description': expected_mode,
  84. }
  85. actual = {
  86. f[len(repo._controldir) + 1:]: oct(os.stat(f).st_mode)
  87. for f in glob.glob(os.path.join(repo._controldir, '*'))
  88. if os.path.isfile(f)
  89. }
  90. self.assertEqual(expected, actual)
  91. def test_create_memory(self):
  92. repo = MemoryRepo.init_bare([], {})
  93. self._check_repo_contents(repo, True)
  94. def test_create_disk_bare(self):
  95. tmp_dir = tempfile.mkdtemp()
  96. self.addCleanup(shutil.rmtree, tmp_dir)
  97. repo = Repo.init_bare(tmp_dir)
  98. self.assertEqual(tmp_dir, repo._controldir)
  99. self._check_repo_contents(repo, True)
  100. def test_create_disk_non_bare(self):
  101. tmp_dir = tempfile.mkdtemp()
  102. self.addCleanup(shutil.rmtree, tmp_dir)
  103. repo = Repo.init(tmp_dir)
  104. self.assertEqual(os.path.join(tmp_dir, ".git"), repo._controldir)
  105. self._check_repo_contents(repo, False)
  106. def test_create_disk_non_bare_mkdir(self):
  107. tmp_dir = tempfile.mkdtemp()
  108. target_dir = os.path.join(tmp_dir, "target")
  109. self.addCleanup(shutil.rmtree, tmp_dir)
  110. repo = Repo.init(target_dir, mkdir=True)
  111. self.assertEqual(os.path.join(target_dir, ".git"), repo._controldir)
  112. self._check_repo_contents(repo, False)
  113. def test_create_disk_bare_mkdir(self):
  114. tmp_dir = tempfile.mkdtemp()
  115. target_dir = os.path.join(tmp_dir, "target")
  116. self.addCleanup(shutil.rmtree, tmp_dir)
  117. repo = Repo.init_bare(target_dir, mkdir=True)
  118. self.assertEqual(target_dir, repo._controldir)
  119. self._check_repo_contents(repo, True)
  120. class MemoryRepoTests(TestCase):
  121. def test_set_description(self):
  122. r = MemoryRepo.init_bare([], {})
  123. description = b"Some description"
  124. r.set_description(description)
  125. self.assertEqual(description, r.get_description())
  126. class RepositoryRootTests(TestCase):
  127. def mkdtemp(self):
  128. return tempfile.mkdtemp()
  129. def open_repo(self, name):
  130. temp_dir = self.mkdtemp()
  131. repo = open_repo(name, temp_dir)
  132. self.addCleanup(tear_down_repo, repo)
  133. return repo
  134. def test_simple_props(self):
  135. r = self.open_repo("a.git")
  136. self.assertEqual(r.controldir(), r.path)
  137. def test_setitem(self):
  138. r = self.open_repo("a.git")
  139. r[b"refs/tags/foo"] = b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"
  140. self.assertEqual(
  141. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", r[b"refs/tags/foo"].id
  142. )
  143. def test_getitem_unicode(self):
  144. r = self.open_repo("a.git")
  145. test_keys = [
  146. (b"refs/heads/master", True),
  147. (b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", True),
  148. (b"11" * 19 + b"--", False),
  149. ]
  150. for k, contained in test_keys:
  151. self.assertEqual(k in r, contained)
  152. # Avoid deprecation warning under Py3.2+
  153. if getattr(self, "assertRaisesRegex", None):
  154. assertRaisesRegexp = self.assertRaisesRegex
  155. else:
  156. assertRaisesRegexp = self.assertRaisesRegexp
  157. for k, _ in test_keys:
  158. assertRaisesRegexp(
  159. TypeError,
  160. "'name' must be bytestring, not int",
  161. r.__getitem__,
  162. 12,
  163. )
  164. def test_delitem(self):
  165. r = self.open_repo("a.git")
  166. del r[b"refs/heads/master"]
  167. self.assertRaises(KeyError, lambda: r[b"refs/heads/master"])
  168. del r[b"HEAD"]
  169. self.assertRaises(KeyError, lambda: r[b"HEAD"])
  170. self.assertRaises(ValueError, r.__delitem__, b"notrefs/foo")
  171. def test_get_refs(self):
  172. r = self.open_repo("a.git")
  173. self.assertEqual(
  174. {
  175. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  176. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  177. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  178. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  179. },
  180. r.get_refs(),
  181. )
  182. def test_head(self):
  183. r = self.open_repo("a.git")
  184. self.assertEqual(r.head(), b"a90fa2d900a17e99b433217e988c4eb4a2e9a097")
  185. def test_get_object(self):
  186. r = self.open_repo("a.git")
  187. obj = r.get_object(r.head())
  188. self.assertEqual(obj.type_name, b"commit")
  189. def test_get_object_non_existant(self):
  190. r = self.open_repo("a.git")
  191. self.assertRaises(KeyError, r.get_object, missing_sha)
  192. def test_contains_object(self):
  193. r = self.open_repo("a.git")
  194. self.assertIn(r.head(), r)
  195. self.assertNotIn(b"z" * 40, r)
  196. def test_contains_ref(self):
  197. r = self.open_repo("a.git")
  198. self.assertIn(b"HEAD", r)
  199. def test_get_no_description(self):
  200. r = self.open_repo("a.git")
  201. self.assertIs(None, r.get_description())
  202. def test_get_description(self):
  203. r = self.open_repo("a.git")
  204. with open(os.path.join(r.path, "description"), "wb") as f:
  205. f.write(b"Some description")
  206. self.assertEqual(b"Some description", r.get_description())
  207. def test_set_description(self):
  208. r = self.open_repo("a.git")
  209. description = b"Some description"
  210. r.set_description(description)
  211. self.assertEqual(description, r.get_description())
  212. def test_contains_missing(self):
  213. r = self.open_repo("a.git")
  214. self.assertNotIn(b"bar", r)
  215. def test_get_peeled(self):
  216. # unpacked ref
  217. r = self.open_repo("a.git")
  218. tag_sha = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a"
  219. self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head())
  220. self.assertEqual(r.get_peeled(b"refs/tags/mytag"), r.head())
  221. # packed ref with cached peeled value
  222. packed_tag_sha = b"b0931cadc54336e78a1d980420e3268903b57a50"
  223. parent_sha = r[r.head()].parents[0]
  224. self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha)
  225. self.assertEqual(r.get_peeled(b"refs/tags/mytag-packed"), parent_sha)
  226. # TODO: add more corner cases to test repo
  227. def test_get_peeled_not_tag(self):
  228. r = self.open_repo("a.git")
  229. self.assertEqual(r.get_peeled(b"HEAD"), r.head())
  230. def test_get_parents(self):
  231. r = self.open_repo("a.git")
  232. self.assertEqual(
  233. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  234. r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"),
  235. )
  236. r.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None)
  237. self.assertEqual([], r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"))
  238. def test_get_walker(self):
  239. r = self.open_repo("a.git")
  240. # include defaults to [r.head()]
  241. self.assertEqual(
  242. [e.commit.id for e in r.get_walker()],
  243. [r.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  244. )
  245. self.assertEqual(
  246. [
  247. e.commit.id
  248. for e in r.get_walker([b"2a72d929692c41d8554c07f6301757ba18a65d91"])
  249. ],
  250. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  251. )
  252. self.assertEqual(
  253. [
  254. e.commit.id
  255. for e in r.get_walker(b"2a72d929692c41d8554c07f6301757ba18a65d91")
  256. ],
  257. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  258. )
  259. def assertFilesystemHidden(self, path):
  260. if sys.platform != "win32":
  261. return
  262. import ctypes
  263. from ctypes.wintypes import DWORD, LPCWSTR
  264. GetFileAttributesW = ctypes.WINFUNCTYPE(DWORD, LPCWSTR)(
  265. ("GetFileAttributesW", ctypes.windll.kernel32)
  266. )
  267. self.assertTrue(2 & GetFileAttributesW(path))
  268. def test_init_existing(self):
  269. tmp_dir = self.mkdtemp()
  270. self.addCleanup(shutil.rmtree, tmp_dir)
  271. t = Repo.init(tmp_dir)
  272. self.addCleanup(t.close)
  273. self.assertEqual(os.listdir(tmp_dir), [".git"])
  274. self.assertFilesystemHidden(os.path.join(tmp_dir, ".git"))
  275. def test_init_mkdir(self):
  276. tmp_dir = self.mkdtemp()
  277. self.addCleanup(shutil.rmtree, tmp_dir)
  278. repo_dir = os.path.join(tmp_dir, "a-repo")
  279. t = Repo.init(repo_dir, mkdir=True)
  280. self.addCleanup(t.close)
  281. self.assertEqual(os.listdir(repo_dir), [".git"])
  282. self.assertFilesystemHidden(os.path.join(repo_dir, ".git"))
  283. def test_init_mkdir_unicode(self):
  284. repo_name = u"\xa7"
  285. try:
  286. os.fsencode(repo_name)
  287. except UnicodeEncodeError:
  288. self.skipTest("filesystem lacks unicode support")
  289. tmp_dir = self.mkdtemp()
  290. self.addCleanup(shutil.rmtree, tmp_dir)
  291. repo_dir = os.path.join(tmp_dir, repo_name)
  292. t = Repo.init(repo_dir, mkdir=True)
  293. self.addCleanup(t.close)
  294. self.assertEqual(os.listdir(repo_dir), [".git"])
  295. self.assertFilesystemHidden(os.path.join(repo_dir, ".git"))
  296. @skipIf(sys.platform == "win32", "fails on Windows")
  297. def test_fetch(self):
  298. r = self.open_repo("a.git")
  299. tmp_dir = self.mkdtemp()
  300. self.addCleanup(shutil.rmtree, tmp_dir)
  301. t = Repo.init(tmp_dir)
  302. self.addCleanup(t.close)
  303. r.fetch(t)
  304. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  305. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  306. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  307. self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t)
  308. self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t)
  309. @skipIf(sys.platform == "win32", "fails on Windows")
  310. def test_fetch_ignores_missing_refs(self):
  311. r = self.open_repo("a.git")
  312. missing = b"1234566789123456789123567891234657373833"
  313. r.refs[b"refs/heads/blah"] = missing
  314. tmp_dir = self.mkdtemp()
  315. self.addCleanup(shutil.rmtree, tmp_dir)
  316. t = Repo.init(tmp_dir)
  317. self.addCleanup(t.close)
  318. r.fetch(t)
  319. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  320. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  321. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  322. self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t)
  323. self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t)
  324. self.assertNotIn(missing, t)
  325. def test_clone(self):
  326. r = self.open_repo("a.git")
  327. tmp_dir = self.mkdtemp()
  328. self.addCleanup(shutil.rmtree, tmp_dir)
  329. with r.clone(tmp_dir, mkdir=False) as t:
  330. self.assertEqual(
  331. {
  332. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  333. b"refs/remotes/origin/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  334. b"refs/remotes/origin/HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  335. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  336. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  337. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  338. },
  339. t.refs.as_dict(),
  340. )
  341. shas = [e.commit.id for e in r.get_walker()]
  342. self.assertEqual(
  343. shas, [t.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"]
  344. )
  345. c = t.get_config()
  346. encoded_path = r.path
  347. if not isinstance(encoded_path, bytes):
  348. encoded_path = os.fsencode(encoded_path)
  349. self.assertEqual(encoded_path, c.get((b"remote", b"origin"), b"url"))
  350. self.assertEqual(
  351. b"+refs/heads/*:refs/remotes/origin/*",
  352. c.get((b"remote", b"origin"), b"fetch"),
  353. )
  354. def test_clone_no_head(self):
  355. temp_dir = self.mkdtemp()
  356. self.addCleanup(shutil.rmtree, temp_dir)
  357. repo_dir = os.path.join(os.path.dirname(__file__), "..", "..", "testdata", "repos")
  358. dest_dir = os.path.join(temp_dir, "a.git")
  359. shutil.copytree(os.path.join(repo_dir, "a.git"), dest_dir, symlinks=True)
  360. r = Repo(dest_dir)
  361. del r.refs[b"refs/heads/master"]
  362. del r.refs[b"HEAD"]
  363. t = r.clone(os.path.join(temp_dir, "b.git"), mkdir=True)
  364. self.assertEqual(
  365. {
  366. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  367. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  368. },
  369. t.refs.as_dict(),
  370. )
  371. def test_clone_empty(self):
  372. """Test clone() doesn't crash if HEAD points to a non-existing ref.
  373. This simulates cloning server-side bare repository either when it is
  374. still empty or if user renames master branch and pushes private repo
  375. to the server.
  376. Non-bare repo HEAD always points to an existing ref.
  377. """
  378. r = self.open_repo("empty.git")
  379. tmp_dir = self.mkdtemp()
  380. self.addCleanup(shutil.rmtree, tmp_dir)
  381. r.clone(tmp_dir, mkdir=False, bare=True)
  382. def test_clone_bare(self):
  383. r = self.open_repo("a.git")
  384. tmp_dir = self.mkdtemp()
  385. self.addCleanup(shutil.rmtree, tmp_dir)
  386. t = r.clone(tmp_dir, mkdir=False)
  387. t.close()
  388. def test_clone_checkout_and_bare(self):
  389. r = self.open_repo("a.git")
  390. tmp_dir = self.mkdtemp()
  391. self.addCleanup(shutil.rmtree, tmp_dir)
  392. self.assertRaises(
  393. ValueError, r.clone, tmp_dir, mkdir=False, checkout=True, bare=True
  394. )
  395. def test_clone_branch(self):
  396. r = self.open_repo("a.git")
  397. r.refs[b"refs/heads/mybranch"] = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a"
  398. tmp_dir = self.mkdtemp()
  399. self.addCleanup(shutil.rmtree, tmp_dir)
  400. with r.clone(tmp_dir, mkdir=False, branch=b"mybranch") as t:
  401. # HEAD should point to specified branch and not origin HEAD
  402. chain, sha = t.refs.follow(b"HEAD")
  403. self.assertEqual(chain[-1], b"refs/heads/mybranch")
  404. self.assertEqual(sha, b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a")
  405. self.assertEqual(
  406. t.refs[b"refs/remotes/origin/HEAD"],
  407. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  408. )
  409. def test_clone_tag(self):
  410. r = self.open_repo("a.git")
  411. tmp_dir = self.mkdtemp()
  412. self.addCleanup(shutil.rmtree, tmp_dir)
  413. with r.clone(tmp_dir, mkdir=False, branch=b"mytag") as t:
  414. # HEAD should be detached (and not a symbolic ref) at tag
  415. self.assertEqual(
  416. t.refs.read_ref(b"HEAD"),
  417. b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  418. )
  419. self.assertEqual(
  420. t.refs[b"refs/remotes/origin/HEAD"],
  421. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  422. )
  423. def test_clone_invalid_branch(self):
  424. r = self.open_repo("a.git")
  425. tmp_dir = self.mkdtemp()
  426. self.addCleanup(shutil.rmtree, tmp_dir)
  427. self.assertRaises(
  428. ValueError,
  429. r.clone,
  430. tmp_dir,
  431. mkdir=False,
  432. branch=b"mybranch",
  433. )
  434. def test_merge_history(self):
  435. r = self.open_repo("simple_merge.git")
  436. shas = [e.commit.id for e in r.get_walker()]
  437. self.assertEqual(
  438. shas,
  439. [
  440. b"5dac377bdded4c9aeb8dff595f0faeebcc8498cc",
  441. b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd",
  442. b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6",
  443. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  444. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  445. ],
  446. )
  447. def test_out_of_order_merge(self):
  448. """Test that revision history is ordered by date, not parent order."""
  449. r = self.open_repo("ooo_merge.git")
  450. shas = [e.commit.id for e in r.get_walker()]
  451. self.assertEqual(
  452. shas,
  453. [
  454. b"7601d7f6231db6a57f7bbb79ee52e4d462fd44d1",
  455. b"f507291b64138b875c28e03469025b1ea20bc614",
  456. b"fb5b0425c7ce46959bec94d54b9a157645e114f5",
  457. b"f9e39b120c68182a4ba35349f832d0e4e61f485c",
  458. ],
  459. )
  460. def test_get_tags_empty(self):
  461. r = self.open_repo("ooo_merge.git")
  462. self.assertEqual({}, r.refs.as_dict(b"refs/tags"))
  463. def test_get_config(self):
  464. r = self.open_repo("ooo_merge.git")
  465. self.assertIsInstance(r.get_config(), Config)
  466. def test_get_config_stack(self):
  467. r = self.open_repo("ooo_merge.git")
  468. self.assertIsInstance(r.get_config_stack(), Config)
  469. def test_common_revisions(self):
  470. """
  471. This test demonstrates that ``find_common_revisions()`` actually
  472. returns common heads, not revisions; dulwich already uses
  473. ``find_common_revisions()`` in such a manner (see
  474. ``Repo.fetch_objects()``).
  475. """
  476. expected_shas = set([b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e"])
  477. # Source for objects.
  478. r_base = self.open_repo("simple_merge.git")
  479. # Re-create each-side of the merge in simple_merge.git.
  480. #
  481. # Since the trees and blobs are missing, the repository created is
  482. # corrupted, but we're only checking for commits for the purpose of
  483. # this test, so it's immaterial.
  484. r1_dir = self.mkdtemp()
  485. self.addCleanup(shutil.rmtree, r1_dir)
  486. r1_commits = [
  487. b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", # HEAD
  488. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  489. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  490. ]
  491. r2_dir = self.mkdtemp()
  492. self.addCleanup(shutil.rmtree, r2_dir)
  493. r2_commits = [
  494. b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", # HEAD
  495. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  496. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  497. ]
  498. r1 = Repo.init_bare(r1_dir)
  499. for c in r1_commits:
  500. r1.object_store.add_object(r_base.get_object(c))
  501. r1.refs[b"HEAD"] = r1_commits[0]
  502. r2 = Repo.init_bare(r2_dir)
  503. for c in r2_commits:
  504. r2.object_store.add_object(r_base.get_object(c))
  505. r2.refs[b"HEAD"] = r2_commits[0]
  506. # Finally, the 'real' testing!
  507. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  508. self.assertEqual(set(shas), expected_shas)
  509. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  510. self.assertEqual(set(shas), expected_shas)
  511. def test_shell_hook_pre_commit(self):
  512. if os.name != "posix":
  513. self.skipTest("shell hook tests requires POSIX shell")
  514. pre_commit_fail = """#!/bin/sh
  515. exit 1
  516. """
  517. pre_commit_success = """#!/bin/sh
  518. exit 0
  519. """
  520. repo_dir = os.path.join(self.mkdtemp())
  521. self.addCleanup(shutil.rmtree, repo_dir)
  522. r = Repo.init(repo_dir)
  523. self.addCleanup(r.close)
  524. pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit")
  525. with open(pre_commit, "w") as f:
  526. f.write(pre_commit_fail)
  527. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  528. self.assertRaises(
  529. errors.CommitError,
  530. r.do_commit,
  531. b"failed commit",
  532. committer=b"Test Committer <test@nodomain.com>",
  533. author=b"Test Author <test@nodomain.com>",
  534. commit_timestamp=12345,
  535. commit_timezone=0,
  536. author_timestamp=12345,
  537. author_timezone=0,
  538. )
  539. with open(pre_commit, "w") as f:
  540. f.write(pre_commit_success)
  541. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  542. commit_sha = r.do_commit(
  543. b"empty commit",
  544. committer=b"Test Committer <test@nodomain.com>",
  545. author=b"Test Author <test@nodomain.com>",
  546. commit_timestamp=12395,
  547. commit_timezone=0,
  548. author_timestamp=12395,
  549. author_timezone=0,
  550. )
  551. self.assertEqual([], r[commit_sha].parents)
  552. def test_shell_hook_commit_msg(self):
  553. if os.name != "posix":
  554. self.skipTest("shell hook tests requires POSIX shell")
  555. commit_msg_fail = """#!/bin/sh
  556. exit 1
  557. """
  558. commit_msg_success = """#!/bin/sh
  559. exit 0
  560. """
  561. repo_dir = self.mkdtemp()
  562. self.addCleanup(shutil.rmtree, repo_dir)
  563. r = Repo.init(repo_dir)
  564. self.addCleanup(r.close)
  565. commit_msg = os.path.join(r.controldir(), "hooks", "commit-msg")
  566. with open(commit_msg, "w") as f:
  567. f.write(commit_msg_fail)
  568. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  569. self.assertRaises(
  570. errors.CommitError,
  571. r.do_commit,
  572. b"failed commit",
  573. committer=b"Test Committer <test@nodomain.com>",
  574. author=b"Test Author <test@nodomain.com>",
  575. commit_timestamp=12345,
  576. commit_timezone=0,
  577. author_timestamp=12345,
  578. author_timezone=0,
  579. )
  580. with open(commit_msg, "w") as f:
  581. f.write(commit_msg_success)
  582. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  583. commit_sha = r.do_commit(
  584. b"empty commit",
  585. committer=b"Test Committer <test@nodomain.com>",
  586. author=b"Test Author <test@nodomain.com>",
  587. commit_timestamp=12395,
  588. commit_timezone=0,
  589. author_timestamp=12395,
  590. author_timezone=0,
  591. )
  592. self.assertEqual([], r[commit_sha].parents)
  593. def test_shell_hook_pre_commit_add_files(self):
  594. if os.name != "posix":
  595. self.skipTest("shell hook tests requires POSIX shell")
  596. pre_commit_contents = """#!%(executable)s
  597. import sys
  598. sys.path.extend(%(path)r)
  599. from dulwich.repo import Repo
  600. with open('foo', 'w') as f:
  601. f.write('newfile')
  602. r = Repo('.')
  603. r.stage(['foo'])
  604. """ % {
  605. 'executable': sys.executable,
  606. 'path': [os.path.join(os.path.dirname(__file__), '..', '..')] + sys.path}
  607. repo_dir = os.path.join(self.mkdtemp())
  608. self.addCleanup(shutil.rmtree, repo_dir)
  609. r = Repo.init(repo_dir)
  610. self.addCleanup(r.close)
  611. with open(os.path.join(repo_dir, 'blah'), 'w') as f:
  612. f.write('blah')
  613. r.stage(['blah'])
  614. pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit")
  615. with open(pre_commit, "w") as f:
  616. f.write(pre_commit_contents)
  617. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  618. commit_sha = r.do_commit(
  619. b"new commit",
  620. committer=b"Test Committer <test@nodomain.com>",
  621. author=b"Test Author <test@nodomain.com>",
  622. commit_timestamp=12395,
  623. commit_timezone=0,
  624. author_timestamp=12395,
  625. author_timezone=0,
  626. )
  627. self.assertEqual([], r[commit_sha].parents)
  628. tree = r[r[commit_sha].tree]
  629. self.assertEqual(set([b'blah', b'foo']), set(tree))
  630. def test_shell_hook_post_commit(self):
  631. if os.name != "posix":
  632. self.skipTest("shell hook tests requires POSIX shell")
  633. repo_dir = self.mkdtemp()
  634. self.addCleanup(shutil.rmtree, repo_dir)
  635. r = Repo.init(repo_dir)
  636. self.addCleanup(r.close)
  637. (fd, path) = tempfile.mkstemp(dir=repo_dir)
  638. os.close(fd)
  639. post_commit_msg = (
  640. """#!/bin/sh
  641. rm """
  642. + path
  643. + """
  644. """
  645. )
  646. root_sha = r.do_commit(
  647. b"empty commit",
  648. committer=b"Test Committer <test@nodomain.com>",
  649. author=b"Test Author <test@nodomain.com>",
  650. commit_timestamp=12345,
  651. commit_timezone=0,
  652. author_timestamp=12345,
  653. author_timezone=0,
  654. )
  655. self.assertEqual([], r[root_sha].parents)
  656. post_commit = os.path.join(r.controldir(), "hooks", "post-commit")
  657. with open(post_commit, "wb") as f:
  658. f.write(post_commit_msg.encode(locale.getpreferredencoding()))
  659. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  660. commit_sha = r.do_commit(
  661. b"empty commit",
  662. committer=b"Test Committer <test@nodomain.com>",
  663. author=b"Test Author <test@nodomain.com>",
  664. commit_timestamp=12345,
  665. commit_timezone=0,
  666. author_timestamp=12345,
  667. author_timezone=0,
  668. )
  669. self.assertEqual([root_sha], r[commit_sha].parents)
  670. self.assertFalse(os.path.exists(path))
  671. post_commit_msg_fail = """#!/bin/sh
  672. exit 1
  673. """
  674. with open(post_commit, "w") as f:
  675. f.write(post_commit_msg_fail)
  676. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  677. warnings.simplefilter("always", UserWarning)
  678. self.addCleanup(warnings.resetwarnings)
  679. warnings_list, restore_warnings = setup_warning_catcher()
  680. self.addCleanup(restore_warnings)
  681. commit_sha2 = r.do_commit(
  682. b"empty commit",
  683. committer=b"Test Committer <test@nodomain.com>",
  684. author=b"Test Author <test@nodomain.com>",
  685. commit_timestamp=12345,
  686. commit_timezone=0,
  687. author_timestamp=12345,
  688. author_timezone=0,
  689. )
  690. expected_warning = UserWarning(
  691. "post-commit hook failed: Hook post-commit exited with "
  692. "non-zero status 1",
  693. )
  694. for w in warnings_list:
  695. if type(w) == type(expected_warning) and w.args == expected_warning.args:
  696. break
  697. else:
  698. raise AssertionError(
  699. "Expected warning %r not in %r" % (expected_warning, warnings_list)
  700. )
  701. self.assertEqual([commit_sha], r[commit_sha2].parents)
  702. def test_as_dict(self):
  703. def check(repo):
  704. self.assertEqual(
  705. repo.refs.subkeys(b"refs/tags"),
  706. repo.refs.subkeys(b"refs/tags/"),
  707. )
  708. self.assertEqual(
  709. repo.refs.as_dict(b"refs/tags"),
  710. repo.refs.as_dict(b"refs/tags/"),
  711. )
  712. self.assertEqual(
  713. repo.refs.as_dict(b"refs/heads"),
  714. repo.refs.as_dict(b"refs/heads/"),
  715. )
  716. bare = self.open_repo("a.git")
  717. tmp_dir = self.mkdtemp()
  718. self.addCleanup(shutil.rmtree, tmp_dir)
  719. with bare.clone(tmp_dir, mkdir=False) as nonbare:
  720. check(nonbare)
  721. check(bare)
  722. def test_working_tree(self):
  723. temp_dir = tempfile.mkdtemp()
  724. self.addCleanup(shutil.rmtree, temp_dir)
  725. worktree_temp_dir = tempfile.mkdtemp()
  726. self.addCleanup(shutil.rmtree, worktree_temp_dir)
  727. r = Repo.init(temp_dir)
  728. self.addCleanup(r.close)
  729. root_sha = r.do_commit(
  730. b"empty commit",
  731. committer=b"Test Committer <test@nodomain.com>",
  732. author=b"Test Author <test@nodomain.com>",
  733. commit_timestamp=12345,
  734. commit_timezone=0,
  735. author_timestamp=12345,
  736. author_timezone=0,
  737. )
  738. r.refs[b"refs/heads/master"] = root_sha
  739. w = Repo._init_new_working_directory(worktree_temp_dir, r)
  740. self.addCleanup(w.close)
  741. new_sha = w.do_commit(
  742. b"new commit",
  743. committer=b"Test Committer <test@nodomain.com>",
  744. author=b"Test Author <test@nodomain.com>",
  745. commit_timestamp=12345,
  746. commit_timezone=0,
  747. author_timestamp=12345,
  748. author_timezone=0,
  749. )
  750. w.refs[b"HEAD"] = new_sha
  751. self.assertEqual(
  752. os.path.abspath(r.controldir()), os.path.abspath(w.commondir())
  753. )
  754. self.assertEqual(r.refs.keys(), w.refs.keys())
  755. self.assertNotEqual(r.head(), w.head())
  756. class BuildRepoRootTests(TestCase):
  757. """Tests that build on-disk repos from scratch.
  758. Repos live in a temp dir and are torn down after each test. They start with
  759. a single commit in master having single file named 'a'.
  760. """
  761. def get_repo_dir(self):
  762. return os.path.join(tempfile.mkdtemp(), "test")
  763. def setUp(self):
  764. super(BuildRepoRootTests, self).setUp()
  765. self._repo_dir = self.get_repo_dir()
  766. os.makedirs(self._repo_dir)
  767. r = self._repo = Repo.init(self._repo_dir)
  768. self.addCleanup(tear_down_repo, r)
  769. self.assertFalse(r.bare)
  770. self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD"))
  771. self.assertRaises(KeyError, lambda: r.refs[b"refs/heads/master"])
  772. with open(os.path.join(r.path, "a"), "wb") as f:
  773. f.write(b"file contents")
  774. r.stage(["a"])
  775. commit_sha = r.do_commit(
  776. b"msg",
  777. committer=b"Test Committer <test@nodomain.com>",
  778. author=b"Test Author <test@nodomain.com>",
  779. commit_timestamp=12345,
  780. commit_timezone=0,
  781. author_timestamp=12345,
  782. author_timezone=0,
  783. )
  784. self.assertEqual([], r[commit_sha].parents)
  785. self._root_commit = commit_sha
  786. def test_get_shallow(self):
  787. self.assertEqual(set(), self._repo.get_shallow())
  788. with open(os.path.join(self._repo.path, ".git", "shallow"), "wb") as f:
  789. f.write(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097\n")
  790. self.assertEqual(
  791. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  792. self._repo.get_shallow(),
  793. )
  794. def test_update_shallow(self):
  795. self._repo.update_shallow(None, None) # no op
  796. self.assertEqual(set(), self._repo.get_shallow())
  797. self._repo.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None)
  798. self.assertEqual(
  799. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  800. self._repo.get_shallow(),
  801. )
  802. self._repo.update_shallow(
  803. [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"],
  804. [b"f9e39b120c68182a4ba35349f832d0e4e61f485c"],
  805. )
  806. self.assertEqual(
  807. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  808. self._repo.get_shallow(),
  809. )
  810. self._repo.update_shallow(
  811. None, [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"]
  812. )
  813. self.assertEqual(set(), self._repo.get_shallow())
  814. self.assertEqual(
  815. False,
  816. os.path.exists(os.path.join(self._repo.controldir(), "shallow")),
  817. )
  818. def test_build_repo(self):
  819. r = self._repo
  820. self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD"))
  821. self.assertEqual(self._root_commit, r.refs[b"refs/heads/master"])
  822. expected_blob = objects.Blob.from_string(b"file contents")
  823. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  824. actual_commit = r[self._root_commit]
  825. self.assertEqual(b"msg", actual_commit.message)
  826. def test_commit_modified(self):
  827. r = self._repo
  828. with open(os.path.join(r.path, "a"), "wb") as f:
  829. f.write(b"new contents")
  830. r.stage(["a"])
  831. commit_sha = r.do_commit(
  832. b"modified a",
  833. committer=b"Test Committer <test@nodomain.com>",
  834. author=b"Test Author <test@nodomain.com>",
  835. commit_timestamp=12395,
  836. commit_timezone=0,
  837. author_timestamp=12395,
  838. author_timezone=0,
  839. )
  840. self.assertEqual([self._root_commit], r[commit_sha].parents)
  841. a_mode, a_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"a")
  842. self.assertEqual(stat.S_IFREG | 0o644, a_mode)
  843. self.assertEqual(b"new contents", r[a_id].data)
  844. @skipIf(not getattr(os, "symlink", None), "Requires symlink support")
  845. def test_commit_symlink(self):
  846. r = self._repo
  847. os.symlink("a", os.path.join(r.path, "b"))
  848. r.stage(["a", "b"])
  849. commit_sha = r.do_commit(
  850. b"Symlink b",
  851. committer=b"Test Committer <test@nodomain.com>",
  852. author=b"Test Author <test@nodomain.com>",
  853. commit_timestamp=12395,
  854. commit_timezone=0,
  855. author_timestamp=12395,
  856. author_timezone=0,
  857. )
  858. self.assertEqual([self._root_commit], r[commit_sha].parents)
  859. b_mode, b_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"b")
  860. self.assertTrue(stat.S_ISLNK(b_mode))
  861. self.assertEqual(b"a", r[b_id].data)
  862. def test_commit_merge_heads_file(self):
  863. tmp_dir = tempfile.mkdtemp()
  864. self.addCleanup(shutil.rmtree, tmp_dir)
  865. r = Repo.init(tmp_dir)
  866. with open(os.path.join(r.path, "a"), "w") as f:
  867. f.write("initial text")
  868. c1 = r.do_commit(
  869. b"initial commit",
  870. committer=b"Test Committer <test@nodomain.com>",
  871. author=b"Test Author <test@nodomain.com>",
  872. commit_timestamp=12395,
  873. commit_timezone=0,
  874. author_timestamp=12395,
  875. author_timezone=0,
  876. )
  877. with open(os.path.join(r.path, "a"), "w") as f:
  878. f.write("merged text")
  879. with open(os.path.join(r.path, ".git", "MERGE_HEAD"), "w") as f:
  880. f.write("c27a2d21dd136312d7fa9e8baabb82561a1727d0\n")
  881. r.stage(["a"])
  882. commit_sha = r.do_commit(
  883. b"deleted a",
  884. committer=b"Test Committer <test@nodomain.com>",
  885. author=b"Test Author <test@nodomain.com>",
  886. commit_timestamp=12395,
  887. commit_timezone=0,
  888. author_timestamp=12395,
  889. author_timezone=0,
  890. )
  891. self.assertEqual(
  892. [c1, b"c27a2d21dd136312d7fa9e8baabb82561a1727d0"],
  893. r[commit_sha].parents,
  894. )
  895. def test_commit_deleted(self):
  896. r = self._repo
  897. os.remove(os.path.join(r.path, "a"))
  898. r.stage(["a"])
  899. commit_sha = r.do_commit(
  900. b"deleted a",
  901. committer=b"Test Committer <test@nodomain.com>",
  902. author=b"Test Author <test@nodomain.com>",
  903. commit_timestamp=12395,
  904. commit_timezone=0,
  905. author_timestamp=12395,
  906. author_timezone=0,
  907. )
  908. self.assertEqual([self._root_commit], r[commit_sha].parents)
  909. self.assertEqual([], list(r.open_index()))
  910. tree = r[r[commit_sha].tree]
  911. self.assertEqual([], list(tree.iteritems()))
  912. def test_commit_follows(self):
  913. r = self._repo
  914. r.refs.set_symbolic_ref(b"HEAD", b"refs/heads/bla")
  915. commit_sha = r.do_commit(
  916. b"commit with strange character",
  917. committer=b"Test Committer <test@nodomain.com>",
  918. author=b"Test Author <test@nodomain.com>",
  919. commit_timestamp=12395,
  920. commit_timezone=0,
  921. author_timestamp=12395,
  922. author_timezone=0,
  923. ref=b"HEAD",
  924. )
  925. self.assertEqual(commit_sha, r[b"refs/heads/bla"].id)
  926. def test_commit_encoding(self):
  927. r = self._repo
  928. commit_sha = r.do_commit(
  929. b"commit with strange character \xee",
  930. committer=b"Test Committer <test@nodomain.com>",
  931. author=b"Test Author <test@nodomain.com>",
  932. commit_timestamp=12395,
  933. commit_timezone=0,
  934. author_timestamp=12395,
  935. author_timezone=0,
  936. encoding=b"iso8859-1",
  937. )
  938. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  939. def test_compression_level(self):
  940. r = self._repo
  941. c = r.get_config()
  942. c.set(("core",), "compression", "3")
  943. c.set(("core",), "looseCompression", "4")
  944. c.write_to_path()
  945. r = Repo(self._repo_dir)
  946. self.assertEqual(r.object_store.loose_compression_level, 4)
  947. def test_repositoryformatversion_unsupported(self):
  948. r = self._repo
  949. c = r.get_config()
  950. c.set(("core",), "repositoryformatversion", "2")
  951. c.write_to_path()
  952. self.assertRaises(UnsupportedVersion, Repo, self._repo_dir)
  953. def test_repositoryformatversion_1(self):
  954. r = self._repo
  955. c = r.get_config()
  956. c.set(("core",), "repositoryformatversion", "1")
  957. c.write_to_path()
  958. Repo(self._repo_dir)
  959. def test_repositoryformatversion_1_extension(self):
  960. r = self._repo
  961. c = r.get_config()
  962. c.set(("core",), "repositoryformatversion", "1")
  963. c.set(("extensions", ), "worktreeconfig", True)
  964. c.write_to_path()
  965. self.assertRaises(UnsupportedExtension, Repo, self._repo_dir)
  966. def test_commit_encoding_from_config(self):
  967. r = self._repo
  968. c = r.get_config()
  969. c.set(("i18n",), "commitEncoding", "iso8859-1")
  970. c.write_to_path()
  971. commit_sha = r.do_commit(
  972. b"commit with strange character \xee",
  973. committer=b"Test Committer <test@nodomain.com>",
  974. author=b"Test Author <test@nodomain.com>",
  975. commit_timestamp=12395,
  976. commit_timezone=0,
  977. author_timestamp=12395,
  978. author_timezone=0,
  979. )
  980. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  981. def test_commit_config_identity(self):
  982. # commit falls back to the users' identity if it wasn't specified
  983. r = self._repo
  984. c = r.get_config()
  985. c.set((b"user",), b"name", b"Jelmer")
  986. c.set((b"user",), b"email", b"jelmer@apache.org")
  987. c.write_to_path()
  988. commit_sha = r.do_commit(b"message")
  989. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  990. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  991. def test_commit_config_identity_strips_than(self):
  992. # commit falls back to the users' identity if it wasn't specified,
  993. # and strips superfluous <>
  994. r = self._repo
  995. c = r.get_config()
  996. c.set((b"user",), b"name", b"Jelmer")
  997. c.set((b"user",), b"email", b"<jelmer@apache.org>")
  998. c.write_to_path()
  999. commit_sha = r.do_commit(b"message")
  1000. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1001. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1002. def test_commit_config_identity_in_memoryrepo(self):
  1003. # commit falls back to the users' identity if it wasn't specified
  1004. r = MemoryRepo.init_bare([], {})
  1005. c = r.get_config()
  1006. c.set((b"user",), b"name", b"Jelmer")
  1007. c.set((b"user",), b"email", b"jelmer@apache.org")
  1008. commit_sha = r.do_commit(b"message", tree=objects.Tree().id)
  1009. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1010. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1011. def overrideEnv(self, name, value):
  1012. def restore():
  1013. if oldval is not None:
  1014. os.environ[name] = oldval
  1015. else:
  1016. del os.environ[name]
  1017. oldval = os.environ.get(name)
  1018. os.environ[name] = value
  1019. self.addCleanup(restore)
  1020. def test_commit_config_identity_from_env(self):
  1021. # commit falls back to the users' identity if it wasn't specified
  1022. self.overrideEnv("GIT_COMMITTER_NAME", "joe")
  1023. self.overrideEnv("GIT_COMMITTER_EMAIL", "joe@example.com")
  1024. r = self._repo
  1025. c = r.get_config()
  1026. c.set((b"user",), b"name", b"Jelmer")
  1027. c.set((b"user",), b"email", b"jelmer@apache.org")
  1028. c.write_to_path()
  1029. commit_sha = r.do_commit(b"message")
  1030. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1031. self.assertEqual(b"joe <joe@example.com>", r[commit_sha].committer)
  1032. def test_commit_fail_ref(self):
  1033. r = self._repo
  1034. def set_if_equals(name, old_ref, new_ref, **kwargs):
  1035. return False
  1036. r.refs.set_if_equals = set_if_equals
  1037. def add_if_new(name, new_ref, **kwargs):
  1038. self.fail("Unexpected call to add_if_new")
  1039. r.refs.add_if_new = add_if_new
  1040. old_shas = set(r.object_store)
  1041. self.assertRaises(
  1042. errors.CommitError,
  1043. r.do_commit,
  1044. b"failed commit",
  1045. committer=b"Test Committer <test@nodomain.com>",
  1046. author=b"Test Author <test@nodomain.com>",
  1047. commit_timestamp=12345,
  1048. commit_timezone=0,
  1049. author_timestamp=12345,
  1050. author_timezone=0,
  1051. )
  1052. new_shas = set(r.object_store) - old_shas
  1053. self.assertEqual(1, len(new_shas))
  1054. # Check that the new commit (now garbage) was added.
  1055. new_commit = r[new_shas.pop()]
  1056. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1057. self.assertEqual(b"failed commit", new_commit.message)
  1058. def test_commit_branch(self):
  1059. r = self._repo
  1060. commit_sha = r.do_commit(
  1061. b"commit to branch",
  1062. committer=b"Test Committer <test@nodomain.com>",
  1063. author=b"Test Author <test@nodomain.com>",
  1064. commit_timestamp=12395,
  1065. commit_timezone=0,
  1066. author_timestamp=12395,
  1067. author_timezone=0,
  1068. ref=b"refs/heads/new_branch",
  1069. )
  1070. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  1071. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  1072. self.assertEqual([], r[commit_sha].parents)
  1073. self.assertIn(b"refs/heads/new_branch", r)
  1074. new_branch_head = commit_sha
  1075. commit_sha = r.do_commit(
  1076. b"commit to branch 2",
  1077. committer=b"Test Committer <test@nodomain.com>",
  1078. author=b"Test Author <test@nodomain.com>",
  1079. commit_timestamp=12395,
  1080. commit_timezone=0,
  1081. author_timestamp=12395,
  1082. author_timezone=0,
  1083. ref=b"refs/heads/new_branch",
  1084. )
  1085. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  1086. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  1087. self.assertEqual([new_branch_head], r[commit_sha].parents)
  1088. def test_commit_merge_heads(self):
  1089. r = self._repo
  1090. merge_1 = r.do_commit(
  1091. b"commit to branch 2",
  1092. committer=b"Test Committer <test@nodomain.com>",
  1093. author=b"Test Author <test@nodomain.com>",
  1094. commit_timestamp=12395,
  1095. commit_timezone=0,
  1096. author_timestamp=12395,
  1097. author_timezone=0,
  1098. ref=b"refs/heads/new_branch",
  1099. )
  1100. commit_sha = r.do_commit(
  1101. b"commit with merge",
  1102. committer=b"Test Committer <test@nodomain.com>",
  1103. author=b"Test Author <test@nodomain.com>",
  1104. commit_timestamp=12395,
  1105. commit_timezone=0,
  1106. author_timestamp=12395,
  1107. author_timezone=0,
  1108. merge_heads=[merge_1],
  1109. )
  1110. self.assertEqual([self._root_commit, merge_1], r[commit_sha].parents)
  1111. def test_commit_dangling_commit(self):
  1112. r = self._repo
  1113. old_shas = set(r.object_store)
  1114. old_refs = r.get_refs()
  1115. commit_sha = r.do_commit(
  1116. b"commit with no ref",
  1117. committer=b"Test Committer <test@nodomain.com>",
  1118. author=b"Test Author <test@nodomain.com>",
  1119. commit_timestamp=12395,
  1120. commit_timezone=0,
  1121. author_timestamp=12395,
  1122. author_timezone=0,
  1123. ref=None,
  1124. )
  1125. new_shas = set(r.object_store) - old_shas
  1126. # New sha is added, but no new refs
  1127. self.assertEqual(1, len(new_shas))
  1128. new_commit = r[new_shas.pop()]
  1129. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1130. self.assertEqual([], r[commit_sha].parents)
  1131. self.assertEqual(old_refs, r.get_refs())
  1132. def test_commit_dangling_commit_with_parents(self):
  1133. r = self._repo
  1134. old_shas = set(r.object_store)
  1135. old_refs = r.get_refs()
  1136. commit_sha = r.do_commit(
  1137. b"commit with no ref",
  1138. committer=b"Test Committer <test@nodomain.com>",
  1139. author=b"Test Author <test@nodomain.com>",
  1140. commit_timestamp=12395,
  1141. commit_timezone=0,
  1142. author_timestamp=12395,
  1143. author_timezone=0,
  1144. ref=None,
  1145. merge_heads=[self._root_commit],
  1146. )
  1147. new_shas = set(r.object_store) - old_shas
  1148. # New sha is added, but no new refs
  1149. self.assertEqual(1, len(new_shas))
  1150. new_commit = r[new_shas.pop()]
  1151. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1152. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1153. self.assertEqual(old_refs, r.get_refs())
  1154. def test_stage_absolute(self):
  1155. r = self._repo
  1156. os.remove(os.path.join(r.path, "a"))
  1157. self.assertRaises(ValueError, r.stage, [os.path.join(r.path, "a")])
  1158. def test_stage_deleted(self):
  1159. r = self._repo
  1160. os.remove(os.path.join(r.path, "a"))
  1161. r.stage(["a"])
  1162. r.stage(["a"]) # double-stage a deleted path
  1163. self.assertEqual([], list(r.open_index()))
  1164. def test_stage_directory(self):
  1165. r = self._repo
  1166. os.mkdir(os.path.join(r.path, "c"))
  1167. r.stage(["c"])
  1168. self.assertEqual([b"a"], list(r.open_index()))
  1169. def test_stage_submodule(self):
  1170. r = self._repo
  1171. s = Repo.init(os.path.join(r.path, "sub"), mkdir=True)
  1172. s.do_commit(b'message')
  1173. r.stage(["sub"])
  1174. self.assertEqual([b"a", b"sub"], list(r.open_index()))
  1175. def test_unstage_midify_file_with_dir(self):
  1176. os.mkdir(os.path.join(self._repo.path, 'new_dir'))
  1177. full_path = os.path.join(self._repo.path, 'new_dir', 'foo')
  1178. with open(full_path, 'w') as f:
  1179. f.write('hello')
  1180. porcelain.add(self._repo, paths=[full_path])
  1181. porcelain.commit(
  1182. self._repo,
  1183. message=b"unitest",
  1184. committer=b"Jane <jane@example.com>",
  1185. author=b"John <john@example.com>",
  1186. )
  1187. with open(full_path, 'a') as f:
  1188. f.write('something new')
  1189. self._repo.unstage(['new_dir/foo'])
  1190. status = list(porcelain.status(self._repo))
  1191. self.assertEqual([{'add': [], 'delete': [], 'modify': []}, [b'new_dir/foo'], []], status)
  1192. def test_unstage_while_no_commit(self):
  1193. file = 'foo'
  1194. full_path = os.path.join(self._repo.path, file)
  1195. with open(full_path, 'w') as f:
  1196. f.write('hello')
  1197. porcelain.add(self._repo, paths=[full_path])
  1198. self._repo.unstage([file])
  1199. status = list(porcelain.status(self._repo))
  1200. self.assertEqual([{'add': [], 'delete': [], 'modify': []}, [], ['foo']], status)
  1201. def test_unstage_add_file(self):
  1202. file = 'foo'
  1203. full_path = os.path.join(self._repo.path, file)
  1204. porcelain.commit(
  1205. self._repo,
  1206. message=b"unitest",
  1207. committer=b"Jane <jane@example.com>",
  1208. author=b"John <john@example.com>",
  1209. )
  1210. with open(full_path, 'w') as f:
  1211. f.write('hello')
  1212. porcelain.add(self._repo, paths=[full_path])
  1213. self._repo.unstage([file])
  1214. status = list(porcelain.status(self._repo))
  1215. self.assertEqual([{'add': [], 'delete': [], 'modify': []}, [], ['foo']], status)
  1216. def test_unstage_modify_file(self):
  1217. file = 'foo'
  1218. full_path = os.path.join(self._repo.path, file)
  1219. with open(full_path, 'w') as f:
  1220. f.write('hello')
  1221. porcelain.add(self._repo, paths=[full_path])
  1222. porcelain.commit(
  1223. self._repo,
  1224. message=b"unitest",
  1225. committer=b"Jane <jane@example.com>",
  1226. author=b"John <john@example.com>",
  1227. )
  1228. with open(full_path, 'a') as f:
  1229. f.write('broken')
  1230. porcelain.add(self._repo, paths=[full_path])
  1231. self._repo.unstage([file])
  1232. status = list(porcelain.status(self._repo))
  1233. self.assertEqual([{'add': [], 'delete': [], 'modify': []}, [b'foo'], []], status)
  1234. def test_unstage_remove_file(self):
  1235. file = 'foo'
  1236. full_path = os.path.join(self._repo.path, file)
  1237. with open(full_path, 'w') as f:
  1238. f.write('hello')
  1239. porcelain.add(self._repo, paths=[full_path])
  1240. porcelain.commit(
  1241. self._repo,
  1242. message=b"unitest",
  1243. committer=b"Jane <jane@example.com>",
  1244. author=b"John <john@example.com>",
  1245. )
  1246. os.remove(full_path)
  1247. self._repo.unstage([file])
  1248. status = list(porcelain.status(self._repo))
  1249. self.assertEqual([{'add': [], 'delete': [], 'modify': []}, [b'foo'], []], status)
  1250. @skipIf(
  1251. sys.platform in ("win32", "darwin"),
  1252. "tries to implicitly decode as utf8",
  1253. )
  1254. def test_commit_no_encode_decode(self):
  1255. r = self._repo
  1256. repo_path_bytes = os.fsencode(r.path)
  1257. encodings = ("utf8", "latin1")
  1258. names = [u"À".encode(encoding) for encoding in encodings]
  1259. for name, encoding in zip(names, encodings):
  1260. full_path = os.path.join(repo_path_bytes, name)
  1261. with open(full_path, "wb") as f:
  1262. f.write(encoding.encode("ascii"))
  1263. # These files are break tear_down_repo, so cleanup these files
  1264. # ourselves.
  1265. self.addCleanup(os.remove, full_path)
  1266. r.stage(names)
  1267. commit_sha = r.do_commit(
  1268. b"Files with different encodings",
  1269. committer=b"Test Committer <test@nodomain.com>",
  1270. author=b"Test Author <test@nodomain.com>",
  1271. commit_timestamp=12395,
  1272. commit_timezone=0,
  1273. author_timestamp=12395,
  1274. author_timezone=0,
  1275. ref=None,
  1276. merge_heads=[self._root_commit],
  1277. )
  1278. for name, encoding in zip(names, encodings):
  1279. mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name)
  1280. self.assertEqual(stat.S_IFREG | 0o644, mode)
  1281. self.assertEqual(encoding.encode("ascii"), r[id].data)
  1282. def test_discover_intended(self):
  1283. path = os.path.join(self._repo_dir, "b/c")
  1284. r = Repo.discover(path)
  1285. self.assertEqual(r.head(), self._repo.head())
  1286. def test_discover_isrepo(self):
  1287. r = Repo.discover(self._repo_dir)
  1288. self.assertEqual(r.head(), self._repo.head())
  1289. def test_discover_notrepo(self):
  1290. with self.assertRaises(NotGitRepository):
  1291. Repo.discover("/")
  1292. class CheckUserIdentityTests(TestCase):
  1293. def test_valid(self):
  1294. check_user_identity(b"Me <me@example.com>")
  1295. def test_invalid(self):
  1296. self.assertRaises(InvalidUserIdentity, check_user_identity, b"No Email")
  1297. self.assertRaises(
  1298. InvalidUserIdentity, check_user_identity, b"Fullname <missing"
  1299. )
  1300. self.assertRaises(
  1301. InvalidUserIdentity, check_user_identity, b"Fullname missing>"
  1302. )
  1303. self.assertRaises(
  1304. InvalidUserIdentity, check_user_identity, b"Fullname >order<>"
  1305. )