2
0

test_repository.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  1. # test_repository.py -- tests for repository.py
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  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, objects, porcelain
  31. from dulwich.config import Config
  32. from dulwich.errors import NotGitRepository
  33. from dulwich.object_store import tree_lookup_path
  34. from dulwich.repo import (
  35. InvalidUserIdentity,
  36. MemoryRepo,
  37. Repo,
  38. UnsupportedExtension,
  39. UnsupportedVersion,
  40. check_user_identity,
  41. )
  42. from dulwich.tests.utils import open_repo, setup_warning_catcher, tear_down_repo
  43. from . import TestCase, skipIf
  44. missing_sha = b"b91fa4d900e17e99b433218e988c4eb4a3e9a097"
  45. class CreateRepositoryTests(TestCase):
  46. def assertFileContentsEqual(self, expected, repo, path) -> None:
  47. f = repo.get_named_file(path)
  48. if not f:
  49. self.assertEqual(expected, None)
  50. else:
  51. with f:
  52. self.assertEqual(expected, f.read())
  53. def _check_repo_contents(self, repo, expect_bare) -> None:
  54. self.assertEqual(expect_bare, repo.bare)
  55. self.assertFileContentsEqual(b"Unnamed repository", repo, "description")
  56. self.assertFileContentsEqual(b"", repo, os.path.join("info", "exclude"))
  57. self.assertFileContentsEqual(None, repo, "nonexistent file")
  58. barestr = b"bare = " + str(expect_bare).lower().encode("ascii")
  59. with repo.get_named_file("config") as f:
  60. config_text = f.read()
  61. self.assertIn(barestr, config_text, f"{config_text!r}")
  62. expect_filemode = sys.platform != "win32"
  63. barestr = b"filemode = " + str(expect_filemode).lower().encode("ascii")
  64. with repo.get_named_file("config") as f:
  65. config_text = f.read()
  66. self.assertIn(barestr, config_text, f"{config_text!r}")
  67. if isinstance(repo, Repo):
  68. expected_mode = "0o100644" if expect_filemode else "0o100666"
  69. expected = {
  70. "HEAD": expected_mode,
  71. "config": expected_mode,
  72. "description": expected_mode,
  73. }
  74. actual = {
  75. f[len(repo._controldir) + 1 :]: oct(os.stat(f).st_mode)
  76. for f in glob.glob(os.path.join(repo._controldir, "*"))
  77. if os.path.isfile(f)
  78. }
  79. self.assertEqual(expected, actual)
  80. def test_create_memory(self) -> None:
  81. repo = MemoryRepo.init_bare([], {})
  82. self._check_repo_contents(repo, True)
  83. def test_create_disk_bare(self) -> None:
  84. tmp_dir = tempfile.mkdtemp()
  85. self.addCleanup(shutil.rmtree, tmp_dir)
  86. repo = Repo.init_bare(tmp_dir)
  87. self.assertEqual(tmp_dir, repo._controldir)
  88. self._check_repo_contents(repo, True)
  89. def test_create_disk_non_bare(self) -> None:
  90. tmp_dir = tempfile.mkdtemp()
  91. self.addCleanup(shutil.rmtree, tmp_dir)
  92. repo = Repo.init(tmp_dir)
  93. self.assertEqual(os.path.join(tmp_dir, ".git"), repo._controldir)
  94. self._check_repo_contents(repo, False)
  95. def test_create_disk_non_bare_mkdir(self) -> None:
  96. tmp_dir = tempfile.mkdtemp()
  97. target_dir = os.path.join(tmp_dir, "target")
  98. self.addCleanup(shutil.rmtree, tmp_dir)
  99. repo = Repo.init(target_dir, mkdir=True)
  100. self.assertEqual(os.path.join(target_dir, ".git"), repo._controldir)
  101. self._check_repo_contents(repo, False)
  102. def test_create_disk_bare_mkdir(self) -> None:
  103. tmp_dir = tempfile.mkdtemp()
  104. target_dir = os.path.join(tmp_dir, "target")
  105. self.addCleanup(shutil.rmtree, tmp_dir)
  106. repo = Repo.init_bare(target_dir, mkdir=True)
  107. self.assertEqual(target_dir, repo._controldir)
  108. self._check_repo_contents(repo, True)
  109. def test_create_disk_bare_pathlib(self) -> None:
  110. from pathlib import Path
  111. tmp_dir = tempfile.mkdtemp()
  112. self.addCleanup(shutil.rmtree, tmp_dir)
  113. repo_path = Path(tmp_dir)
  114. repo = Repo.init_bare(repo_path)
  115. self.assertEqual(tmp_dir, repo._controldir)
  116. self._check_repo_contents(repo, True)
  117. # Test that refpath works with pathlib
  118. ref_path = repo.refs.refpath(b"refs/heads/master")
  119. self.assertTrue(isinstance(ref_path, bytes))
  120. expected_path = os.path.join(tmp_dir.encode(), b"refs", b"heads", b"master")
  121. self.assertEqual(ref_path, expected_path)
  122. def test_create_disk_non_bare_pathlib(self) -> None:
  123. from pathlib import Path
  124. tmp_dir = tempfile.mkdtemp()
  125. self.addCleanup(shutil.rmtree, tmp_dir)
  126. repo_path = Path(tmp_dir)
  127. repo = Repo.init(repo_path)
  128. self.assertEqual(os.path.join(tmp_dir, ".git"), repo._controldir)
  129. self._check_repo_contents(repo, False)
  130. def test_open_repo_pathlib(self) -> None:
  131. from pathlib import Path
  132. tmp_dir = tempfile.mkdtemp()
  133. self.addCleanup(shutil.rmtree, tmp_dir)
  134. # First create a repo
  135. repo = Repo.init_bare(tmp_dir)
  136. repo.close()
  137. # Now open it with pathlib
  138. repo_path = Path(tmp_dir)
  139. repo2 = Repo(repo_path)
  140. self.assertEqual(tmp_dir, repo2._controldir)
  141. self.assertTrue(repo2.bare)
  142. repo2.close()
  143. def test_create_disk_bare_mkdir_pathlib(self) -> None:
  144. from pathlib import Path
  145. tmp_dir = tempfile.mkdtemp()
  146. target_path = Path(tmp_dir) / "target"
  147. self.addCleanup(shutil.rmtree, tmp_dir)
  148. repo = Repo.init_bare(target_path, mkdir=True)
  149. self.assertEqual(str(target_path), repo._controldir)
  150. self._check_repo_contents(repo, True)
  151. class MemoryRepoTests(TestCase):
  152. def test_set_description(self) -> None:
  153. r = MemoryRepo.init_bare([], {})
  154. description = b"Some description"
  155. r.set_description(description)
  156. self.assertEqual(description, r.get_description())
  157. def test_pull_into(self) -> None:
  158. r = MemoryRepo.init_bare([], {})
  159. repo = open_repo("a.git")
  160. self.addCleanup(tear_down_repo, repo)
  161. repo.fetch(r)
  162. def test_fetch_from_git_cloned_repo(self) -> None:
  163. """Test fetching from a git-cloned repo into MemoryRepo (issue #1179)."""
  164. import tempfile
  165. from dulwich.client import LocalGitClient
  166. with tempfile.TemporaryDirectory() as tmpdir:
  167. # Create initial repo using dulwich
  168. initial_path = os.path.join(tmpdir, "initial")
  169. initial_repo = Repo.init(initial_path, mkdir=True)
  170. # Create some content
  171. test_file = os.path.join(initial_path, "test.txt")
  172. with open(test_file, "w") as f:
  173. f.write("test content\n")
  174. # Stage and commit using dulwich
  175. initial_repo.stage(["test.txt"])
  176. initial_repo.do_commit(
  177. b"Initial commit\n",
  178. committer=b"Test Committer <test@example.com>",
  179. author=b"Test Author <test@example.com>",
  180. )
  181. # Clone using dulwich
  182. cloned_path = os.path.join(tmpdir, "cloned")
  183. cloned_repo = initial_repo.clone(cloned_path, mkdir=True)
  184. initial_repo.close()
  185. cloned_repo.close()
  186. # Fetch from the cloned repo into MemoryRepo
  187. memory_repo = MemoryRepo()
  188. client = LocalGitClient()
  189. # This should not raise AssertionError
  190. result = client.fetch(cloned_path, memory_repo)
  191. # Verify the fetch worked
  192. self.assertIn(b"HEAD", result.refs)
  193. self.assertIn(b"refs/heads/master", result.refs)
  194. # Verify we can read the fetched objects
  195. head_sha = result.refs[b"HEAD"]
  196. commit = memory_repo[head_sha]
  197. self.assertEqual(commit.message, b"Initial commit\n")
  198. class RepositoryRootTests(TestCase):
  199. def mkdtemp(self):
  200. return tempfile.mkdtemp()
  201. def open_repo(self, name):
  202. temp_dir = self.mkdtemp()
  203. repo = open_repo(name, temp_dir)
  204. self.addCleanup(tear_down_repo, repo)
  205. return repo
  206. def test_simple_props(self) -> None:
  207. r = self.open_repo("a.git")
  208. self.assertEqual(r.controldir(), r.path)
  209. def test_setitem(self) -> None:
  210. r = self.open_repo("a.git")
  211. r[b"refs/tags/foo"] = b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"
  212. self.assertEqual(
  213. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", r[b"refs/tags/foo"].id
  214. )
  215. def test_getitem_unicode(self) -> None:
  216. r = self.open_repo("a.git")
  217. test_keys = [
  218. (b"refs/heads/master", True),
  219. (b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", True),
  220. (b"11" * 19 + b"--", False),
  221. ]
  222. for k, contained in test_keys:
  223. self.assertEqual(k in r, contained)
  224. # Avoid deprecation warning under Py3.2+
  225. if getattr(self, "assertRaisesRegex", None):
  226. assertRaisesRegexp = self.assertRaisesRegex
  227. else:
  228. assertRaisesRegexp = self.assertRaisesRegexp
  229. for k, _ in test_keys:
  230. assertRaisesRegexp(
  231. TypeError,
  232. "'name' must be bytestring, not int",
  233. r.__getitem__,
  234. 12,
  235. )
  236. def test_delitem(self) -> None:
  237. r = self.open_repo("a.git")
  238. del r[b"refs/heads/master"]
  239. self.assertRaises(KeyError, lambda: r[b"refs/heads/master"])
  240. del r[b"HEAD"]
  241. self.assertRaises(KeyError, lambda: r[b"HEAD"])
  242. self.assertRaises(ValueError, r.__delitem__, b"notrefs/foo")
  243. def test_get_refs(self) -> None:
  244. r = self.open_repo("a.git")
  245. self.assertEqual(
  246. {
  247. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  248. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  249. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  250. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  251. },
  252. r.get_refs(),
  253. )
  254. def test_head(self) -> None:
  255. r = self.open_repo("a.git")
  256. self.assertEqual(r.head(), b"a90fa2d900a17e99b433217e988c4eb4a2e9a097")
  257. def test_get_object(self) -> None:
  258. r = self.open_repo("a.git")
  259. obj = r.get_object(r.head())
  260. self.assertEqual(obj.type_name, b"commit")
  261. def test_get_object_non_existant(self) -> None:
  262. r = self.open_repo("a.git")
  263. self.assertRaises(KeyError, r.get_object, missing_sha)
  264. def test_contains_object(self) -> None:
  265. r = self.open_repo("a.git")
  266. self.assertIn(r.head(), r)
  267. self.assertNotIn(b"z" * 40, r)
  268. def test_contains_ref(self) -> None:
  269. r = self.open_repo("a.git")
  270. self.assertIn(b"HEAD", r)
  271. def test_get_no_description(self) -> None:
  272. r = self.open_repo("a.git")
  273. self.assertIs(None, r.get_description())
  274. def test_get_description(self) -> None:
  275. r = self.open_repo("a.git")
  276. with open(os.path.join(r.path, "description"), "wb") as f:
  277. f.write(b"Some description")
  278. self.assertEqual(b"Some description", r.get_description())
  279. def test_set_description(self) -> None:
  280. r = self.open_repo("a.git")
  281. description = b"Some description"
  282. r.set_description(description)
  283. self.assertEqual(description, r.get_description())
  284. def test_contains_missing(self) -> None:
  285. r = self.open_repo("a.git")
  286. self.assertNotIn(b"bar", r)
  287. def test_get_peeled(self) -> None:
  288. # unpacked ref
  289. r = self.open_repo("a.git")
  290. tag_sha = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a"
  291. self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head())
  292. self.assertEqual(r.get_peeled(b"refs/tags/mytag"), r.head())
  293. # packed ref with cached peeled value
  294. packed_tag_sha = b"b0931cadc54336e78a1d980420e3268903b57a50"
  295. parent_sha = r[r.head()].parents[0]
  296. self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha)
  297. self.assertEqual(r.get_peeled(b"refs/tags/mytag-packed"), parent_sha)
  298. # TODO: add more corner cases to test repo
  299. def test_get_peeled_not_tag(self) -> None:
  300. r = self.open_repo("a.git")
  301. self.assertEqual(r.get_peeled(b"HEAD"), r.head())
  302. def test_get_parents(self) -> None:
  303. r = self.open_repo("a.git")
  304. self.assertEqual(
  305. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  306. r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"),
  307. )
  308. r.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None)
  309. self.assertEqual([], r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"))
  310. def test_get_walker(self) -> None:
  311. r = self.open_repo("a.git")
  312. # include defaults to [r.head()]
  313. self.assertEqual(
  314. [e.commit.id for e in r.get_walker()],
  315. [r.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  316. )
  317. self.assertEqual(
  318. [
  319. e.commit.id
  320. for e in r.get_walker([b"2a72d929692c41d8554c07f6301757ba18a65d91"])
  321. ],
  322. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  323. )
  324. self.assertEqual(
  325. [
  326. e.commit.id
  327. for e in r.get_walker(b"2a72d929692c41d8554c07f6301757ba18a65d91")
  328. ],
  329. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  330. )
  331. def assertFilesystemHidden(self, path) -> None:
  332. if sys.platform != "win32":
  333. return
  334. import ctypes
  335. from ctypes.wintypes import DWORD, LPCWSTR
  336. GetFileAttributesW = ctypes.WINFUNCTYPE(DWORD, LPCWSTR)(
  337. ("GetFileAttributesW", ctypes.windll.kernel32)
  338. )
  339. self.assertTrue(2 & GetFileAttributesW(path))
  340. def test_init_existing(self) -> None:
  341. tmp_dir = self.mkdtemp()
  342. self.addCleanup(shutil.rmtree, tmp_dir)
  343. t = Repo.init(tmp_dir)
  344. self.addCleanup(t.close)
  345. self.assertEqual(os.listdir(tmp_dir), [".git"])
  346. self.assertFilesystemHidden(os.path.join(tmp_dir, ".git"))
  347. def test_init_mkdir(self) -> None:
  348. tmp_dir = self.mkdtemp()
  349. self.addCleanup(shutil.rmtree, tmp_dir)
  350. repo_dir = os.path.join(tmp_dir, "a-repo")
  351. t = Repo.init(repo_dir, mkdir=True)
  352. self.addCleanup(t.close)
  353. self.assertEqual(os.listdir(repo_dir), [".git"])
  354. self.assertFilesystemHidden(os.path.join(repo_dir, ".git"))
  355. def test_init_mkdir_unicode(self) -> None:
  356. repo_name = "\xa7"
  357. try:
  358. os.fsencode(repo_name)
  359. except UnicodeEncodeError:
  360. self.skipTest("filesystem lacks unicode support")
  361. tmp_dir = self.mkdtemp()
  362. self.addCleanup(shutil.rmtree, tmp_dir)
  363. repo_dir = os.path.join(tmp_dir, repo_name)
  364. t = Repo.init(repo_dir, mkdir=True)
  365. self.addCleanup(t.close)
  366. self.assertEqual(os.listdir(repo_dir), [".git"])
  367. self.assertFilesystemHidden(os.path.join(repo_dir, ".git"))
  368. def test_init_format(self) -> None:
  369. tmp_dir = self.mkdtemp()
  370. self.addCleanup(shutil.rmtree, tmp_dir)
  371. # Test format 0
  372. t0 = Repo.init(tmp_dir + "0", mkdir=True, format=0)
  373. self.addCleanup(t0.close)
  374. self.assertEqual(t0.get_config().get("core", "repositoryformatversion"), b"0")
  375. # Test format 1
  376. t1 = Repo.init(tmp_dir + "1", mkdir=True, format=1)
  377. self.addCleanup(t1.close)
  378. self.assertEqual(t1.get_config().get("core", "repositoryformatversion"), b"1")
  379. # Test default format
  380. td = Repo.init(tmp_dir + "d", mkdir=True)
  381. self.addCleanup(td.close)
  382. self.assertEqual(td.get_config().get("core", "repositoryformatversion"), b"0")
  383. # Test invalid format
  384. with self.assertRaises(ValueError):
  385. Repo.init(tmp_dir + "bad", mkdir=True, format=99)
  386. def test_init_bare_format(self) -> None:
  387. tmp_dir = self.mkdtemp()
  388. self.addCleanup(shutil.rmtree, tmp_dir)
  389. # Test format 1 for bare repo
  390. t = Repo.init_bare(tmp_dir + "bare", mkdir=True, format=1)
  391. self.addCleanup(t.close)
  392. self.assertEqual(t.get_config().get("core", "repositoryformatversion"), b"1")
  393. # Test invalid format for bare repo
  394. with self.assertRaises(ValueError):
  395. Repo.init_bare(tmp_dir + "badbr", mkdir=True, format=2)
  396. @skipIf(sys.platform == "win32", "fails on Windows")
  397. def test_fetch(self) -> None:
  398. r = self.open_repo("a.git")
  399. tmp_dir = self.mkdtemp()
  400. self.addCleanup(shutil.rmtree, tmp_dir)
  401. t = Repo.init(tmp_dir)
  402. self.addCleanup(t.close)
  403. r.fetch(t)
  404. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  405. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  406. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  407. self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t)
  408. self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t)
  409. @skipIf(sys.platform == "win32", "fails on Windows")
  410. def test_fetch_ignores_missing_refs(self) -> None:
  411. r = self.open_repo("a.git")
  412. missing = b"1234566789123456789123567891234657373833"
  413. r.refs[b"refs/heads/blah"] = missing
  414. tmp_dir = self.mkdtemp()
  415. self.addCleanup(shutil.rmtree, tmp_dir)
  416. t = Repo.init(tmp_dir)
  417. self.addCleanup(t.close)
  418. r.fetch(t)
  419. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  420. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  421. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  422. self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t)
  423. self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t)
  424. self.assertNotIn(missing, t)
  425. def test_clone(self) -> None:
  426. r = self.open_repo("a.git")
  427. tmp_dir = self.mkdtemp()
  428. self.addCleanup(shutil.rmtree, tmp_dir)
  429. with r.clone(tmp_dir, mkdir=False) as t:
  430. self.assertEqual(
  431. {
  432. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  433. b"refs/remotes/origin/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  434. b"refs/remotes/origin/HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  435. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  436. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  437. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  438. },
  439. t.refs.as_dict(),
  440. )
  441. shas = [e.commit.id for e in r.get_walker()]
  442. self.assertEqual(
  443. shas, [t.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"]
  444. )
  445. c = t.get_config()
  446. encoded_path = r.path
  447. if not isinstance(encoded_path, bytes):
  448. encoded_path = os.fsencode(encoded_path)
  449. self.assertEqual(encoded_path, c.get((b"remote", b"origin"), b"url"))
  450. self.assertEqual(
  451. b"+refs/heads/*:refs/remotes/origin/*",
  452. c.get((b"remote", b"origin"), b"fetch"),
  453. )
  454. def test_clone_no_head(self) -> None:
  455. temp_dir = self.mkdtemp()
  456. self.addCleanup(shutil.rmtree, temp_dir)
  457. repo_dir = os.path.join(os.path.dirname(__file__), "..", "testdata", "repos")
  458. dest_dir = os.path.join(temp_dir, "a.git")
  459. shutil.copytree(os.path.join(repo_dir, "a.git"), dest_dir, symlinks=True)
  460. r = Repo(dest_dir)
  461. self.addCleanup(r.close)
  462. del r.refs[b"refs/heads/master"]
  463. del r.refs[b"HEAD"]
  464. t = r.clone(os.path.join(temp_dir, "b.git"), mkdir=True)
  465. self.addCleanup(t.close)
  466. self.assertEqual(
  467. {
  468. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  469. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  470. },
  471. t.refs.as_dict(),
  472. )
  473. def test_clone_empty(self) -> None:
  474. """Test clone() doesn't crash if HEAD points to a non-existing ref.
  475. This simulates cloning server-side bare repository either when it is
  476. still empty or if user renames master branch and pushes private repo
  477. to the server.
  478. Non-bare repo HEAD always points to an existing ref.
  479. """
  480. r = self.open_repo("empty.git")
  481. tmp_dir = self.mkdtemp()
  482. self.addCleanup(shutil.rmtree, tmp_dir)
  483. r.clone(tmp_dir, mkdir=False, bare=True)
  484. def test_reset_index_symlink_enabled(self) -> None:
  485. if sys.platform == "win32":
  486. self.skipTest("symlinks are not supported on Windows")
  487. tmp_dir = self.mkdtemp()
  488. self.addCleanup(shutil.rmtree, tmp_dir)
  489. o = Repo.init(os.path.join(tmp_dir, "s"), mkdir=True)
  490. os.symlink("foo", os.path.join(tmp_dir, "s", "bar"))
  491. o.stage("bar")
  492. o.do_commit(b"add symlink")
  493. t = o.clone(os.path.join(tmp_dir, "t"), symlinks=True)
  494. o.close()
  495. bar_path = os.path.join(tmp_dir, "t", "bar")
  496. if sys.platform == "win32":
  497. with open(bar_path) as f:
  498. self.assertEqual("foo", f.read())
  499. else:
  500. self.assertEqual("foo", os.readlink(bar_path))
  501. t.close()
  502. def test_reset_index_symlink_disabled(self) -> None:
  503. tmp_dir = self.mkdtemp()
  504. self.addCleanup(shutil.rmtree, tmp_dir)
  505. o = Repo.init(os.path.join(tmp_dir, "s"), mkdir=True)
  506. o.close()
  507. os.symlink("foo", os.path.join(tmp_dir, "s", "bar"))
  508. o.stage("bar")
  509. o.do_commit(b"add symlink")
  510. t = o.clone(os.path.join(tmp_dir, "t"), symlinks=False)
  511. with open(os.path.join(tmp_dir, "t", "bar")) as f:
  512. self.assertEqual("foo", f.read())
  513. t.close()
  514. def test_clone_bare(self) -> None:
  515. r = self.open_repo("a.git")
  516. tmp_dir = self.mkdtemp()
  517. self.addCleanup(shutil.rmtree, tmp_dir)
  518. t = r.clone(tmp_dir, mkdir=False)
  519. t.close()
  520. def test_clone_checkout_and_bare(self) -> None:
  521. r = self.open_repo("a.git")
  522. tmp_dir = self.mkdtemp()
  523. self.addCleanup(shutil.rmtree, tmp_dir)
  524. self.assertRaises(
  525. ValueError, r.clone, tmp_dir, mkdir=False, checkout=True, bare=True
  526. )
  527. def test_clone_branch(self) -> None:
  528. r = self.open_repo("a.git")
  529. r.refs[b"refs/heads/mybranch"] = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a"
  530. tmp_dir = self.mkdtemp()
  531. self.addCleanup(shutil.rmtree, tmp_dir)
  532. with r.clone(tmp_dir, mkdir=False, branch=b"mybranch") as t:
  533. # HEAD should point to specified branch and not origin HEAD
  534. chain, sha = t.refs.follow(b"HEAD")
  535. self.assertEqual(chain[-1], b"refs/heads/mybranch")
  536. self.assertEqual(sha, b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a")
  537. self.assertEqual(
  538. t.refs[b"refs/remotes/origin/HEAD"],
  539. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  540. )
  541. def test_clone_tag(self) -> None:
  542. r = self.open_repo("a.git")
  543. tmp_dir = self.mkdtemp()
  544. self.addCleanup(shutil.rmtree, tmp_dir)
  545. with r.clone(tmp_dir, mkdir=False, branch=b"mytag") as t:
  546. # HEAD should be detached (and not a symbolic ref) at tag
  547. self.assertEqual(
  548. t.refs.read_ref(b"HEAD"),
  549. b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  550. )
  551. self.assertEqual(
  552. t.refs[b"refs/remotes/origin/HEAD"],
  553. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  554. )
  555. def test_clone_invalid_branch(self) -> None:
  556. r = self.open_repo("a.git")
  557. tmp_dir = self.mkdtemp()
  558. self.addCleanup(shutil.rmtree, tmp_dir)
  559. self.assertRaises(
  560. ValueError,
  561. r.clone,
  562. tmp_dir,
  563. mkdir=False,
  564. branch=b"mybranch",
  565. )
  566. def test_merge_history(self) -> None:
  567. r = self.open_repo("simple_merge.git")
  568. shas = [e.commit.id for e in r.get_walker()]
  569. self.assertEqual(
  570. shas,
  571. [
  572. b"5dac377bdded4c9aeb8dff595f0faeebcc8498cc",
  573. b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd",
  574. b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6",
  575. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  576. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  577. ],
  578. )
  579. def test_out_of_order_merge(self) -> None:
  580. """Test that revision history is ordered by date, not parent order."""
  581. r = self.open_repo("ooo_merge.git")
  582. shas = [e.commit.id for e in r.get_walker()]
  583. self.assertEqual(
  584. shas,
  585. [
  586. b"7601d7f6231db6a57f7bbb79ee52e4d462fd44d1",
  587. b"f507291b64138b875c28e03469025b1ea20bc614",
  588. b"fb5b0425c7ce46959bec94d54b9a157645e114f5",
  589. b"f9e39b120c68182a4ba35349f832d0e4e61f485c",
  590. ],
  591. )
  592. def test_get_tags_empty(self) -> None:
  593. r = self.open_repo("ooo_merge.git")
  594. self.assertEqual({}, r.refs.as_dict(b"refs/tags"))
  595. def test_get_config(self) -> None:
  596. r = self.open_repo("ooo_merge.git")
  597. self.assertIsInstance(r.get_config(), Config)
  598. def test_get_config_stack(self) -> None:
  599. r = self.open_repo("ooo_merge.git")
  600. self.assertIsInstance(r.get_config_stack(), Config)
  601. def test_common_revisions(self) -> None:
  602. """This test demonstrates that ``find_common_revisions()`` actually
  603. returns common heads, not revisions; dulwich already uses
  604. ``find_common_revisions()`` in such a manner (see
  605. ``Repo.find_objects()``).
  606. """
  607. expected_shas = {b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e"}
  608. # Source for objects.
  609. r_base = self.open_repo("simple_merge.git")
  610. # Re-create each-side of the merge in simple_merge.git.
  611. #
  612. # Since the trees and blobs are missing, the repository created is
  613. # corrupted, but we're only checking for commits for the purpose of
  614. # this test, so it's immaterial.
  615. r1_dir = self.mkdtemp()
  616. self.addCleanup(shutil.rmtree, r1_dir)
  617. r1_commits = [
  618. b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", # HEAD
  619. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  620. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  621. ]
  622. r2_dir = self.mkdtemp()
  623. self.addCleanup(shutil.rmtree, r2_dir)
  624. r2_commits = [
  625. b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", # HEAD
  626. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  627. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  628. ]
  629. r1 = Repo.init_bare(r1_dir)
  630. for c in r1_commits:
  631. r1.object_store.add_object(r_base.get_object(c))
  632. r1.refs[b"HEAD"] = r1_commits[0]
  633. r2 = Repo.init_bare(r2_dir)
  634. for c in r2_commits:
  635. r2.object_store.add_object(r_base.get_object(c))
  636. r2.refs[b"HEAD"] = r2_commits[0]
  637. # Finally, the 'real' testing!
  638. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  639. self.assertEqual(set(shas), expected_shas)
  640. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  641. self.assertEqual(set(shas), expected_shas)
  642. def test_shell_hook_pre_commit(self) -> None:
  643. if os.name != "posix":
  644. self.skipTest("shell hook tests requires POSIX shell")
  645. pre_commit_fail = """#!/bin/sh
  646. exit 1
  647. """
  648. pre_commit_success = """#!/bin/sh
  649. exit 0
  650. """
  651. repo_dir = os.path.join(self.mkdtemp())
  652. self.addCleanup(shutil.rmtree, repo_dir)
  653. r = Repo.init(repo_dir)
  654. self.addCleanup(r.close)
  655. pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit")
  656. with open(pre_commit, "w") as f:
  657. f.write(pre_commit_fail)
  658. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  659. self.assertRaises(
  660. errors.CommitError,
  661. r.do_commit,
  662. b"failed commit",
  663. committer=b"Test Committer <test@nodomain.com>",
  664. author=b"Test Author <test@nodomain.com>",
  665. commit_timestamp=12345,
  666. commit_timezone=0,
  667. author_timestamp=12345,
  668. author_timezone=0,
  669. )
  670. with open(pre_commit, "w") as f:
  671. f.write(pre_commit_success)
  672. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  673. commit_sha = r.do_commit(
  674. b"empty commit",
  675. committer=b"Test Committer <test@nodomain.com>",
  676. author=b"Test Author <test@nodomain.com>",
  677. commit_timestamp=12395,
  678. commit_timezone=0,
  679. author_timestamp=12395,
  680. author_timezone=0,
  681. )
  682. self.assertEqual([], r[commit_sha].parents)
  683. def test_shell_hook_commit_msg(self) -> None:
  684. if os.name != "posix":
  685. self.skipTest("shell hook tests requires POSIX shell")
  686. commit_msg_fail = """#!/bin/sh
  687. exit 1
  688. """
  689. commit_msg_success = """#!/bin/sh
  690. exit 0
  691. """
  692. repo_dir = self.mkdtemp()
  693. self.addCleanup(shutil.rmtree, repo_dir)
  694. r = Repo.init(repo_dir)
  695. self.addCleanup(r.close)
  696. commit_msg = os.path.join(r.controldir(), "hooks", "commit-msg")
  697. with open(commit_msg, "w") as f:
  698. f.write(commit_msg_fail)
  699. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  700. self.assertRaises(
  701. errors.CommitError,
  702. r.do_commit,
  703. b"failed commit",
  704. committer=b"Test Committer <test@nodomain.com>",
  705. author=b"Test Author <test@nodomain.com>",
  706. commit_timestamp=12345,
  707. commit_timezone=0,
  708. author_timestamp=12345,
  709. author_timezone=0,
  710. )
  711. with open(commit_msg, "w") as f:
  712. f.write(commit_msg_success)
  713. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  714. commit_sha = r.do_commit(
  715. b"empty commit",
  716. committer=b"Test Committer <test@nodomain.com>",
  717. author=b"Test Author <test@nodomain.com>",
  718. commit_timestamp=12395,
  719. commit_timezone=0,
  720. author_timestamp=12395,
  721. author_timezone=0,
  722. )
  723. self.assertEqual([], r[commit_sha].parents)
  724. def test_shell_hook_pre_commit_add_files(self) -> None:
  725. if os.name != "posix":
  726. self.skipTest("shell hook tests requires POSIX shell")
  727. pre_commit_contents = """#!{executable}
  728. import sys
  729. sys.path.extend({path!r})
  730. from dulwich.repo import Repo
  731. with open('foo', 'w') as f:
  732. f.write('newfile')
  733. r = Repo('.')
  734. r.stage(['foo'])
  735. """.format(
  736. executable=sys.executable,
  737. path=[os.path.join(os.path.dirname(__file__), "..", ".."), *sys.path],
  738. )
  739. repo_dir = os.path.join(self.mkdtemp())
  740. self.addCleanup(shutil.rmtree, repo_dir)
  741. r = Repo.init(repo_dir)
  742. self.addCleanup(r.close)
  743. with open(os.path.join(repo_dir, "blah"), "w") as f:
  744. f.write("blah")
  745. r.stage(["blah"])
  746. pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit")
  747. with open(pre_commit, "w") as f:
  748. f.write(pre_commit_contents)
  749. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  750. commit_sha = r.do_commit(
  751. b"new commit",
  752. committer=b"Test Committer <test@nodomain.com>",
  753. author=b"Test Author <test@nodomain.com>",
  754. commit_timestamp=12395,
  755. commit_timezone=0,
  756. author_timestamp=12395,
  757. author_timezone=0,
  758. )
  759. self.assertEqual([], r[commit_sha].parents)
  760. tree = r[r[commit_sha].tree]
  761. self.assertEqual({b"blah", b"foo"}, set(tree))
  762. def test_shell_hook_post_commit(self) -> None:
  763. if os.name != "posix":
  764. self.skipTest("shell hook tests requires POSIX shell")
  765. repo_dir = self.mkdtemp()
  766. self.addCleanup(shutil.rmtree, repo_dir)
  767. r = Repo.init(repo_dir)
  768. self.addCleanup(r.close)
  769. (fd, path) = tempfile.mkstemp(dir=repo_dir)
  770. os.close(fd)
  771. post_commit_msg = (
  772. """#!/bin/sh
  773. rm """
  774. + path
  775. + """
  776. """
  777. )
  778. root_sha = r.do_commit(
  779. b"empty commit",
  780. committer=b"Test Committer <test@nodomain.com>",
  781. author=b"Test Author <test@nodomain.com>",
  782. commit_timestamp=12345,
  783. commit_timezone=0,
  784. author_timestamp=12345,
  785. author_timezone=0,
  786. )
  787. self.assertEqual([], r[root_sha].parents)
  788. post_commit = os.path.join(r.controldir(), "hooks", "post-commit")
  789. with open(post_commit, "wb") as f:
  790. f.write(post_commit_msg.encode(locale.getpreferredencoding()))
  791. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  792. commit_sha = r.do_commit(
  793. b"empty commit",
  794. committer=b"Test Committer <test@nodomain.com>",
  795. author=b"Test Author <test@nodomain.com>",
  796. commit_timestamp=12345,
  797. commit_timezone=0,
  798. author_timestamp=12345,
  799. author_timezone=0,
  800. )
  801. self.assertEqual([root_sha], r[commit_sha].parents)
  802. self.assertFalse(os.path.exists(path))
  803. post_commit_msg_fail = """#!/bin/sh
  804. exit 1
  805. """
  806. with open(post_commit, "w") as f:
  807. f.write(post_commit_msg_fail)
  808. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  809. warnings.simplefilter("always", UserWarning)
  810. self.addCleanup(warnings.resetwarnings)
  811. warnings_list, restore_warnings = setup_warning_catcher()
  812. self.addCleanup(restore_warnings)
  813. commit_sha2 = r.do_commit(
  814. b"empty commit",
  815. committer=b"Test Committer <test@nodomain.com>",
  816. author=b"Test Author <test@nodomain.com>",
  817. commit_timestamp=12345,
  818. commit_timezone=0,
  819. author_timestamp=12345,
  820. author_timezone=0,
  821. )
  822. expected_warning = UserWarning(
  823. "post-commit hook failed: Hook post-commit exited with non-zero status 1",
  824. )
  825. for w in warnings_list:
  826. if type(w) is type(expected_warning) and w.args == expected_warning.args:
  827. break
  828. else:
  829. raise AssertionError(
  830. f"Expected warning {expected_warning!r} not in {warnings_list!r}"
  831. )
  832. self.assertEqual([commit_sha], r[commit_sha2].parents)
  833. def test_as_dict(self) -> None:
  834. def check(repo) -> None:
  835. self.assertEqual(
  836. repo.refs.subkeys(b"refs/tags"),
  837. repo.refs.subkeys(b"refs/tags/"),
  838. )
  839. self.assertEqual(
  840. repo.refs.as_dict(b"refs/tags"),
  841. repo.refs.as_dict(b"refs/tags/"),
  842. )
  843. self.assertEqual(
  844. repo.refs.as_dict(b"refs/heads"),
  845. repo.refs.as_dict(b"refs/heads/"),
  846. )
  847. bare = self.open_repo("a.git")
  848. tmp_dir = self.mkdtemp()
  849. self.addCleanup(shutil.rmtree, tmp_dir)
  850. with bare.clone(tmp_dir, mkdir=False) as nonbare:
  851. check(nonbare)
  852. check(bare)
  853. def test_working_tree(self) -> None:
  854. temp_dir = tempfile.mkdtemp()
  855. self.addCleanup(shutil.rmtree, temp_dir)
  856. worktree_temp_dir = tempfile.mkdtemp()
  857. self.addCleanup(shutil.rmtree, worktree_temp_dir)
  858. r = Repo.init(temp_dir)
  859. self.addCleanup(r.close)
  860. root_sha = r.do_commit(
  861. b"empty commit",
  862. committer=b"Test Committer <test@nodomain.com>",
  863. author=b"Test Author <test@nodomain.com>",
  864. commit_timestamp=12345,
  865. commit_timezone=0,
  866. author_timestamp=12345,
  867. author_timezone=0,
  868. )
  869. r.refs[b"refs/heads/master"] = root_sha
  870. w = Repo._init_new_working_directory(worktree_temp_dir, r)
  871. self.addCleanup(w.close)
  872. new_sha = w.do_commit(
  873. b"new commit",
  874. committer=b"Test Committer <test@nodomain.com>",
  875. author=b"Test Author <test@nodomain.com>",
  876. commit_timestamp=12345,
  877. commit_timezone=0,
  878. author_timestamp=12345,
  879. author_timezone=0,
  880. )
  881. w.refs[b"HEAD"] = new_sha
  882. self.assertEqual(
  883. os.path.abspath(r.controldir()), os.path.abspath(w.commondir())
  884. )
  885. self.assertEqual(r.refs.keys(), w.refs.keys())
  886. self.assertNotEqual(r.head(), w.head())
  887. class BuildRepoRootTests(TestCase):
  888. """Tests that build on-disk repos from scratch.
  889. Repos live in a temp dir and are torn down after each test. They start with
  890. a single commit in master having single file named 'a'.
  891. """
  892. def get_repo_dir(self):
  893. return os.path.join(tempfile.mkdtemp(), "test")
  894. def setUp(self) -> None:
  895. super().setUp()
  896. self._repo_dir = self.get_repo_dir()
  897. os.makedirs(self._repo_dir)
  898. r = self._repo = Repo.init(self._repo_dir)
  899. self.addCleanup(tear_down_repo, r)
  900. self.assertFalse(r.bare)
  901. self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD"))
  902. self.assertRaises(KeyError, lambda: r.refs[b"refs/heads/master"])
  903. with open(os.path.join(r.path, "a"), "wb") as f:
  904. f.write(b"file contents")
  905. r.stage(["a"])
  906. commit_sha = r.do_commit(
  907. b"msg",
  908. committer=b"Test Committer <test@nodomain.com>",
  909. author=b"Test Author <test@nodomain.com>",
  910. commit_timestamp=12345,
  911. commit_timezone=0,
  912. author_timestamp=12345,
  913. author_timezone=0,
  914. )
  915. self.assertEqual([], r[commit_sha].parents)
  916. self._root_commit = commit_sha
  917. def test_get_shallow(self) -> None:
  918. self.assertEqual(set(), self._repo.get_shallow())
  919. with open(os.path.join(self._repo.path, ".git", "shallow"), "wb") as f:
  920. f.write(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097\n")
  921. self.assertEqual(
  922. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  923. self._repo.get_shallow(),
  924. )
  925. def test_update_shallow(self) -> None:
  926. self._repo.update_shallow(None, None) # no op
  927. self.assertEqual(set(), self._repo.get_shallow())
  928. self._repo.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None)
  929. self.assertEqual(
  930. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  931. self._repo.get_shallow(),
  932. )
  933. self._repo.update_shallow(
  934. [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"],
  935. [b"f9e39b120c68182a4ba35349f832d0e4e61f485c"],
  936. )
  937. self.assertEqual(
  938. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  939. self._repo.get_shallow(),
  940. )
  941. self._repo.update_shallow(None, [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"])
  942. self.assertEqual(set(), self._repo.get_shallow())
  943. self.assertEqual(
  944. False,
  945. os.path.exists(os.path.join(self._repo.controldir(), "shallow")),
  946. )
  947. def test_build_repo(self) -> None:
  948. r = self._repo
  949. self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD"))
  950. self.assertEqual(self._root_commit, r.refs[b"refs/heads/master"])
  951. expected_blob = objects.Blob.from_string(b"file contents")
  952. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  953. actual_commit = r[self._root_commit]
  954. self.assertEqual(b"msg", actual_commit.message)
  955. def test_commit_modified(self) -> None:
  956. r = self._repo
  957. with open(os.path.join(r.path, "a"), "wb") as f:
  958. f.write(b"new contents")
  959. r.stage(["a"])
  960. commit_sha = r.do_commit(
  961. b"modified a",
  962. committer=b"Test Committer <test@nodomain.com>",
  963. author=b"Test Author <test@nodomain.com>",
  964. commit_timestamp=12395,
  965. commit_timezone=0,
  966. author_timestamp=12395,
  967. author_timezone=0,
  968. )
  969. self.assertEqual([self._root_commit], r[commit_sha].parents)
  970. a_mode, a_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"a")
  971. self.assertEqual(stat.S_IFREG | 0o644, a_mode)
  972. self.assertEqual(b"new contents", r[a_id].data)
  973. @skipIf(not getattr(os, "symlink", None), "Requires symlink support")
  974. def test_commit_symlink(self) -> None:
  975. r = self._repo
  976. os.symlink("a", os.path.join(r.path, "b"))
  977. r.stage(["a", "b"])
  978. commit_sha = r.do_commit(
  979. b"Symlink b",
  980. committer=b"Test Committer <test@nodomain.com>",
  981. author=b"Test Author <test@nodomain.com>",
  982. commit_timestamp=12395,
  983. commit_timezone=0,
  984. author_timestamp=12395,
  985. author_timezone=0,
  986. )
  987. self.assertEqual([self._root_commit], r[commit_sha].parents)
  988. b_mode, b_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"b")
  989. self.assertTrue(stat.S_ISLNK(b_mode))
  990. self.assertEqual(b"a", r[b_id].data)
  991. def test_commit_merge_heads_file(self) -> None:
  992. tmp_dir = tempfile.mkdtemp()
  993. self.addCleanup(shutil.rmtree, tmp_dir)
  994. r = Repo.init(tmp_dir)
  995. with open(os.path.join(r.path, "a"), "w") as f:
  996. f.write("initial text")
  997. c1 = r.do_commit(
  998. b"initial commit",
  999. committer=b"Test Committer <test@nodomain.com>",
  1000. author=b"Test Author <test@nodomain.com>",
  1001. commit_timestamp=12395,
  1002. commit_timezone=0,
  1003. author_timestamp=12395,
  1004. author_timezone=0,
  1005. )
  1006. with open(os.path.join(r.path, "a"), "w") as f:
  1007. f.write("merged text")
  1008. with open(os.path.join(r.path, ".git", "MERGE_HEAD"), "w") as f:
  1009. f.write("c27a2d21dd136312d7fa9e8baabb82561a1727d0\n")
  1010. r.stage(["a"])
  1011. commit_sha = r.do_commit(
  1012. b"deleted a",
  1013. committer=b"Test Committer <test@nodomain.com>",
  1014. author=b"Test Author <test@nodomain.com>",
  1015. commit_timestamp=12395,
  1016. commit_timezone=0,
  1017. author_timestamp=12395,
  1018. author_timezone=0,
  1019. )
  1020. self.assertEqual(
  1021. [c1, b"c27a2d21dd136312d7fa9e8baabb82561a1727d0"],
  1022. r[commit_sha].parents,
  1023. )
  1024. def test_commit_deleted(self) -> None:
  1025. r = self._repo
  1026. os.remove(os.path.join(r.path, "a"))
  1027. r.stage(["a"])
  1028. commit_sha = r.do_commit(
  1029. b"deleted a",
  1030. committer=b"Test Committer <test@nodomain.com>",
  1031. author=b"Test Author <test@nodomain.com>",
  1032. commit_timestamp=12395,
  1033. commit_timezone=0,
  1034. author_timestamp=12395,
  1035. author_timezone=0,
  1036. )
  1037. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1038. self.assertEqual([], list(r.open_index()))
  1039. tree = r[r[commit_sha].tree]
  1040. self.assertEqual([], list(tree.iteritems()))
  1041. def test_commit_follows(self) -> None:
  1042. r = self._repo
  1043. r.refs.set_symbolic_ref(b"HEAD", b"refs/heads/bla")
  1044. commit_sha = r.do_commit(
  1045. b"commit with strange character",
  1046. committer=b"Test Committer <test@nodomain.com>",
  1047. author=b"Test Author <test@nodomain.com>",
  1048. commit_timestamp=12395,
  1049. commit_timezone=0,
  1050. author_timestamp=12395,
  1051. author_timezone=0,
  1052. ref=b"HEAD",
  1053. )
  1054. self.assertEqual(commit_sha, r[b"refs/heads/bla"].id)
  1055. def test_commit_encoding(self) -> None:
  1056. r = self._repo
  1057. commit_sha = r.do_commit(
  1058. b"commit with strange character \xee",
  1059. committer=b"Test Committer <test@nodomain.com>",
  1060. author=b"Test Author <test@nodomain.com>",
  1061. commit_timestamp=12395,
  1062. commit_timezone=0,
  1063. author_timestamp=12395,
  1064. author_timezone=0,
  1065. encoding=b"iso8859-1",
  1066. )
  1067. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  1068. def test_compression_level(self) -> None:
  1069. r = self._repo
  1070. c = r.get_config()
  1071. c.set(("core",), "compression", "3")
  1072. c.set(("core",), "looseCompression", "4")
  1073. c.write_to_path()
  1074. r = Repo(self._repo_dir)
  1075. self.assertEqual(r.object_store.loose_compression_level, 4)
  1076. def test_repositoryformatversion_unsupported(self) -> None:
  1077. r = self._repo
  1078. c = r.get_config()
  1079. c.set(("core",), "repositoryformatversion", "2")
  1080. c.write_to_path()
  1081. self.assertRaises(UnsupportedVersion, Repo, self._repo_dir)
  1082. def test_repositoryformatversion_1(self) -> None:
  1083. r = self._repo
  1084. c = r.get_config()
  1085. c.set(("core",), "repositoryformatversion", "1")
  1086. c.write_to_path()
  1087. Repo(self._repo_dir)
  1088. def test_worktreeconfig_extension(self) -> None:
  1089. r = self._repo
  1090. c = r.get_config()
  1091. c.set(("core",), "repositoryformatversion", "1")
  1092. c.set(("extensions",), "worktreeconfig", True)
  1093. c.write_to_path()
  1094. c = r.get_worktree_config()
  1095. c.set(("user",), "repositoryformatversion", "1")
  1096. c.set((b"user",), b"name", b"Jelmer")
  1097. c.write_to_path()
  1098. cs = r.get_config_stack()
  1099. self.assertEqual(cs.get(("user",), "name"), b"Jelmer")
  1100. def test_worktreeconfig_extension_case(self) -> None:
  1101. """Test that worktree code does not error for alternate case format."""
  1102. r = self._repo
  1103. c = r.get_config()
  1104. c.set(("core",), "repositoryformatversion", "1")
  1105. # Capitalize "Config"
  1106. c.set(("extensions",), "worktreeConfig", True)
  1107. c.write_to_path()
  1108. c = r.get_worktree_config()
  1109. c.set(("user",), "repositoryformatversion", "1")
  1110. c.set((b"user",), b"name", b"Jelmer")
  1111. c.write_to_path()
  1112. # The following line errored before
  1113. # https://github.com/jelmer/dulwich/issues/1285 was addressed
  1114. Repo(self._repo_dir)
  1115. def test_repositoryformatversion_1_extension(self) -> None:
  1116. r = self._repo
  1117. c = r.get_config()
  1118. c.set(("core",), "repositoryformatversion", "1")
  1119. c.set(("extensions",), "unknownextension", True)
  1120. c.write_to_path()
  1121. self.assertRaises(UnsupportedExtension, Repo, self._repo_dir)
  1122. def test_commit_encoding_from_config(self) -> None:
  1123. r = self._repo
  1124. c = r.get_config()
  1125. c.set(("i18n",), "commitEncoding", "iso8859-1")
  1126. c.write_to_path()
  1127. commit_sha = r.do_commit(
  1128. b"commit with strange character \xee",
  1129. committer=b"Test Committer <test@nodomain.com>",
  1130. author=b"Test Author <test@nodomain.com>",
  1131. commit_timestamp=12395,
  1132. commit_timezone=0,
  1133. author_timestamp=12395,
  1134. author_timezone=0,
  1135. )
  1136. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  1137. def test_commit_config_identity(self) -> None:
  1138. # commit falls back to the users' identity if it wasn't specified
  1139. r = self._repo
  1140. c = r.get_config()
  1141. c.set((b"user",), b"name", b"Jelmer")
  1142. c.set((b"user",), b"email", b"jelmer@apache.org")
  1143. c.write_to_path()
  1144. commit_sha = r.do_commit(b"message")
  1145. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1146. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1147. def test_commit_config_identity_strips_than(self) -> None:
  1148. # commit falls back to the users' identity if it wasn't specified,
  1149. # and strips superfluous <>
  1150. r = self._repo
  1151. c = r.get_config()
  1152. c.set((b"user",), b"name", b"Jelmer")
  1153. c.set((b"user",), b"email", b"<jelmer@apache.org>")
  1154. c.write_to_path()
  1155. commit_sha = r.do_commit(b"message")
  1156. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1157. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1158. def test_commit_config_identity_in_memoryrepo(self) -> None:
  1159. # commit falls back to the users' identity if it wasn't specified
  1160. r = MemoryRepo.init_bare([], {})
  1161. c = r.get_config()
  1162. c.set((b"user",), b"name", b"Jelmer")
  1163. c.set((b"user",), b"email", b"jelmer@apache.org")
  1164. commit_sha = r.do_commit(b"message", tree=objects.Tree().id)
  1165. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1166. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1167. def test_commit_config_identity_from_env(self) -> None:
  1168. # commit falls back to the users' identity if it wasn't specified
  1169. self.overrideEnv("GIT_COMMITTER_NAME", "joe")
  1170. self.overrideEnv("GIT_COMMITTER_EMAIL", "joe@example.com")
  1171. r = self._repo
  1172. c = r.get_config()
  1173. c.set((b"user",), b"name", b"Jelmer")
  1174. c.set((b"user",), b"email", b"jelmer@apache.org")
  1175. c.write_to_path()
  1176. commit_sha = r.do_commit(b"message")
  1177. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1178. self.assertEqual(b"joe <joe@example.com>", r[commit_sha].committer)
  1179. def test_commit_fail_ref(self) -> None:
  1180. r = self._repo
  1181. def set_if_equals(name, old_ref, new_ref, **kwargs) -> bool:
  1182. return False
  1183. r.refs.set_if_equals = set_if_equals
  1184. def add_if_new(name, new_ref, **kwargs) -> None:
  1185. self.fail("Unexpected call to add_if_new")
  1186. r.refs.add_if_new = add_if_new
  1187. old_shas = set(r.object_store)
  1188. self.assertRaises(
  1189. errors.CommitError,
  1190. r.do_commit,
  1191. b"failed commit",
  1192. committer=b"Test Committer <test@nodomain.com>",
  1193. author=b"Test Author <test@nodomain.com>",
  1194. commit_timestamp=12345,
  1195. commit_timezone=0,
  1196. author_timestamp=12345,
  1197. author_timezone=0,
  1198. )
  1199. new_shas = set(r.object_store) - old_shas
  1200. self.assertEqual(1, len(new_shas))
  1201. # Check that the new commit (now garbage) was added.
  1202. new_commit = r[new_shas.pop()]
  1203. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1204. self.assertEqual(b"failed commit", new_commit.message)
  1205. def test_commit_branch(self) -> None:
  1206. r = self._repo
  1207. commit_sha = r.do_commit(
  1208. b"commit to branch",
  1209. committer=b"Test Committer <test@nodomain.com>",
  1210. author=b"Test Author <test@nodomain.com>",
  1211. commit_timestamp=12395,
  1212. commit_timezone=0,
  1213. author_timestamp=12395,
  1214. author_timezone=0,
  1215. ref=b"refs/heads/new_branch",
  1216. )
  1217. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  1218. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  1219. self.assertEqual([], r[commit_sha].parents)
  1220. self.assertIn(b"refs/heads/new_branch", r)
  1221. new_branch_head = commit_sha
  1222. commit_sha = r.do_commit(
  1223. b"commit to branch 2",
  1224. committer=b"Test Committer <test@nodomain.com>",
  1225. author=b"Test Author <test@nodomain.com>",
  1226. commit_timestamp=12395,
  1227. commit_timezone=0,
  1228. author_timestamp=12395,
  1229. author_timezone=0,
  1230. ref=b"refs/heads/new_branch",
  1231. )
  1232. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  1233. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  1234. self.assertEqual([new_branch_head], r[commit_sha].parents)
  1235. def test_commit_merge_heads(self) -> None:
  1236. r = self._repo
  1237. merge_1 = r.do_commit(
  1238. b"commit to branch 2",
  1239. committer=b"Test Committer <test@nodomain.com>",
  1240. author=b"Test Author <test@nodomain.com>",
  1241. commit_timestamp=12395,
  1242. commit_timezone=0,
  1243. author_timestamp=12395,
  1244. author_timezone=0,
  1245. ref=b"refs/heads/new_branch",
  1246. )
  1247. commit_sha = r.do_commit(
  1248. b"commit with merge",
  1249. committer=b"Test Committer <test@nodomain.com>",
  1250. author=b"Test Author <test@nodomain.com>",
  1251. commit_timestamp=12395,
  1252. commit_timezone=0,
  1253. author_timestamp=12395,
  1254. author_timezone=0,
  1255. merge_heads=[merge_1],
  1256. )
  1257. self.assertEqual([self._root_commit, merge_1], r[commit_sha].parents)
  1258. def test_commit_dangling_commit(self) -> None:
  1259. r = self._repo
  1260. old_shas = set(r.object_store)
  1261. old_refs = r.get_refs()
  1262. commit_sha = r.do_commit(
  1263. b"commit with no ref",
  1264. committer=b"Test Committer <test@nodomain.com>",
  1265. author=b"Test Author <test@nodomain.com>",
  1266. commit_timestamp=12395,
  1267. commit_timezone=0,
  1268. author_timestamp=12395,
  1269. author_timezone=0,
  1270. ref=None,
  1271. )
  1272. new_shas = set(r.object_store) - old_shas
  1273. # New sha is added, but no new refs
  1274. self.assertEqual(1, len(new_shas))
  1275. new_commit = r[new_shas.pop()]
  1276. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1277. self.assertEqual([], r[commit_sha].parents)
  1278. self.assertEqual(old_refs, r.get_refs())
  1279. def test_commit_dangling_commit_with_parents(self) -> None:
  1280. r = self._repo
  1281. old_shas = set(r.object_store)
  1282. old_refs = r.get_refs()
  1283. commit_sha = r.do_commit(
  1284. b"commit with no ref",
  1285. committer=b"Test Committer <test@nodomain.com>",
  1286. author=b"Test Author <test@nodomain.com>",
  1287. commit_timestamp=12395,
  1288. commit_timezone=0,
  1289. author_timestamp=12395,
  1290. author_timezone=0,
  1291. ref=None,
  1292. merge_heads=[self._root_commit],
  1293. )
  1294. new_shas = set(r.object_store) - old_shas
  1295. # New sha is added, but no new refs
  1296. self.assertEqual(1, len(new_shas))
  1297. new_commit = r[new_shas.pop()]
  1298. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1299. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1300. self.assertEqual(old_refs, r.get_refs())
  1301. def test_stage_absolute(self) -> None:
  1302. r = self._repo
  1303. os.remove(os.path.join(r.path, "a"))
  1304. self.assertRaises(ValueError, r.stage, [os.path.join(r.path, "a")])
  1305. def test_stage_deleted(self) -> None:
  1306. r = self._repo
  1307. os.remove(os.path.join(r.path, "a"))
  1308. r.stage(["a"])
  1309. r.stage(["a"]) # double-stage a deleted path
  1310. self.assertEqual([], list(r.open_index()))
  1311. def test_stage_directory(self) -> None:
  1312. r = self._repo
  1313. os.mkdir(os.path.join(r.path, "c"))
  1314. r.stage(["c"])
  1315. self.assertEqual([b"a"], list(r.open_index()))
  1316. def test_stage_submodule(self) -> None:
  1317. r = self._repo
  1318. s = Repo.init(os.path.join(r.path, "sub"), mkdir=True)
  1319. s.do_commit(b"message")
  1320. r.stage(["sub"])
  1321. self.assertEqual([b"a", b"sub"], list(r.open_index()))
  1322. def test_unstage_midify_file_with_dir(self) -> None:
  1323. os.mkdir(os.path.join(self._repo.path, "new_dir"))
  1324. full_path = os.path.join(self._repo.path, "new_dir", "foo")
  1325. with open(full_path, "w") as f:
  1326. f.write("hello")
  1327. porcelain.add(self._repo, paths=[full_path])
  1328. porcelain.commit(
  1329. self._repo,
  1330. message=b"unitest",
  1331. committer=b"Jane <jane@example.com>",
  1332. author=b"John <john@example.com>",
  1333. )
  1334. with open(full_path, "a") as f:
  1335. f.write("something new")
  1336. self._repo.unstage(["new_dir/foo"])
  1337. status = list(porcelain.status(self._repo))
  1338. self.assertEqual(
  1339. [{"add": [], "delete": [], "modify": []}, [b"new_dir/foo"], []], status
  1340. )
  1341. def test_unstage_while_no_commit(self) -> None:
  1342. file = "foo"
  1343. full_path = os.path.join(self._repo.path, file)
  1344. with open(full_path, "w") as f:
  1345. f.write("hello")
  1346. porcelain.add(self._repo, paths=[full_path])
  1347. self._repo.unstage([file])
  1348. status = list(porcelain.status(self._repo))
  1349. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["foo"]], status)
  1350. def test_unstage_add_file(self) -> None:
  1351. file = "foo"
  1352. full_path = os.path.join(self._repo.path, file)
  1353. porcelain.commit(
  1354. self._repo,
  1355. message=b"unitest",
  1356. committer=b"Jane <jane@example.com>",
  1357. author=b"John <john@example.com>",
  1358. )
  1359. with open(full_path, "w") as f:
  1360. f.write("hello")
  1361. porcelain.add(self._repo, paths=[full_path])
  1362. self._repo.unstage([file])
  1363. status = list(porcelain.status(self._repo))
  1364. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["foo"]], status)
  1365. def test_unstage_modify_file(self) -> None:
  1366. file = "foo"
  1367. full_path = os.path.join(self._repo.path, file)
  1368. with open(full_path, "w") as f:
  1369. f.write("hello")
  1370. porcelain.add(self._repo, paths=[full_path])
  1371. porcelain.commit(
  1372. self._repo,
  1373. message=b"unitest",
  1374. committer=b"Jane <jane@example.com>",
  1375. author=b"John <john@example.com>",
  1376. )
  1377. with open(full_path, "a") as f:
  1378. f.write("broken")
  1379. porcelain.add(self._repo, paths=[full_path])
  1380. self._repo.unstage([file])
  1381. status = list(porcelain.status(self._repo))
  1382. self.assertEqual(
  1383. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  1384. )
  1385. def test_unstage_remove_file(self) -> None:
  1386. file = "foo"
  1387. full_path = os.path.join(self._repo.path, file)
  1388. with open(full_path, "w") as f:
  1389. f.write("hello")
  1390. porcelain.add(self._repo, paths=[full_path])
  1391. porcelain.commit(
  1392. self._repo,
  1393. message=b"unitest",
  1394. committer=b"Jane <jane@example.com>",
  1395. author=b"John <john@example.com>",
  1396. )
  1397. os.remove(full_path)
  1398. self._repo.unstage([file])
  1399. status = list(porcelain.status(self._repo))
  1400. self.assertEqual(
  1401. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  1402. )
  1403. def test_reset_index(self) -> None:
  1404. r = self._repo
  1405. with open(os.path.join(r.path, "a"), "wb") as f:
  1406. f.write(b"changed")
  1407. with open(os.path.join(r.path, "b"), "wb") as f:
  1408. f.write(b"added")
  1409. r.stage(["a", "b"])
  1410. status = list(porcelain.status(self._repo))
  1411. self.assertEqual(
  1412. [{"add": [b"b"], "delete": [], "modify": [b"a"]}, [], []], status
  1413. )
  1414. r.reset_index()
  1415. status = list(porcelain.status(self._repo))
  1416. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["b"]], status)
  1417. @skipIf(
  1418. sys.platform in ("win32", "darwin"),
  1419. "tries to implicitly decode as utf8",
  1420. )
  1421. def test_commit_no_encode_decode(self) -> None:
  1422. r = self._repo
  1423. repo_path_bytes = os.fsencode(r.path)
  1424. encodings = ("utf8", "latin1")
  1425. names = ["À".encode(encoding) for encoding in encodings]
  1426. for name, encoding in zip(names, encodings):
  1427. full_path = os.path.join(repo_path_bytes, name)
  1428. with open(full_path, "wb") as f:
  1429. f.write(encoding.encode("ascii"))
  1430. # These files are break tear_down_repo, so cleanup these files
  1431. # ourselves.
  1432. self.addCleanup(os.remove, full_path)
  1433. r.stage(names)
  1434. commit_sha = r.do_commit(
  1435. b"Files with different encodings",
  1436. committer=b"Test Committer <test@nodomain.com>",
  1437. author=b"Test Author <test@nodomain.com>",
  1438. commit_timestamp=12395,
  1439. commit_timezone=0,
  1440. author_timestamp=12395,
  1441. author_timezone=0,
  1442. ref=None,
  1443. merge_heads=[self._root_commit],
  1444. )
  1445. for name, encoding in zip(names, encodings):
  1446. mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name)
  1447. self.assertEqual(stat.S_IFREG | 0o644, mode)
  1448. self.assertEqual(encoding.encode("ascii"), r[id].data)
  1449. def test_discover_intended(self) -> None:
  1450. path = os.path.join(self._repo_dir, "b/c")
  1451. r = Repo.discover(path)
  1452. self.assertEqual(r.head(), self._repo.head())
  1453. def test_discover_isrepo(self) -> None:
  1454. r = Repo.discover(self._repo_dir)
  1455. self.assertEqual(r.head(), self._repo.head())
  1456. def test_discover_notrepo(self) -> None:
  1457. with self.assertRaises(NotGitRepository):
  1458. Repo.discover("/")
  1459. class CheckUserIdentityTests(TestCase):
  1460. def test_valid(self) -> None:
  1461. check_user_identity(b"Me <me@example.com>")
  1462. def test_invalid(self) -> None:
  1463. self.assertRaises(InvalidUserIdentity, check_user_identity, b"No Email")
  1464. self.assertRaises(
  1465. InvalidUserIdentity, check_user_identity, b"Fullname <missing"
  1466. )
  1467. self.assertRaises(
  1468. InvalidUserIdentity, check_user_identity, b"Fullname missing>"
  1469. )
  1470. self.assertRaises(
  1471. InvalidUserIdentity, check_user_identity, b"Fullname >order<>"
  1472. )
  1473. self.assertRaises(
  1474. InvalidUserIdentity, check_user_identity, b"Contains\0null byte <>"
  1475. )
  1476. self.assertRaises(
  1477. InvalidUserIdentity, check_user_identity, b"Contains\nnewline byte <>"
  1478. )
  1479. class RepoConfigIncludeIfTests(TestCase):
  1480. """Test includeIf functionality in repository config loading."""
  1481. def test_repo_config_includeif_gitdir(self) -> None:
  1482. """Test that includeIf gitdir conditions work when loading repo config."""
  1483. import tempfile
  1484. from dulwich.repo import Repo
  1485. with tempfile.TemporaryDirectory() as tmpdir:
  1486. # Create a repository
  1487. repo_path = os.path.join(tmpdir, "myrepo")
  1488. r = Repo.init(repo_path, mkdir=True)
  1489. # Use realpath to resolve any symlinks (important on macOS)
  1490. repo_path = os.path.realpath(repo_path)
  1491. # Create an included config file
  1492. included_path = os.path.join(tmpdir, "work.config")
  1493. with open(included_path, "wb") as f:
  1494. f.write(b"[user]\n email = work@example.com\n")
  1495. # Add includeIf to the repo config
  1496. config_path = os.path.join(repo_path, ".git", "config")
  1497. with open(config_path, "ab") as f:
  1498. f.write(f'\n[includeIf "gitdir:{repo_path}/.git/"]\n'.encode())
  1499. escaped_path = included_path.replace("\\", "\\\\")
  1500. f.write(f" path = {escaped_path}\n".encode())
  1501. # Close and reopen to reload config
  1502. r.close()
  1503. r = Repo(repo_path)
  1504. # Check if include was processed
  1505. config = r.get_config()
  1506. self.assertEqual(b"work@example.com", config.get((b"user",), b"email"))
  1507. r.close()
  1508. def test_repo_config_includeif_gitdir_pattern(self) -> None:
  1509. """Test includeIf gitdir pattern matching in repository config."""
  1510. import tempfile
  1511. from dulwich.repo import Repo
  1512. with tempfile.TemporaryDirectory() as tmpdir:
  1513. # Create a repository under "work" directory
  1514. work_dir = os.path.join(tmpdir, "work", "project1")
  1515. os.makedirs(os.path.dirname(work_dir), exist_ok=True)
  1516. r = Repo.init(work_dir, mkdir=True)
  1517. # Create an included config file
  1518. included_path = os.path.join(tmpdir, "work.config")
  1519. with open(included_path, "wb") as f:
  1520. f.write(b"[user]\n email = work@company.com\n")
  1521. # Add includeIf with pattern to the repo config
  1522. config_path = os.path.join(work_dir, ".git", "config")
  1523. with open(config_path, "ab") as f:
  1524. # Use a pattern that will match paths containing /work/
  1525. f.write(b'\n[includeIf "gitdir:**/work/**"]\n')
  1526. escaped_path = included_path.replace("\\", "\\\\")
  1527. f.write(f" path = {escaped_path}\n".encode())
  1528. # Close and reopen to reload config
  1529. r.close()
  1530. r = Repo(work_dir)
  1531. # Check if include was processed
  1532. config = r.get_config()
  1533. self.assertEqual(b"work@company.com", config.get((b"user",), b"email"))
  1534. r.close()
  1535. def test_repo_config_includeif_no_match(self) -> None:
  1536. """Test that includeIf doesn't include when condition doesn't match."""
  1537. import tempfile
  1538. from dulwich.repo import Repo
  1539. with tempfile.TemporaryDirectory() as tmpdir:
  1540. # Create a repository
  1541. repo_path = os.path.join(tmpdir, "personal", "project")
  1542. os.makedirs(os.path.dirname(repo_path), exist_ok=True)
  1543. r = Repo.init(repo_path, mkdir=True)
  1544. # Create an included config file
  1545. included_path = os.path.join(tmpdir, "work.config")
  1546. with open(included_path, "wb") as f:
  1547. f.write(b"[user]\n email = work@company.com\n")
  1548. # Add includeIf that won't match
  1549. config_path = os.path.join(repo_path, ".git", "config")
  1550. with open(config_path, "ab") as f:
  1551. f.write(b'\n[includeIf "gitdir:**/work/**"]\n')
  1552. escaped_path = included_path.replace("\\", "\\\\")
  1553. f.write(f" path = {escaped_path}\n".encode())
  1554. # Close and reopen to reload config
  1555. r.close()
  1556. r = Repo(repo_path)
  1557. # Check that include was NOT processed
  1558. config = r.get_config()
  1559. with self.assertRaises(KeyError):
  1560. config.get((b"user",), b"email")
  1561. r.close()
  1562. def test_bare_repo_config_includeif(self) -> None:
  1563. """Test includeIf in bare repository."""
  1564. import tempfile
  1565. from dulwich.repo import Repo
  1566. with tempfile.TemporaryDirectory() as tmpdir:
  1567. # Create a bare repository
  1568. repo_path = os.path.join(tmpdir, "bare.git")
  1569. r = Repo.init_bare(repo_path, mkdir=True)
  1570. # Use realpath to resolve any symlinks (important on macOS)
  1571. repo_path = os.path.realpath(repo_path)
  1572. # Create an included config file
  1573. included_path = os.path.join(tmpdir, "server.config")
  1574. with open(included_path, "wb") as f:
  1575. f.write(b"[receive]\n denyNonFastForwards = true\n")
  1576. # Add includeIf to the repo config
  1577. config_path = os.path.join(repo_path, "config")
  1578. with open(config_path, "ab") as f:
  1579. f.write(f'\n[includeIf "gitdir:{repo_path}/"]\n'.encode())
  1580. escaped_path = included_path.replace("\\", "\\\\")
  1581. f.write(f" path = {escaped_path}\n".encode())
  1582. # Close and reopen to reload config
  1583. r.close()
  1584. r = Repo(repo_path)
  1585. # Check if include was processed
  1586. config = r.get_config()
  1587. self.assertEqual(b"true", config.get((b"receive",), b"denyNonFastForwards"))
  1588. r.close()
  1589. def test_repo_config_includeif_hasconfig(self) -> None:
  1590. """Test includeIf hasconfig conditions in repository config."""
  1591. import tempfile
  1592. from dulwich.repo import Repo
  1593. with tempfile.TemporaryDirectory() as tmpdir:
  1594. # Create a repository
  1595. repo_path = os.path.join(tmpdir, "myrepo")
  1596. r = Repo.init(repo_path, mkdir=True)
  1597. # Create an included config file
  1598. included_path = os.path.join(tmpdir, "work.config")
  1599. with open(included_path, "wb") as f:
  1600. f.write(b"[user]\n name = WorkUser\n")
  1601. # Add a remote and includeIf hasconfig to the repo config
  1602. config_path = os.path.join(repo_path, ".git", "config")
  1603. with open(config_path, "ab") as f:
  1604. f.write(b'\n[remote "origin"]\n')
  1605. f.write(b" url = ssh://org-work@github.com/company/project\n")
  1606. f.write(
  1607. b'[includeIf "hasconfig:remote.*.url:ssh://org-*@github.com/**"]\n'
  1608. )
  1609. escaped_path = included_path.replace("\\", "\\\\")
  1610. f.write(f" path = {escaped_path}\n".encode())
  1611. # Close and reopen to reload config
  1612. r.close()
  1613. r = Repo(repo_path)
  1614. # Check if include was processed
  1615. config = r.get_config()
  1616. self.assertEqual(b"WorkUser", config.get((b"user",), b"name"))
  1617. r.close()
  1618. def test_repo_config_includeif_onbranch(self) -> None:
  1619. """Test includeIf onbranch conditions in repository config."""
  1620. import tempfile
  1621. from dulwich.repo import Repo
  1622. with tempfile.TemporaryDirectory() as tmpdir:
  1623. # Create a repository
  1624. repo_path = os.path.join(tmpdir, "myrepo")
  1625. r = Repo.init(repo_path, mkdir=True)
  1626. # Create HEAD pointing to main branch
  1627. refs_heads_dir = os.path.join(repo_path, ".git", "refs", "heads")
  1628. os.makedirs(refs_heads_dir, exist_ok=True)
  1629. main_ref_path = os.path.join(refs_heads_dir, "main")
  1630. with open(main_ref_path, "wb") as f:
  1631. f.write(b"0123456789012345678901234567890123456789\n")
  1632. head_path = os.path.join(repo_path, ".git", "HEAD")
  1633. with open(head_path, "wb") as f:
  1634. f.write(b"ref: refs/heads/main\n")
  1635. # Create an included config file
  1636. included_path = os.path.join(tmpdir, "main.config")
  1637. with open(included_path, "wb") as f:
  1638. f.write(b"[core]\n autocrlf = true\n")
  1639. # Add includeIf onbranch to the repo config
  1640. config_path = os.path.join(repo_path, ".git", "config")
  1641. with open(config_path, "ab") as f:
  1642. f.write(b'\n[includeIf "onbranch:main"]\n')
  1643. escaped_path = included_path.replace("\\", "\\\\")
  1644. f.write(f" path = {escaped_path}\n".encode())
  1645. # Close and reopen to reload config
  1646. r.close()
  1647. r = Repo(repo_path)
  1648. # Check if include was processed
  1649. config = r.get_config()
  1650. self.assertEqual(b"true", config.get((b"core",), b"autocrlf"))
  1651. r.close()