test_repository.py 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  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 published 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 time
  30. import warnings
  31. from dulwich import errors, objects, porcelain
  32. from dulwich.config import Config
  33. from dulwich.errors import NotGitRepository
  34. from dulwich.object_store import tree_lookup_path
  35. from dulwich.repo import (
  36. InvalidUserIdentity,
  37. MemoryRepo,
  38. Repo,
  39. UnsupportedExtension,
  40. UnsupportedVersion,
  41. check_user_identity,
  42. )
  43. from dulwich.tests.utils import open_repo, setup_warning_catcher, tear_down_repo
  44. from . import TestCase, skipIf
  45. missing_sha = b"b91fa4d900e17e99b433218e988c4eb4a3e9a097"
  46. class CreateRepositoryTests(TestCase):
  47. def assertFileContentsEqual(self, expected, repo, path) -> None:
  48. f = repo.get_named_file(path)
  49. if not f:
  50. self.assertEqual(expected, None)
  51. else:
  52. with f:
  53. self.assertEqual(expected, f.read())
  54. def _check_repo_contents(self, repo, expect_bare) -> None:
  55. self.assertEqual(expect_bare, repo.bare)
  56. self.assertFileContentsEqual(b"Unnamed repository", repo, "description")
  57. self.assertFileContentsEqual(b"", repo, os.path.join("info", "exclude"))
  58. self.assertFileContentsEqual(None, repo, "nonexistent file")
  59. barestr = b"bare = " + str(expect_bare).lower().encode("ascii")
  60. with repo.get_named_file("config") as f:
  61. config_text = f.read()
  62. self.assertIn(barestr, config_text, f"{config_text!r}")
  63. expect_filemode = sys.platform != "win32"
  64. barestr = b"filemode = " + str(expect_filemode).lower().encode("ascii")
  65. with repo.get_named_file("config") as f:
  66. config_text = f.read()
  67. self.assertIn(barestr, config_text, f"{config_text!r}")
  68. if isinstance(repo, Repo):
  69. expected_mode = "0o100644" if expect_filemode else "0o100666"
  70. expected = {
  71. "HEAD": expected_mode,
  72. "config": expected_mode,
  73. "description": expected_mode,
  74. }
  75. actual = {
  76. f[len(repo._controldir) + 1 :]: oct(os.stat(f).st_mode)
  77. for f in glob.glob(os.path.join(repo._controldir, "*"))
  78. if os.path.isfile(f)
  79. }
  80. self.assertEqual(expected, actual)
  81. def test_create_memory(self) -> None:
  82. repo = MemoryRepo.init_bare([], {})
  83. self._check_repo_contents(repo, True)
  84. def test_create_disk_bare(self) -> None:
  85. tmp_dir = tempfile.mkdtemp()
  86. self.addCleanup(shutil.rmtree, tmp_dir)
  87. repo = Repo.init_bare(tmp_dir)
  88. self.assertEqual(tmp_dir, repo._controldir)
  89. self._check_repo_contents(repo, True)
  90. def test_create_disk_non_bare(self) -> None:
  91. tmp_dir = tempfile.mkdtemp()
  92. self.addCleanup(shutil.rmtree, tmp_dir)
  93. repo = Repo.init(tmp_dir)
  94. self.assertEqual(os.path.join(tmp_dir, ".git"), repo._controldir)
  95. self._check_repo_contents(repo, False)
  96. def test_create_disk_non_bare_mkdir(self) -> None:
  97. tmp_dir = tempfile.mkdtemp()
  98. target_dir = os.path.join(tmp_dir, "target")
  99. self.addCleanup(shutil.rmtree, tmp_dir)
  100. repo = Repo.init(target_dir, mkdir=True)
  101. self.assertEqual(os.path.join(target_dir, ".git"), repo._controldir)
  102. self._check_repo_contents(repo, False)
  103. def test_create_disk_bare_mkdir(self) -> None:
  104. tmp_dir = tempfile.mkdtemp()
  105. target_dir = os.path.join(tmp_dir, "target")
  106. self.addCleanup(shutil.rmtree, tmp_dir)
  107. repo = Repo.init_bare(target_dir, mkdir=True)
  108. self.assertEqual(target_dir, repo._controldir)
  109. self._check_repo_contents(repo, True)
  110. def test_create_disk_bare_pathlib(self) -> None:
  111. from pathlib import Path
  112. tmp_dir = tempfile.mkdtemp()
  113. self.addCleanup(shutil.rmtree, tmp_dir)
  114. repo_path = Path(tmp_dir)
  115. repo = Repo.init_bare(repo_path)
  116. self.assertEqual(tmp_dir, repo._controldir)
  117. self._check_repo_contents(repo, True)
  118. # Test that refpath works with pathlib
  119. ref_path = repo.refs.refpath(b"refs/heads/master")
  120. self.assertTrue(isinstance(ref_path, bytes))
  121. expected_path = os.path.join(tmp_dir.encode(), b"refs", b"heads", b"master")
  122. self.assertEqual(ref_path, expected_path)
  123. def test_create_disk_non_bare_pathlib(self) -> None:
  124. from pathlib import Path
  125. tmp_dir = tempfile.mkdtemp()
  126. self.addCleanup(shutil.rmtree, tmp_dir)
  127. repo_path = Path(tmp_dir)
  128. repo = Repo.init(repo_path)
  129. self.assertEqual(os.path.join(tmp_dir, ".git"), repo._controldir)
  130. self._check_repo_contents(repo, False)
  131. def test_open_repo_pathlib(self) -> None:
  132. from pathlib import Path
  133. tmp_dir = tempfile.mkdtemp()
  134. self.addCleanup(shutil.rmtree, tmp_dir)
  135. # First create a repo
  136. repo = Repo.init_bare(tmp_dir)
  137. repo.close()
  138. # Now open it with pathlib
  139. repo_path = Path(tmp_dir)
  140. repo2 = Repo(repo_path)
  141. self.assertEqual(tmp_dir, repo2._controldir)
  142. self.assertTrue(repo2.bare)
  143. repo2.close()
  144. def test_create_disk_bare_mkdir_pathlib(self) -> None:
  145. from pathlib import Path
  146. tmp_dir = tempfile.mkdtemp()
  147. target_path = Path(tmp_dir) / "target"
  148. self.addCleanup(shutil.rmtree, tmp_dir)
  149. repo = Repo.init_bare(target_path, mkdir=True)
  150. self.assertEqual(str(target_path), repo._controldir)
  151. self._check_repo_contents(repo, True)
  152. class MemoryRepoTests(TestCase):
  153. def test_set_description(self) -> None:
  154. r = MemoryRepo.init_bare([], {})
  155. description = b"Some description"
  156. r.set_description(description)
  157. self.assertEqual(description, r.get_description())
  158. def test_pull_into(self) -> None:
  159. r = MemoryRepo.init_bare([], {})
  160. repo = open_repo("a.git")
  161. self.addCleanup(tear_down_repo, repo)
  162. repo.fetch(r)
  163. def test_fetch_from_git_cloned_repo(self) -> None:
  164. """Test fetching from a git-cloned repo into MemoryRepo (issue #1179)."""
  165. import tempfile
  166. from dulwich.client import LocalGitClient
  167. with tempfile.TemporaryDirectory() as tmpdir:
  168. # Create initial repo using dulwich
  169. initial_path = os.path.join(tmpdir, "initial")
  170. initial_repo = Repo.init(initial_path, mkdir=True)
  171. # Create some content
  172. test_file = os.path.join(initial_path, "test.txt")
  173. with open(test_file, "w") as f:
  174. f.write("test content\n")
  175. # Stage and commit using dulwich
  176. initial_repo.get_worktree().stage(["test.txt"])
  177. initial_repo.get_worktree().commit(
  178. message=b"Initial commit\n",
  179. committer=b"Test Committer <test@example.com>",
  180. author=b"Test Author <test@example.com>",
  181. )
  182. # Clone using dulwich
  183. cloned_path = os.path.join(tmpdir, "cloned")
  184. cloned_repo = initial_repo.clone(cloned_path, mkdir=True)
  185. initial_repo.close()
  186. cloned_repo.close()
  187. # Fetch from the cloned repo into MemoryRepo
  188. memory_repo = MemoryRepo()
  189. client = LocalGitClient()
  190. # This should not raise AssertionError
  191. result = client.fetch(cloned_path, memory_repo)
  192. # Verify the fetch worked
  193. self.assertIn(b"HEAD", result.refs)
  194. self.assertIn(b"refs/heads/master", result.refs)
  195. # Verify we can read the fetched objects
  196. head_sha = result.refs[b"HEAD"]
  197. commit = memory_repo[head_sha]
  198. self.assertEqual(commit.message, b"Initial commit\n")
  199. class RepositoryRootTests(TestCase):
  200. def mkdtemp(self):
  201. return tempfile.mkdtemp()
  202. def open_repo(self, name):
  203. temp_dir = self.mkdtemp()
  204. repo = open_repo(name, temp_dir)
  205. self.addCleanup(tear_down_repo, repo)
  206. return repo
  207. def test_simple_props(self) -> None:
  208. r = self.open_repo("a.git")
  209. self.assertEqual(r.controldir(), r.path)
  210. def test_setitem(self) -> None:
  211. r = self.open_repo("a.git")
  212. r[b"refs/tags/foo"] = b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"
  213. self.assertEqual(
  214. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", r[b"refs/tags/foo"].id
  215. )
  216. def test_getitem_unicode(self) -> None:
  217. r = self.open_repo("a.git")
  218. test_keys = [
  219. (b"refs/heads/master", True),
  220. (b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", True),
  221. (b"11" * 19 + b"--", False),
  222. ]
  223. for k, contained in test_keys:
  224. self.assertEqual(k in r, contained)
  225. # Avoid deprecation warning under Py3.2+
  226. if getattr(self, "assertRaisesRegex", None):
  227. assertRaisesRegexp = self.assertRaisesRegex
  228. else:
  229. assertRaisesRegexp = self.assertRaisesRegexp
  230. for k, _ in test_keys:
  231. assertRaisesRegexp(
  232. TypeError,
  233. "'name' must be bytestring, not int",
  234. r.__getitem__,
  235. 12,
  236. )
  237. def test_delitem(self) -> None:
  238. r = self.open_repo("a.git")
  239. del r[b"refs/heads/master"]
  240. self.assertRaises(KeyError, lambda: r[b"refs/heads/master"])
  241. del r[b"HEAD"]
  242. self.assertRaises(KeyError, lambda: r[b"HEAD"])
  243. self.assertRaises(ValueError, r.__delitem__, b"notrefs/foo")
  244. def test_getitem_32_byte_ref(self) -> None:
  245. """Test that accessing a ref name that's 32 bytes long works (issue #2040)."""
  246. r = self.open_repo("a.git")
  247. # Create a ref with exactly 32 bytes
  248. ref_name = b"refs/heads/feat-backend-refactor"
  249. self.assertEqual(len(ref_name), 32)
  250. r[ref_name] = b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"
  251. # This should not raise AssertionError
  252. obj = r[ref_name]
  253. self.assertEqual(obj.id, b"a90fa2d900a17e99b433217e988c4eb4a2e9a097")
  254. def test_get_refs(self) -> None:
  255. r = self.open_repo("a.git")
  256. self.assertEqual(
  257. {
  258. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  259. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  260. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  261. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  262. },
  263. r.get_refs(),
  264. )
  265. def test_head(self) -> None:
  266. r = self.open_repo("a.git")
  267. self.assertEqual(r.head(), b"a90fa2d900a17e99b433217e988c4eb4a2e9a097")
  268. def test_get_object(self) -> None:
  269. r = self.open_repo("a.git")
  270. obj = r.get_object(r.head())
  271. self.assertEqual(obj.type_name, b"commit")
  272. def test_get_object_non_existant(self) -> None:
  273. r = self.open_repo("a.git")
  274. self.assertRaises(KeyError, r.get_object, missing_sha)
  275. def test_contains_object(self) -> None:
  276. r = self.open_repo("a.git")
  277. self.assertIn(r.head(), r)
  278. self.assertNotIn(b"z" * 40, r)
  279. def test_contains_ref(self) -> None:
  280. r = self.open_repo("a.git")
  281. self.assertIn(b"HEAD", r)
  282. def test_get_no_description(self) -> None:
  283. r = self.open_repo("a.git")
  284. self.assertIs(None, r.get_description())
  285. def test_get_description(self) -> None:
  286. r = self.open_repo("a.git")
  287. with open(os.path.join(r.path, "description"), "wb") as f:
  288. f.write(b"Some description")
  289. self.assertEqual(b"Some description", r.get_description())
  290. def test_set_description(self) -> None:
  291. r = self.open_repo("a.git")
  292. description = b"Some description"
  293. r.set_description(description)
  294. self.assertEqual(description, r.get_description())
  295. def test_get_gitattributes(self) -> None:
  296. # Test when no .gitattributes file exists
  297. r = self.open_repo("a.git")
  298. attrs = r.get_gitattributes()
  299. from dulwich.attrs import GitAttributes
  300. self.assertIsInstance(attrs, GitAttributes)
  301. self.assertEqual(len(attrs), 0)
  302. # Create .git/info/attributes file (which is read by get_gitattributes)
  303. info_dir = os.path.join(r.controldir(), "info")
  304. if not os.path.exists(info_dir):
  305. os.makedirs(info_dir)
  306. attrs_path = os.path.join(info_dir, "attributes")
  307. with open(attrs_path, "wb") as f:
  308. f.write(b"*.txt text\n")
  309. f.write(b"*.jpg -text binary\n")
  310. # Test with attributes file
  311. attrs = r.get_gitattributes()
  312. self.assertEqual(len(attrs), 2)
  313. # Test matching
  314. txt_attrs = attrs.match_path(b"file.txt")
  315. self.assertEqual(txt_attrs, {b"text": True})
  316. jpg_attrs = attrs.match_path(b"image.jpg")
  317. self.assertEqual(jpg_attrs, {b"text": False, b"binary": True})
  318. def test_contains_missing(self) -> None:
  319. r = self.open_repo("a.git")
  320. self.assertNotIn(b"bar", r)
  321. def test_get_peeled(self) -> None:
  322. # unpacked ref
  323. r = self.open_repo("a.git")
  324. tag_sha = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a"
  325. self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head())
  326. self.assertEqual(r.get_peeled(b"refs/tags/mytag"), r.head())
  327. # packed ref with cached peeled value
  328. packed_tag_sha = b"b0931cadc54336e78a1d980420e3268903b57a50"
  329. parent_sha = r[r.head()].parents[0]
  330. self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha)
  331. self.assertEqual(r.get_peeled(b"refs/tags/mytag-packed"), parent_sha)
  332. # TODO: add more corner cases to test repo
  333. def test_get_peeled_not_tag(self) -> None:
  334. r = self.open_repo("a.git")
  335. self.assertEqual(r.get_peeled(b"HEAD"), r.head())
  336. def test_get_parents(self) -> None:
  337. r = self.open_repo("a.git")
  338. self.assertEqual(
  339. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  340. r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"),
  341. )
  342. r.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None)
  343. self.assertEqual([], r.get_parents(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"))
  344. def test_get_walker(self) -> None:
  345. r = self.open_repo("a.git")
  346. # include defaults to [r.head()]
  347. self.assertEqual(
  348. [e.commit.id for e in r.get_walker()],
  349. [r.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  350. )
  351. self.assertEqual(
  352. [
  353. e.commit.id
  354. for e in r.get_walker([b"2a72d929692c41d8554c07f6301757ba18a65d91"])
  355. ],
  356. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  357. )
  358. self.assertEqual(
  359. [
  360. e.commit.id
  361. for e in r.get_walker(b"2a72d929692c41d8554c07f6301757ba18a65d91")
  362. ],
  363. [b"2a72d929692c41d8554c07f6301757ba18a65d91"],
  364. )
  365. def assertFilesystemHidden(self, path) -> None:
  366. if sys.platform != "win32":
  367. return
  368. import ctypes
  369. from ctypes.wintypes import DWORD, LPCWSTR
  370. GetFileAttributesW = ctypes.WINFUNCTYPE(DWORD, LPCWSTR)(
  371. ("GetFileAttributesW", ctypes.windll.kernel32)
  372. )
  373. self.assertTrue(2 & GetFileAttributesW(path))
  374. def test_init_existing(self) -> None:
  375. tmp_dir = self.mkdtemp()
  376. self.addCleanup(shutil.rmtree, tmp_dir)
  377. t = Repo.init(tmp_dir)
  378. self.addCleanup(t.close)
  379. self.assertEqual(os.listdir(tmp_dir), [".git"])
  380. self.assertFilesystemHidden(os.path.join(tmp_dir, ".git"))
  381. def test_init_mkdir(self) -> None:
  382. tmp_dir = self.mkdtemp()
  383. self.addCleanup(shutil.rmtree, tmp_dir)
  384. repo_dir = os.path.join(tmp_dir, "a-repo")
  385. t = Repo.init(repo_dir, mkdir=True)
  386. self.addCleanup(t.close)
  387. self.assertEqual(os.listdir(repo_dir), [".git"])
  388. self.assertFilesystemHidden(os.path.join(repo_dir, ".git"))
  389. def test_init_mkdir_unicode(self) -> None:
  390. repo_name = "\xa7"
  391. try:
  392. os.fsencode(repo_name)
  393. except UnicodeEncodeError:
  394. self.skipTest("filesystem lacks unicode support")
  395. tmp_dir = self.mkdtemp()
  396. self.addCleanup(shutil.rmtree, tmp_dir)
  397. repo_dir = os.path.join(tmp_dir, repo_name)
  398. t = Repo.init(repo_dir, mkdir=True)
  399. self.addCleanup(t.close)
  400. self.assertEqual(os.listdir(repo_dir), [".git"])
  401. self.assertFilesystemHidden(os.path.join(repo_dir, ".git"))
  402. def test_init_format(self) -> None:
  403. tmp_dir = self.mkdtemp()
  404. self.addCleanup(shutil.rmtree, tmp_dir)
  405. # Test format 0
  406. t0 = Repo.init(tmp_dir + "0", mkdir=True, format=0)
  407. self.addCleanup(t0.close)
  408. self.assertEqual(t0.get_config().get("core", "repositoryformatversion"), b"0")
  409. # Test format 1
  410. t1 = Repo.init(tmp_dir + "1", mkdir=True, format=1)
  411. self.addCleanup(t1.close)
  412. self.assertEqual(t1.get_config().get("core", "repositoryformatversion"), b"1")
  413. # Test default format
  414. td = Repo.init(tmp_dir + "d", mkdir=True)
  415. self.addCleanup(td.close)
  416. self.assertEqual(td.get_config().get("core", "repositoryformatversion"), b"0")
  417. # Test invalid format
  418. with self.assertRaises(ValueError):
  419. Repo.init(tmp_dir + "bad", mkdir=True, format=99)
  420. def test_init_bare_format(self) -> None:
  421. tmp_dir = self.mkdtemp()
  422. self.addCleanup(shutil.rmtree, tmp_dir)
  423. # Test format 1 for bare repo
  424. t = Repo.init_bare(tmp_dir + "bare", mkdir=True, format=1)
  425. self.addCleanup(t.close)
  426. self.assertEqual(t.get_config().get("core", "repositoryformatversion"), b"1")
  427. # Test invalid format for bare repo
  428. with self.assertRaises(ValueError):
  429. Repo.init_bare(tmp_dir + "badbr", mkdir=True, format=2)
  430. @skipIf(sys.platform == "win32", "fails on Windows")
  431. def test_fetch(self) -> None:
  432. r = self.open_repo("a.git")
  433. tmp_dir = self.mkdtemp()
  434. self.addCleanup(shutil.rmtree, tmp_dir)
  435. t = Repo.init(tmp_dir)
  436. self.addCleanup(t.close)
  437. r.fetch(t)
  438. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  439. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  440. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  441. self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t)
  442. self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t)
  443. @skipIf(sys.platform == "win32", "fails on Windows")
  444. def test_fetch_ignores_missing_refs(self) -> None:
  445. r = self.open_repo("a.git")
  446. missing = b"1234566789123456789123567891234657373833"
  447. r.refs[b"refs/heads/blah"] = missing
  448. tmp_dir = self.mkdtemp()
  449. self.addCleanup(shutil.rmtree, tmp_dir)
  450. t = Repo.init(tmp_dir)
  451. self.addCleanup(t.close)
  452. r.fetch(t)
  453. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  454. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  455. self.assertIn(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097", t)
  456. self.assertIn(b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a", t)
  457. self.assertIn(b"b0931cadc54336e78a1d980420e3268903b57a50", t)
  458. self.assertNotIn(missing, t)
  459. def test_clone(self) -> None:
  460. r = self.open_repo("a.git")
  461. tmp_dir = self.mkdtemp()
  462. self.addCleanup(shutil.rmtree, tmp_dir)
  463. with r.clone(tmp_dir, mkdir=False) as t:
  464. self.assertEqual(
  465. {
  466. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  467. b"refs/remotes/origin/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  468. b"refs/remotes/origin/HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  469. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  470. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  471. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  472. },
  473. t.refs.as_dict(),
  474. )
  475. shas = [e.commit.id for e in r.get_walker()]
  476. self.assertEqual(
  477. shas, [t.head(), b"2a72d929692c41d8554c07f6301757ba18a65d91"]
  478. )
  479. c = t.get_config()
  480. encoded_path = r.path
  481. if not isinstance(encoded_path, bytes):
  482. encoded_path = os.fsencode(encoded_path)
  483. self.assertEqual(encoded_path, c.get((b"remote", b"origin"), b"url"))
  484. self.assertEqual(
  485. b"+refs/heads/*:refs/remotes/origin/*",
  486. c.get((b"remote", b"origin"), b"fetch"),
  487. )
  488. def test_clone_no_head(self) -> None:
  489. temp_dir = self.mkdtemp()
  490. self.addCleanup(shutil.rmtree, temp_dir)
  491. repo_dir = os.path.join(os.path.dirname(__file__), "..", "testdata", "repos")
  492. dest_dir = os.path.join(temp_dir, "a.git")
  493. shutil.copytree(os.path.join(repo_dir, "a.git"), dest_dir, symlinks=True)
  494. r = Repo(dest_dir)
  495. self.addCleanup(r.close)
  496. del r.refs[b"refs/heads/master"]
  497. del r.refs[b"HEAD"]
  498. t = r.clone(os.path.join(temp_dir, "b.git"), mkdir=True)
  499. self.addCleanup(t.close)
  500. self.assertEqual(
  501. {
  502. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  503. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  504. },
  505. t.refs.as_dict(),
  506. )
  507. def test_clone_empty(self) -> None:
  508. """Test clone() doesn't crash if HEAD points to a non-existing ref.
  509. This simulates cloning server-side bare repository either when it is
  510. still empty or if user renames master branch and pushes private repo
  511. to the server.
  512. Non-bare repo HEAD always points to an existing ref.
  513. """
  514. r = self.open_repo("empty.git")
  515. tmp_dir = self.mkdtemp()
  516. self.addCleanup(shutil.rmtree, tmp_dir)
  517. r.clone(tmp_dir, mkdir=False, bare=True)
  518. def test_reset_index_symlink_enabled(self) -> None:
  519. if sys.platform == "win32":
  520. self.skipTest("symlinks are not supported on Windows")
  521. tmp_dir = self.mkdtemp()
  522. self.addCleanup(shutil.rmtree, tmp_dir)
  523. o = Repo.init(os.path.join(tmp_dir, "s"), mkdir=True)
  524. os.symlink("foo", os.path.join(tmp_dir, "s", "bar"))
  525. o.get_worktree().stage("bar")
  526. o.get_worktree().commit(
  527. message=b"add symlink",
  528. )
  529. t = o.clone(os.path.join(tmp_dir, "t"), symlinks=True)
  530. o.close()
  531. bar_path = os.path.join(tmp_dir, "t", "bar")
  532. if sys.platform == "win32":
  533. with open(bar_path) as f:
  534. self.assertEqual("foo", f.read())
  535. else:
  536. self.assertEqual("foo", os.readlink(bar_path))
  537. t.close()
  538. def test_reset_index_symlink_disabled(self) -> None:
  539. tmp_dir = self.mkdtemp()
  540. self.addCleanup(shutil.rmtree, tmp_dir)
  541. o = Repo.init(os.path.join(tmp_dir, "s"), mkdir=True)
  542. self.addCleanup(o.close)
  543. os.symlink("foo", os.path.join(tmp_dir, "s", "bar"))
  544. o.get_worktree().stage("bar")
  545. o.get_worktree().commit(
  546. message=b"add symlink",
  547. )
  548. t = o.clone(os.path.join(tmp_dir, "t"), symlinks=False)
  549. self.addCleanup(t.close)
  550. with open(os.path.join(tmp_dir, "t", "bar")) as f:
  551. self.assertEqual("foo", f.read())
  552. def test_reset_index_protect_hfs(self) -> None:
  553. tmp_dir = self.mkdtemp()
  554. self.addCleanup(shutil.rmtree, tmp_dir)
  555. repo = Repo.init(tmp_dir)
  556. self.addCleanup(repo.close)
  557. config = repo.get_config()
  558. # Test with protectHFS enabled
  559. config.set(b"core", b"core.protectHFS", b"true")
  560. config.write_to_path()
  561. # Create a file with HFS+ Unicode attack vector
  562. # This uses a zero-width non-joiner to create ".g\u200cit"
  563. attack_name = b".g\xe2\x80\x8cit"
  564. attack_path = os.path.join(tmp_dir, attack_name.decode("utf-8"))
  565. os.mkdir(attack_path)
  566. # Try to stage the malicious path - should be rejected
  567. with self.assertRaises(ValueError):
  568. repo.get_worktree().stage([attack_name])
  569. # Test with protectHFS disabled
  570. config.set(b"core", b"core.protectHFS", b"false")
  571. config.write_to_path()
  572. # Now it should work (though still dangerous!)
  573. # We're not actually staging it to avoid creating a dangerous repo
  574. def test_clone_bare(self) -> None:
  575. r = self.open_repo("a.git")
  576. tmp_dir = self.mkdtemp()
  577. self.addCleanup(shutil.rmtree, tmp_dir)
  578. t = r.clone(tmp_dir, mkdir=False)
  579. t.close()
  580. def test_clone_checkout_and_bare(self) -> None:
  581. r = self.open_repo("a.git")
  582. tmp_dir = self.mkdtemp()
  583. self.addCleanup(shutil.rmtree, tmp_dir)
  584. self.assertRaises(
  585. ValueError, r.clone, tmp_dir, mkdir=False, checkout=True, bare=True
  586. )
  587. def test_clone_branch(self) -> None:
  588. r = self.open_repo("a.git")
  589. r.refs[b"refs/heads/mybranch"] = b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a"
  590. tmp_dir = self.mkdtemp()
  591. self.addCleanup(shutil.rmtree, tmp_dir)
  592. with r.clone(tmp_dir, mkdir=False, branch=b"mybranch") as t:
  593. # HEAD should point to specified branch and not origin HEAD
  594. chain, sha = t.refs.follow(b"HEAD")
  595. self.assertEqual(chain[-1], b"refs/heads/mybranch")
  596. self.assertEqual(sha, b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a")
  597. self.assertEqual(
  598. t.refs[b"refs/remotes/origin/HEAD"],
  599. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  600. )
  601. def test_clone_tag(self) -> None:
  602. r = self.open_repo("a.git")
  603. tmp_dir = self.mkdtemp()
  604. self.addCleanup(shutil.rmtree, tmp_dir)
  605. with r.clone(tmp_dir, mkdir=False, branch=b"mytag") as t:
  606. # HEAD should be detached (and not a symbolic ref) at tag
  607. self.assertEqual(
  608. t.refs.read_ref(b"HEAD"),
  609. b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  610. )
  611. self.assertEqual(
  612. t.refs[b"refs/remotes/origin/HEAD"],
  613. b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  614. )
  615. def test_clone_invalid_branch(self) -> None:
  616. r = self.open_repo("a.git")
  617. tmp_dir = self.mkdtemp()
  618. self.addCleanup(shutil.rmtree, tmp_dir)
  619. self.assertRaises(
  620. ValueError,
  621. r.clone,
  622. tmp_dir,
  623. mkdir=False,
  624. branch=b"mybranch",
  625. )
  626. def test_merge_history(self) -> None:
  627. r = self.open_repo("simple_merge.git")
  628. shas = [e.commit.id for e in r.get_walker()]
  629. self.assertEqual(
  630. shas,
  631. [
  632. b"5dac377bdded4c9aeb8dff595f0faeebcc8498cc",
  633. b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd",
  634. b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6",
  635. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  636. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  637. ],
  638. )
  639. def test_out_of_order_merge(self) -> None:
  640. """Test that revision history is ordered by date, not parent order."""
  641. r = self.open_repo("ooo_merge.git")
  642. shas = [e.commit.id for e in r.get_walker()]
  643. self.assertEqual(
  644. shas,
  645. [
  646. b"7601d7f6231db6a57f7bbb79ee52e4d462fd44d1",
  647. b"f507291b64138b875c28e03469025b1ea20bc614",
  648. b"fb5b0425c7ce46959bec94d54b9a157645e114f5",
  649. b"f9e39b120c68182a4ba35349f832d0e4e61f485c",
  650. ],
  651. )
  652. def test_get_tags_empty(self) -> None:
  653. r = self.open_repo("ooo_merge.git")
  654. self.assertEqual({}, r.refs.as_dict(b"refs/tags"))
  655. def test_get_config(self) -> None:
  656. r = self.open_repo("ooo_merge.git")
  657. self.assertIsInstance(r.get_config(), Config)
  658. def test_get_config_stack(self) -> None:
  659. r = self.open_repo("ooo_merge.git")
  660. self.assertIsInstance(r.get_config_stack(), Config)
  661. def test_common_revisions(self) -> None:
  662. """This test demonstrates that ``find_common_revisions()`` actually
  663. returns common heads, not revisions; dulwich already uses
  664. ``find_common_revisions()`` in such a manner (see
  665. ``Repo.find_objects()``).
  666. """
  667. expected_shas = {b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e"}
  668. # Source for objects.
  669. r_base = self.open_repo("simple_merge.git")
  670. # Re-create each-side of the merge in simple_merge.git.
  671. #
  672. # Since the trees and blobs are missing, the repository created is
  673. # corrupted, but we're only checking for commits for the purpose of
  674. # this test, so it's immaterial.
  675. r1_dir = self.mkdtemp()
  676. self.addCleanup(shutil.rmtree, r1_dir)
  677. r1_commits = [
  678. b"ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd", # HEAD
  679. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  680. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  681. ]
  682. r2_dir = self.mkdtemp()
  683. self.addCleanup(shutil.rmtree, r2_dir)
  684. r2_commits = [
  685. b"4cffe90e0a41ad3f5190079d7c8f036bde29cbe6", # HEAD
  686. b"60dacdc733de308bb77bb76ce0fb0f9b44c9769e",
  687. b"0d89f20333fbb1d2f3a94da77f4981373d8f4310",
  688. ]
  689. r1 = Repo.init_bare(r1_dir)
  690. for c in r1_commits:
  691. r1.object_store.add_object(r_base.get_object(c))
  692. r1.refs[b"HEAD"] = r1_commits[0]
  693. r2 = Repo.init_bare(r2_dir)
  694. for c in r2_commits:
  695. r2.object_store.add_object(r_base.get_object(c))
  696. r2.refs[b"HEAD"] = r2_commits[0]
  697. # Finally, the 'real' testing!
  698. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  699. self.assertEqual(set(shas), expected_shas)
  700. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  701. self.assertEqual(set(shas), expected_shas)
  702. def test_shell_hook_pre_commit(self) -> None:
  703. if os.name != "posix":
  704. self.skipTest("shell hook tests requires POSIX shell")
  705. pre_commit_fail = """#!/bin/sh
  706. exit 1
  707. """
  708. pre_commit_success = """#!/bin/sh
  709. exit 0
  710. """
  711. repo_dir = os.path.join(self.mkdtemp())
  712. self.addCleanup(shutil.rmtree, repo_dir)
  713. r = Repo.init(repo_dir)
  714. self.addCleanup(r.close)
  715. pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit")
  716. with open(pre_commit, "w") as f:
  717. f.write(pre_commit_fail)
  718. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  719. self.assertRaises(
  720. errors.CommitError,
  721. r.get_worktree().commit,
  722. b"failed commit",
  723. committer=b"Test Committer <test@nodomain.com>",
  724. author=b"Test Author <test@nodomain.com>",
  725. commit_timestamp=12345,
  726. commit_timezone=0,
  727. author_timestamp=12345,
  728. author_timezone=0,
  729. )
  730. with open(pre_commit, "w") as f:
  731. f.write(pre_commit_success)
  732. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  733. commit_sha = r.get_worktree().commit(
  734. message=b"empty commit",
  735. committer=b"Test Committer <test@nodomain.com>",
  736. author=b"Test Author <test@nodomain.com>",
  737. commit_timestamp=12395,
  738. commit_timezone=0,
  739. author_timestamp=12395,
  740. author_timezone=0,
  741. )
  742. self.assertEqual([], r[commit_sha].parents)
  743. def test_shell_hook_commit_msg(self) -> None:
  744. if os.name != "posix":
  745. self.skipTest("shell hook tests requires POSIX shell")
  746. commit_msg_fail = """#!/bin/sh
  747. exit 1
  748. """
  749. commit_msg_success = """#!/bin/sh
  750. exit 0
  751. """
  752. repo_dir = self.mkdtemp()
  753. self.addCleanup(shutil.rmtree, repo_dir)
  754. r = Repo.init(repo_dir)
  755. self.addCleanup(r.close)
  756. commit_msg = os.path.join(r.controldir(), "hooks", "commit-msg")
  757. with open(commit_msg, "w") as f:
  758. f.write(commit_msg_fail)
  759. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  760. self.assertRaises(
  761. errors.CommitError,
  762. r.get_worktree().commit,
  763. b"failed commit",
  764. committer=b"Test Committer <test@nodomain.com>",
  765. author=b"Test Author <test@nodomain.com>",
  766. commit_timestamp=12345,
  767. commit_timezone=0,
  768. author_timestamp=12345,
  769. author_timezone=0,
  770. )
  771. with open(commit_msg, "w") as f:
  772. f.write(commit_msg_success)
  773. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  774. commit_sha = r.get_worktree().commit(
  775. message=b"empty commit",
  776. committer=b"Test Committer <test@nodomain.com>",
  777. author=b"Test Author <test@nodomain.com>",
  778. commit_timestamp=12395,
  779. commit_timezone=0,
  780. author_timestamp=12395,
  781. author_timezone=0,
  782. )
  783. self.assertEqual([], r[commit_sha].parents)
  784. def test_shell_hook_pre_commit_add_files(self) -> None:
  785. if os.name != "posix":
  786. self.skipTest("shell hook tests requires POSIX shell")
  787. pre_commit_contents = """#!{executable}
  788. import sys
  789. sys.path.extend({path!r})
  790. from dulwich.repo import Repo
  791. with open('foo', 'w') as f:
  792. f.write('newfile')
  793. r = Repo('.')
  794. r.get_worktree().stage(['foo'])
  795. """.format(
  796. executable=sys.executable,
  797. path=[os.path.join(os.path.dirname(__file__), "..", ".."), *sys.path],
  798. )
  799. repo_dir = os.path.join(self.mkdtemp())
  800. self.addCleanup(shutil.rmtree, repo_dir)
  801. r = Repo.init(repo_dir)
  802. self.addCleanup(r.close)
  803. with open(os.path.join(repo_dir, "blah"), "w") as f:
  804. f.write("blah")
  805. r.get_worktree().stage(["blah"])
  806. pre_commit = os.path.join(r.controldir(), "hooks", "pre-commit")
  807. with open(pre_commit, "w") as f:
  808. f.write(pre_commit_contents)
  809. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  810. commit_sha = r.get_worktree().commit(
  811. message=b"new commit",
  812. committer=b"Test Committer <test@nodomain.com>",
  813. author=b"Test Author <test@nodomain.com>",
  814. commit_timestamp=12395,
  815. commit_timezone=0,
  816. author_timestamp=12395,
  817. author_timezone=0,
  818. )
  819. self.assertEqual([], r[commit_sha].parents)
  820. tree = r[r[commit_sha].tree]
  821. self.assertEqual({b"blah", b"foo"}, set(tree))
  822. def test_shell_hook_post_commit(self) -> None:
  823. if os.name != "posix":
  824. self.skipTest("shell hook tests requires POSIX shell")
  825. repo_dir = self.mkdtemp()
  826. self.addCleanup(shutil.rmtree, repo_dir)
  827. r = Repo.init(repo_dir)
  828. self.addCleanup(r.close)
  829. (fd, path) = tempfile.mkstemp(dir=repo_dir)
  830. os.close(fd)
  831. post_commit_msg = (
  832. """#!/bin/sh
  833. rm """
  834. + path
  835. + """
  836. """
  837. )
  838. root_sha = r.get_worktree().commit(
  839. message=b"empty commit",
  840. committer=b"Test Committer <test@nodomain.com>",
  841. author=b"Test Author <test@nodomain.com>",
  842. commit_timestamp=12345,
  843. commit_timezone=0,
  844. author_timestamp=12345,
  845. author_timezone=0,
  846. )
  847. self.assertEqual([], r[root_sha].parents)
  848. post_commit = os.path.join(r.controldir(), "hooks", "post-commit")
  849. with open(post_commit, "wb") as f:
  850. f.write(post_commit_msg.encode(locale.getpreferredencoding()))
  851. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  852. commit_sha = r.get_worktree().commit(
  853. message=b"empty commit",
  854. committer=b"Test Committer <test@nodomain.com>",
  855. author=b"Test Author <test@nodomain.com>",
  856. commit_timestamp=12345,
  857. commit_timezone=0,
  858. author_timestamp=12345,
  859. author_timezone=0,
  860. )
  861. self.assertEqual([root_sha], r[commit_sha].parents)
  862. self.assertFalse(os.path.exists(path))
  863. post_commit_msg_fail = """#!/bin/sh
  864. exit 1
  865. """
  866. with open(post_commit, "w") as f:
  867. f.write(post_commit_msg_fail)
  868. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  869. warnings.simplefilter("always", UserWarning)
  870. self.addCleanup(warnings.resetwarnings)
  871. warnings_list, restore_warnings = setup_warning_catcher()
  872. self.addCleanup(restore_warnings)
  873. commit_sha2 = r.get_worktree().commit(
  874. message=b"empty commit",
  875. committer=b"Test Committer <test@nodomain.com>",
  876. author=b"Test Author <test@nodomain.com>",
  877. commit_timestamp=12345,
  878. commit_timezone=0,
  879. author_timestamp=12345,
  880. author_timezone=0,
  881. )
  882. expected_warning = UserWarning(
  883. "post-commit hook failed: Hook post-commit exited with non-zero status 1",
  884. )
  885. for w in warnings_list:
  886. if type(w) is type(expected_warning) and w.args == expected_warning.args:
  887. break
  888. else:
  889. raise AssertionError(
  890. f"Expected warning {expected_warning!r} not in {warnings_list!r}"
  891. )
  892. self.assertEqual([commit_sha], r[commit_sha2].parents)
  893. def test_as_dict(self) -> None:
  894. def check(repo) -> None:
  895. self.assertEqual(
  896. repo.refs.subkeys(b"refs/tags"),
  897. repo.refs.subkeys(b"refs/tags/"),
  898. )
  899. self.assertEqual(
  900. repo.refs.as_dict(b"refs/tags"),
  901. repo.refs.as_dict(b"refs/tags/"),
  902. )
  903. self.assertEqual(
  904. repo.refs.as_dict(b"refs/heads"),
  905. repo.refs.as_dict(b"refs/heads/"),
  906. )
  907. bare = self.open_repo("a.git")
  908. tmp_dir = self.mkdtemp()
  909. self.addCleanup(shutil.rmtree, tmp_dir)
  910. with bare.clone(tmp_dir, mkdir=False) as nonbare:
  911. check(nonbare)
  912. check(bare)
  913. def test_working_tree(self) -> None:
  914. temp_dir = tempfile.mkdtemp()
  915. self.addCleanup(shutil.rmtree, temp_dir)
  916. worktree_temp_dir = tempfile.mkdtemp()
  917. self.addCleanup(shutil.rmtree, worktree_temp_dir)
  918. r = Repo.init(temp_dir)
  919. self.addCleanup(r.close)
  920. root_sha = r.get_worktree().commit(
  921. message=b"empty commit",
  922. committer=b"Test Committer <test@nodomain.com>",
  923. author=b"Test Author <test@nodomain.com>",
  924. commit_timestamp=12345,
  925. commit_timezone=0,
  926. author_timestamp=12345,
  927. author_timezone=0,
  928. )
  929. r.refs[b"refs/heads/master"] = root_sha
  930. w = Repo._init_new_working_directory(worktree_temp_dir, r)
  931. self.addCleanup(w.close)
  932. new_sha = w.get_worktree().commit(
  933. message=b"new commit",
  934. committer=b"Test Committer <test@nodomain.com>",
  935. author=b"Test Author <test@nodomain.com>",
  936. commit_timestamp=12345,
  937. commit_timezone=0,
  938. author_timestamp=12345,
  939. author_timezone=0,
  940. )
  941. w.refs[b"HEAD"] = new_sha
  942. self.assertEqual(
  943. os.path.abspath(r.controldir()), os.path.abspath(w.commondir())
  944. )
  945. self.assertEqual(r.refs.keys(), w.refs.keys())
  946. self.assertNotEqual(r.head(), w.head())
  947. class BuildRepoRootTests(TestCase):
  948. """Tests that build on-disk repos from scratch.
  949. Repos live in a temp dir and are torn down after each test. They start with
  950. a single commit in master having single file named 'a'.
  951. """
  952. def get_repo_dir(self):
  953. return os.path.join(tempfile.mkdtemp(), "test")
  954. def setUp(self) -> None:
  955. super().setUp()
  956. self._repo_dir = self.get_repo_dir()
  957. os.makedirs(self._repo_dir)
  958. r = self._repo = Repo.init(self._repo_dir)
  959. self.addCleanup(tear_down_repo, r)
  960. self.assertFalse(r.bare)
  961. self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD"))
  962. self.assertRaises(KeyError, lambda: r.refs[b"refs/heads/master"])
  963. with open(os.path.join(r.path, "a"), "wb") as f:
  964. f.write(b"file contents")
  965. r.get_worktree().stage(["a"])
  966. commit_sha = r.get_worktree().commit(
  967. message=b"msg",
  968. committer=b"Test Committer <test@nodomain.com>",
  969. author=b"Test Author <test@nodomain.com>",
  970. commit_timestamp=12345,
  971. commit_timezone=0,
  972. author_timestamp=12345,
  973. author_timezone=0,
  974. )
  975. self.assertEqual([], r[commit_sha].parents)
  976. self._root_commit = commit_sha
  977. def test_get_shallow(self) -> None:
  978. self.assertEqual(set(), self._repo.get_shallow())
  979. with open(os.path.join(self._repo.path, ".git", "shallow"), "wb") as f:
  980. f.write(b"a90fa2d900a17e99b433217e988c4eb4a2e9a097\n")
  981. self.assertEqual(
  982. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  983. self._repo.get_shallow(),
  984. )
  985. def test_update_shallow(self) -> None:
  986. self._repo.update_shallow(None, None) # no op
  987. self.assertEqual(set(), self._repo.get_shallow())
  988. self._repo.update_shallow([b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"], None)
  989. self.assertEqual(
  990. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  991. self._repo.get_shallow(),
  992. )
  993. self._repo.update_shallow(
  994. [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"],
  995. [b"f9e39b120c68182a4ba35349f832d0e4e61f485c"],
  996. )
  997. self.assertEqual(
  998. {b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"},
  999. self._repo.get_shallow(),
  1000. )
  1001. self._repo.update_shallow(None, [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"])
  1002. self.assertEqual(set(), self._repo.get_shallow())
  1003. self.assertEqual(
  1004. False,
  1005. os.path.exists(os.path.join(self._repo.controldir(), "shallow")),
  1006. )
  1007. def test_build_repo(self) -> None:
  1008. r = self._repo
  1009. self.assertEqual(b"ref: refs/heads/master", r.refs.read_ref(b"HEAD"))
  1010. self.assertEqual(self._root_commit, r.refs[b"refs/heads/master"])
  1011. expected_blob = objects.Blob.from_string(b"file contents")
  1012. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  1013. actual_commit = r[self._root_commit]
  1014. self.assertEqual(b"msg", actual_commit.message)
  1015. def test_commit_modified(self) -> None:
  1016. r = self._repo
  1017. with open(os.path.join(r.path, "a"), "wb") as f:
  1018. f.write(b"new contents")
  1019. r.get_worktree().stage(["a"])
  1020. commit_sha = r.get_worktree().commit(
  1021. message=b"modified a",
  1022. committer=b"Test Committer <test@nodomain.com>",
  1023. author=b"Test Author <test@nodomain.com>",
  1024. commit_timestamp=12395,
  1025. commit_timezone=0,
  1026. author_timestamp=12395,
  1027. author_timezone=0,
  1028. )
  1029. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1030. a_mode, a_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"a")
  1031. self.assertEqual(stat.S_IFREG | 0o644, a_mode)
  1032. self.assertEqual(b"new contents", r[a_id].data)
  1033. @skipIf(not getattr(os, "symlink", None), "Requires symlink support")
  1034. def test_commit_symlink(self) -> None:
  1035. r = self._repo
  1036. os.symlink("a", os.path.join(r.path, "b"))
  1037. r.get_worktree().stage(["a", "b"])
  1038. commit_sha = r.get_worktree().commit(
  1039. message=b"Symlink b",
  1040. committer=b"Test Committer <test@nodomain.com>",
  1041. author=b"Test Author <test@nodomain.com>",
  1042. commit_timestamp=12395,
  1043. commit_timezone=0,
  1044. author_timestamp=12395,
  1045. author_timezone=0,
  1046. )
  1047. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1048. b_mode, b_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b"b")
  1049. self.assertTrue(stat.S_ISLNK(b_mode))
  1050. self.assertEqual(b"a", r[b_id].data)
  1051. def test_commit_merge_heads_file(self) -> None:
  1052. tmp_dir = tempfile.mkdtemp()
  1053. self.addCleanup(shutil.rmtree, tmp_dir)
  1054. r = Repo.init(tmp_dir)
  1055. with open(os.path.join(r.path, "a"), "w") as f:
  1056. f.write("initial text")
  1057. c1 = r.get_worktree().commit(
  1058. message=b"initial commit",
  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. )
  1066. with open(os.path.join(r.path, "a"), "w") as f:
  1067. f.write("merged text")
  1068. with open(os.path.join(r.path, ".git", "MERGE_HEAD"), "w") as f:
  1069. f.write("c27a2d21dd136312d7fa9e8baabb82561a1727d0\n")
  1070. r.get_worktree().stage(["a"])
  1071. commit_sha = r.get_worktree().commit(
  1072. message=b"deleted a",
  1073. committer=b"Test Committer <test@nodomain.com>",
  1074. author=b"Test Author <test@nodomain.com>",
  1075. commit_timestamp=12395,
  1076. commit_timezone=0,
  1077. author_timestamp=12395,
  1078. author_timezone=0,
  1079. )
  1080. self.assertEqual(
  1081. [c1, b"c27a2d21dd136312d7fa9e8baabb82561a1727d0"],
  1082. r[commit_sha].parents,
  1083. )
  1084. def test_commit_deleted(self) -> None:
  1085. r = self._repo
  1086. os.remove(os.path.join(r.path, "a"))
  1087. r.get_worktree().stage(["a"])
  1088. commit_sha = r.get_worktree().commit(
  1089. message=b"deleted a",
  1090. committer=b"Test Committer <test@nodomain.com>",
  1091. author=b"Test Author <test@nodomain.com>",
  1092. commit_timestamp=12395,
  1093. commit_timezone=0,
  1094. author_timestamp=12395,
  1095. author_timezone=0,
  1096. )
  1097. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1098. self.assertEqual([], list(r.open_index()))
  1099. tree = r[r[commit_sha].tree]
  1100. self.assertEqual([], list(tree.iteritems()))
  1101. def test_commit_follows(self) -> None:
  1102. r = self._repo
  1103. r.refs.set_symbolic_ref(b"HEAD", b"refs/heads/bla")
  1104. commit_sha = r.get_worktree().commit(
  1105. message=b"commit with strange character",
  1106. committer=b"Test Committer <test@nodomain.com>",
  1107. author=b"Test Author <test@nodomain.com>",
  1108. commit_timestamp=12395,
  1109. commit_timezone=0,
  1110. author_timestamp=12395,
  1111. author_timezone=0,
  1112. ref=b"HEAD",
  1113. )
  1114. self.assertEqual(commit_sha, r[b"refs/heads/bla"].id)
  1115. def test_commit_encoding(self) -> None:
  1116. r = self._repo
  1117. commit_sha = r.get_worktree().commit(
  1118. message=b"commit with strange character \xee",
  1119. committer=b"Test Committer <test@nodomain.com>",
  1120. author=b"Test Author <test@nodomain.com>",
  1121. commit_timestamp=12395,
  1122. commit_timezone=0,
  1123. author_timestamp=12395,
  1124. author_timezone=0,
  1125. encoding=b"iso8859-1",
  1126. )
  1127. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  1128. def test_compression_level(self) -> None:
  1129. r = self._repo
  1130. c = r.get_config()
  1131. c.set(("core",), "compression", "3")
  1132. c.set(("core",), "looseCompression", "4")
  1133. c.write_to_path()
  1134. r = Repo(self._repo_dir)
  1135. self.addCleanup(r.close)
  1136. self.assertEqual(r.object_store.loose_compression_level, 4)
  1137. def test_repositoryformatversion_unsupported(self) -> None:
  1138. r = self._repo
  1139. c = r.get_config()
  1140. c.set(("core",), "repositoryformatversion", "2")
  1141. c.write_to_path()
  1142. self.assertRaises(UnsupportedVersion, Repo, self._repo_dir)
  1143. def test_repositoryformatversion_1(self) -> None:
  1144. r = self._repo
  1145. c = r.get_config()
  1146. c.set(("core",), "repositoryformatversion", "1")
  1147. c.write_to_path()
  1148. Repo(self._repo_dir)
  1149. def test_worktreeconfig_extension(self) -> None:
  1150. r = self._repo
  1151. c = r.get_config()
  1152. c.set(("core",), "repositoryformatversion", "1")
  1153. c.set(("extensions",), "worktreeconfig", True)
  1154. c.write_to_path()
  1155. c = r.get_worktree_config()
  1156. c.set(("user",), "repositoryformatversion", "1")
  1157. c.set((b"user",), b"name", b"Jelmer")
  1158. c.write_to_path()
  1159. cs = r.get_config_stack()
  1160. self.assertEqual(cs.get(("user",), "name"), b"Jelmer")
  1161. def test_worktreeconfig_extension_case(self) -> None:
  1162. """Test that worktree code does not error for alternate case format."""
  1163. r = self._repo
  1164. c = r.get_config()
  1165. c.set(("core",), "repositoryformatversion", "1")
  1166. # Capitalize "Config"
  1167. c.set(("extensions",), "worktreeConfig", True)
  1168. c.write_to_path()
  1169. c = r.get_worktree_config()
  1170. c.set(("user",), "repositoryformatversion", "1")
  1171. c.set((b"user",), b"name", b"Jelmer")
  1172. c.write_to_path()
  1173. # The following line errored before
  1174. # https://github.com/jelmer/dulwich/issues/1285 was addressed
  1175. Repo(self._repo_dir)
  1176. def test_repositoryformatversion_1_extension(self) -> None:
  1177. r = self._repo
  1178. c = r.get_config()
  1179. c.set(("core",), "repositoryformatversion", "1")
  1180. c.set(("extensions",), "unknownextension", True)
  1181. c.write_to_path()
  1182. self.assertRaises(UnsupportedExtension, Repo, self._repo_dir)
  1183. def test_commit_encoding_from_config(self) -> None:
  1184. r = self._repo
  1185. c = r.get_config()
  1186. c.set(("i18n",), "commitEncoding", "iso8859-1")
  1187. c.write_to_path()
  1188. commit_sha = r.get_worktree().commit(
  1189. message=b"commit with strange character \xee",
  1190. committer=b"Test Committer <test@nodomain.com>",
  1191. author=b"Test Author <test@nodomain.com>",
  1192. commit_timestamp=12395,
  1193. commit_timezone=0,
  1194. author_timestamp=12395,
  1195. author_timezone=0,
  1196. )
  1197. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  1198. def test_commit_config_identity(self) -> None:
  1199. # commit falls back to the users' identity if it wasn't specified
  1200. r = self._repo
  1201. c = r.get_config()
  1202. c.set((b"user",), b"name", b"Jelmer")
  1203. c.set((b"user",), b"email", b"jelmer@apache.org")
  1204. c.write_to_path()
  1205. commit_sha = r.get_worktree().commit(
  1206. message=b"message",
  1207. )
  1208. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1209. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1210. def test_commit_config_identity_strips_than(self) -> None:
  1211. # commit falls back to the users' identity if it wasn't specified,
  1212. # and strips superfluous <>
  1213. r = self._repo
  1214. c = r.get_config()
  1215. c.set((b"user",), b"name", b"Jelmer")
  1216. c.set((b"user",), b"email", b"<jelmer@apache.org>")
  1217. c.write_to_path()
  1218. commit_sha = r.get_worktree().commit(
  1219. message=b"message",
  1220. )
  1221. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1222. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1223. def test_commit_config_identity_in_memoryrepo(self) -> None:
  1224. # commit falls back to the users' identity if it wasn't specified
  1225. r = MemoryRepo.init_bare([], {})
  1226. c = r.get_config()
  1227. c.set((b"user",), b"name", b"Jelmer")
  1228. c.set((b"user",), b"email", b"jelmer@apache.org")
  1229. # Create a tree object
  1230. tree = objects.Tree()
  1231. r.object_store.add_object(tree)
  1232. # Use do_commit for MemoryRepo since it doesn't support worktree
  1233. # Suppress deprecation warning since we're intentionally testing the deprecated method
  1234. with warnings.catch_warnings():
  1235. warnings.simplefilter("ignore", DeprecationWarning)
  1236. commit_sha = r.do_commit(
  1237. message=b"message",
  1238. tree=tree.id,
  1239. )
  1240. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1241. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].committer)
  1242. def test_commit_config_identity_from_env(self) -> None:
  1243. # commit falls back to the users' identity if it wasn't specified
  1244. self.overrideEnv("GIT_COMMITTER_NAME", "joe")
  1245. self.overrideEnv("GIT_COMMITTER_EMAIL", "joe@example.com")
  1246. r = self._repo
  1247. c = r.get_config()
  1248. c.set((b"user",), b"name", b"Jelmer")
  1249. c.set((b"user",), b"email", b"jelmer@apache.org")
  1250. c.write_to_path()
  1251. commit_sha = r.get_worktree().commit(
  1252. message=b"message",
  1253. )
  1254. self.assertEqual(b"Jelmer <jelmer@apache.org>", r[commit_sha].author)
  1255. self.assertEqual(b"joe <joe@example.com>", r[commit_sha].committer)
  1256. def test_commit_fail_ref(self) -> None:
  1257. r = self._repo
  1258. def set_if_equals(name, old_ref, new_ref, **kwargs) -> bool:
  1259. return False
  1260. r.refs.set_if_equals = set_if_equals
  1261. def add_if_new(name, new_ref, **kwargs) -> None:
  1262. self.fail("Unexpected call to add_if_new")
  1263. r.refs.add_if_new = add_if_new
  1264. old_shas = set(r.object_store)
  1265. self.assertRaises(
  1266. errors.CommitError,
  1267. r.get_worktree().commit,
  1268. b"failed commit",
  1269. committer=b"Test Committer <test@nodomain.com>",
  1270. author=b"Test Author <test@nodomain.com>",
  1271. commit_timestamp=12345,
  1272. commit_timezone=0,
  1273. author_timestamp=12345,
  1274. author_timezone=0,
  1275. )
  1276. new_shas = set(r.object_store) - old_shas
  1277. self.assertEqual(1, len(new_shas))
  1278. # Check that the new commit (now garbage) was added.
  1279. def test_commit_message_callback(self) -> None:
  1280. """Test commit with a callable message."""
  1281. r = self._repo
  1282. # Define a callback that generates message based on repo and commit
  1283. def message_callback(repo, commit):
  1284. # Verify we get the right objects
  1285. self.assertEqual(repo, r)
  1286. self.assertIsNotNone(commit.tree)
  1287. self.assertIsNotNone(commit.author)
  1288. self.assertIsNotNone(commit.committer)
  1289. # Generate a message
  1290. return b"Generated commit for tree " + commit.tree[:8]
  1291. commit_sha = r.get_worktree().commit(
  1292. message=message_callback,
  1293. committer=b"Test Committer <test@nodomain.com>",
  1294. author=b"Test Author <test@nodomain.com>",
  1295. commit_timestamp=12345,
  1296. commit_timezone=0,
  1297. author_timestamp=12345,
  1298. author_timezone=0,
  1299. )
  1300. commit = r[commit_sha]
  1301. self.assertTrue(commit.message.startswith(b"Generated commit for tree "))
  1302. self.assertIn(commit.tree[:8], commit.message)
  1303. def test_commit_message_callback_returns_none(self) -> None:
  1304. """Test commit with callback that returns None."""
  1305. r = self._repo
  1306. def message_callback(repo, commit):
  1307. return None
  1308. self.assertRaises(
  1309. ValueError,
  1310. r.get_worktree().commit,
  1311. message_callback,
  1312. committer=b"Test Committer <test@nodomain.com>",
  1313. author=b"Test Author <test@nodomain.com>",
  1314. commit_timestamp=12345,
  1315. commit_timezone=0,
  1316. author_timestamp=12345,
  1317. author_timezone=0,
  1318. )
  1319. def test_commit_message_callback_with_merge_heads(self) -> None:
  1320. """Test commit with callback for merge commits."""
  1321. r = self._repo
  1322. # Create two parent commits first
  1323. parent1 = r.get_worktree().commit(
  1324. message=b"Parent 1",
  1325. committer=b"Test Committer <test@nodomain.com>",
  1326. author=b"Test Author <test@nodomain.com>",
  1327. )
  1328. parent2 = r.get_worktree().commit(
  1329. message=b"Parent 2",
  1330. committer=b"Test Committer <test@nodomain.com>",
  1331. author=b"Test Author <test@nodomain.com>",
  1332. ref=None,
  1333. )
  1334. def message_callback(repo, commit):
  1335. # Verify the commit object has parents set
  1336. self.assertEqual(2, len(commit.parents))
  1337. return b"Merge commit with %d parents" % len(commit.parents)
  1338. merge_sha = r.get_worktree().commit(
  1339. message=message_callback,
  1340. committer=b"Test Committer <test@nodomain.com>",
  1341. author=b"Test Author <test@nodomain.com>",
  1342. merge_heads=[parent2],
  1343. )
  1344. merge_commit = r[merge_sha]
  1345. self.assertEqual(b"Merge commit with 2 parents", merge_commit.message)
  1346. self.assertEqual([parent1, parent2], merge_commit.parents)
  1347. def test_commit_branch(self) -> None:
  1348. r = self._repo
  1349. commit_sha = r.get_worktree().commit(
  1350. message=b"commit to branch",
  1351. committer=b"Test Committer <test@nodomain.com>",
  1352. author=b"Test Author <test@nodomain.com>",
  1353. commit_timestamp=12395,
  1354. commit_timezone=0,
  1355. author_timestamp=12395,
  1356. author_timezone=0,
  1357. ref=b"refs/heads/new_branch",
  1358. )
  1359. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  1360. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  1361. self.assertEqual([], r[commit_sha].parents)
  1362. self.assertIn(b"refs/heads/new_branch", r)
  1363. new_branch_head = commit_sha
  1364. commit_sha = r.get_worktree().commit(
  1365. message=b"commit to branch 2",
  1366. committer=b"Test Committer <test@nodomain.com>",
  1367. author=b"Test Author <test@nodomain.com>",
  1368. commit_timestamp=12395,
  1369. commit_timezone=0,
  1370. author_timestamp=12395,
  1371. author_timezone=0,
  1372. ref=b"refs/heads/new_branch",
  1373. )
  1374. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  1375. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  1376. self.assertEqual([new_branch_head], r[commit_sha].parents)
  1377. def test_commit_merge_heads(self) -> None:
  1378. r = self._repo
  1379. merge_1 = r.get_worktree().commit(
  1380. message=b"commit to branch 2",
  1381. committer=b"Test Committer <test@nodomain.com>",
  1382. author=b"Test Author <test@nodomain.com>",
  1383. commit_timestamp=12395,
  1384. commit_timezone=0,
  1385. author_timestamp=12395,
  1386. author_timezone=0,
  1387. ref=b"refs/heads/new_branch",
  1388. )
  1389. commit_sha = r.get_worktree().commit(
  1390. message=b"commit with merge",
  1391. committer=b"Test Committer <test@nodomain.com>",
  1392. author=b"Test Author <test@nodomain.com>",
  1393. commit_timestamp=12395,
  1394. commit_timezone=0,
  1395. author_timestamp=12395,
  1396. author_timezone=0,
  1397. merge_heads=[merge_1],
  1398. )
  1399. self.assertEqual([self._root_commit, merge_1], r[commit_sha].parents)
  1400. def test_commit_dangling_commit(self) -> None:
  1401. r = self._repo
  1402. old_shas = set(r.object_store)
  1403. old_refs = r.get_refs()
  1404. commit_sha = r.get_worktree().commit(
  1405. message=b"commit with no ref",
  1406. committer=b"Test Committer <test@nodomain.com>",
  1407. author=b"Test Author <test@nodomain.com>",
  1408. commit_timestamp=12395,
  1409. commit_timezone=0,
  1410. author_timestamp=12395,
  1411. author_timezone=0,
  1412. ref=None,
  1413. )
  1414. new_shas = set(r.object_store) - old_shas
  1415. # New sha is added, but no new refs
  1416. self.assertEqual(1, len(new_shas))
  1417. new_commit = r[new_shas.pop()]
  1418. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1419. self.assertEqual([], r[commit_sha].parents)
  1420. self.assertEqual(old_refs, r.get_refs())
  1421. def test_commit_dangling_commit_with_parents(self) -> None:
  1422. r = self._repo
  1423. old_shas = set(r.object_store)
  1424. old_refs = r.get_refs()
  1425. commit_sha = r.get_worktree().commit(
  1426. message=b"commit with no ref",
  1427. committer=b"Test Committer <test@nodomain.com>",
  1428. author=b"Test Author <test@nodomain.com>",
  1429. commit_timestamp=12395,
  1430. commit_timezone=0,
  1431. author_timestamp=12395,
  1432. author_timezone=0,
  1433. ref=None,
  1434. merge_heads=[self._root_commit],
  1435. )
  1436. new_shas = set(r.object_store) - old_shas
  1437. # New sha is added, but no new refs
  1438. self.assertEqual(1, len(new_shas))
  1439. new_commit = r[new_shas.pop()]
  1440. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  1441. self.assertEqual([self._root_commit], r[commit_sha].parents)
  1442. self.assertEqual(old_refs, r.get_refs())
  1443. def test_stage_absolute(self) -> None:
  1444. r = self._repo
  1445. os.remove(os.path.join(r.path, "a"))
  1446. # Suppress deprecation warning since we're intentionally testing the deprecated method
  1447. with warnings.catch_warnings():
  1448. warnings.simplefilter("ignore", DeprecationWarning)
  1449. self.assertRaises(ValueError, r.stage, [os.path.join(r.path, "a")])
  1450. def test_stage_deleted(self) -> None:
  1451. r = self._repo
  1452. os.remove(os.path.join(r.path, "a"))
  1453. r.get_worktree().stage(["a"])
  1454. r.get_worktree().stage(["a"]) # double-stage a deleted path
  1455. self.assertEqual([], list(r.open_index()))
  1456. def test_stage_directory(self) -> None:
  1457. r = self._repo
  1458. os.mkdir(os.path.join(r.path, "c"))
  1459. r.get_worktree().stage(["c"])
  1460. self.assertEqual([b"a"], list(r.open_index()))
  1461. def test_stage_submodule(self) -> None:
  1462. r = self._repo
  1463. s = Repo.init(os.path.join(r.path, "sub"), mkdir=True)
  1464. s.get_worktree().commit(
  1465. message=b"message",
  1466. )
  1467. r.get_worktree().stage(["sub"])
  1468. self.assertEqual([b"a", b"sub"], list(r.open_index()))
  1469. def test_unstage_midify_file_with_dir(self) -> None:
  1470. os.mkdir(os.path.join(self._repo.path, "new_dir"))
  1471. full_path = os.path.join(self._repo.path, "new_dir", "foo")
  1472. with open(full_path, "w") as f:
  1473. f.write("hello")
  1474. porcelain.add(self._repo, paths=[full_path])
  1475. porcelain.commit(
  1476. self._repo,
  1477. message=b"unitest",
  1478. committer=b"Jane <jane@example.com>",
  1479. author=b"John <john@example.com>",
  1480. )
  1481. with open(full_path, "a") as f:
  1482. f.write("something new")
  1483. self._repo.get_worktree().unstage(["new_dir/foo"])
  1484. status = list(porcelain.status(self._repo))
  1485. self.assertEqual(
  1486. [{"add": [], "delete": [], "modify": []}, [b"new_dir/foo"], []], status
  1487. )
  1488. def test_unstage_while_no_commit(self) -> None:
  1489. file = "foo"
  1490. full_path = os.path.join(self._repo.path, file)
  1491. with open(full_path, "w") as f:
  1492. f.write("hello")
  1493. porcelain.add(self._repo, paths=[full_path])
  1494. self._repo.get_worktree().unstage([file])
  1495. status = list(porcelain.status(self._repo))
  1496. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["foo"]], status)
  1497. def test_unstage_add_file(self) -> None:
  1498. file = "foo"
  1499. full_path = os.path.join(self._repo.path, file)
  1500. porcelain.commit(
  1501. self._repo,
  1502. message=b"unitest",
  1503. committer=b"Jane <jane@example.com>",
  1504. author=b"John <john@example.com>",
  1505. )
  1506. with open(full_path, "w") as f:
  1507. f.write("hello")
  1508. porcelain.add(self._repo, paths=[full_path])
  1509. self._repo.get_worktree().unstage([file])
  1510. status = list(porcelain.status(self._repo))
  1511. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["foo"]], status)
  1512. def test_unstage_modify_file(self) -> None:
  1513. file = "foo"
  1514. full_path = os.path.join(self._repo.path, file)
  1515. with open(full_path, "w") as f:
  1516. f.write("hello")
  1517. porcelain.add(self._repo, paths=[full_path])
  1518. porcelain.commit(
  1519. self._repo,
  1520. message=b"unitest",
  1521. committer=b"Jane <jane@example.com>",
  1522. author=b"John <john@example.com>",
  1523. )
  1524. with open(full_path, "a") as f:
  1525. f.write("broken")
  1526. porcelain.add(self._repo, paths=[full_path])
  1527. self._repo.get_worktree().unstage([file])
  1528. status = list(porcelain.status(self._repo))
  1529. self.assertEqual(
  1530. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  1531. )
  1532. def test_unstage_remove_file(self) -> None:
  1533. file = "foo"
  1534. full_path = os.path.join(self._repo.path, file)
  1535. with open(full_path, "w") as f:
  1536. f.write("hello")
  1537. porcelain.add(self._repo, paths=[full_path])
  1538. porcelain.commit(
  1539. self._repo,
  1540. message=b"unitest",
  1541. committer=b"Jane <jane@example.com>",
  1542. author=b"John <john@example.com>",
  1543. )
  1544. os.remove(full_path)
  1545. self._repo.get_worktree().unstage([file])
  1546. status = list(porcelain.status(self._repo))
  1547. self.assertEqual(
  1548. [{"add": [], "delete": [], "modify": []}, [b"foo"], []], status
  1549. )
  1550. def test_reset_index(self) -> None:
  1551. r = self._repo
  1552. with open(os.path.join(r.path, "a"), "wb") as f:
  1553. f.write(b"changed")
  1554. with open(os.path.join(r.path, "b"), "wb") as f:
  1555. f.write(b"added")
  1556. r.get_worktree().stage(["a", "b"])
  1557. status = list(porcelain.status(self._repo))
  1558. self.assertEqual(
  1559. [{"add": [b"b"], "delete": [], "modify": [b"a"]}, [], []], status
  1560. )
  1561. r.get_worktree().reset_index()
  1562. status = list(porcelain.status(self._repo))
  1563. self.assertEqual([{"add": [], "delete": [], "modify": []}, [], ["b"]], status)
  1564. @skipIf(
  1565. sys.platform in ("win32", "darwin"),
  1566. "tries to implicitly decode as utf8",
  1567. )
  1568. def test_commit_no_encode_decode(self) -> None:
  1569. r = self._repo
  1570. repo_path_bytes = os.fsencode(r.path)
  1571. encodings = ("utf8", "latin1")
  1572. names = ["À".encode(encoding) for encoding in encodings]
  1573. for name, encoding in zip(names, encodings):
  1574. full_path = os.path.join(repo_path_bytes, name)
  1575. with open(full_path, "wb") as f:
  1576. f.write(encoding.encode("ascii"))
  1577. # These files are break tear_down_repo, so cleanup these files
  1578. # ourselves.
  1579. self.addCleanup(os.remove, full_path)
  1580. r.get_worktree().stage(names)
  1581. commit_sha = r.get_worktree().commit(
  1582. message=b"Files with different encodings",
  1583. committer=b"Test Committer <test@nodomain.com>",
  1584. author=b"Test Author <test@nodomain.com>",
  1585. commit_timestamp=12395,
  1586. commit_timezone=0,
  1587. author_timestamp=12395,
  1588. author_timezone=0,
  1589. ref=None,
  1590. merge_heads=[self._root_commit],
  1591. )
  1592. for name, encoding in zip(names, encodings):
  1593. mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name)
  1594. self.assertEqual(stat.S_IFREG | 0o644, mode)
  1595. self.assertEqual(encoding.encode("ascii"), r[id].data)
  1596. def test_discover_intended(self) -> None:
  1597. path = os.path.join(self._repo_dir, "b/c")
  1598. r = Repo.discover(path)
  1599. self.assertEqual(r.head(), self._repo.head())
  1600. def test_discover_isrepo(self) -> None:
  1601. r = Repo.discover(self._repo_dir)
  1602. self.assertEqual(r.head(), self._repo.head())
  1603. def test_discover_notrepo(self) -> None:
  1604. with self.assertRaises(NotGitRepository):
  1605. Repo.discover("/")
  1606. class CheckUserIdentityTests(TestCase):
  1607. def test_valid(self) -> None:
  1608. check_user_identity(b"Me <me@example.com>")
  1609. def test_invalid(self) -> None:
  1610. self.assertRaises(InvalidUserIdentity, check_user_identity, b"No Email")
  1611. self.assertRaises(
  1612. InvalidUserIdentity, check_user_identity, b"Fullname <missing"
  1613. )
  1614. self.assertRaises(
  1615. InvalidUserIdentity, check_user_identity, b"Fullname missing>"
  1616. )
  1617. self.assertRaises(
  1618. InvalidUserIdentity, check_user_identity, b"Fullname >order<>"
  1619. )
  1620. self.assertRaises(
  1621. InvalidUserIdentity, check_user_identity, b"Contains\0null byte <>"
  1622. )
  1623. self.assertRaises(
  1624. InvalidUserIdentity, check_user_identity, b"Contains\nnewline byte <>"
  1625. )
  1626. class RepoConfigIncludeIfTests(TestCase):
  1627. """Test includeIf functionality in repository config loading."""
  1628. def test_repo_config_includeif_gitdir(self) -> None:
  1629. """Test that includeIf gitdir conditions work when loading repo config."""
  1630. import tempfile
  1631. from dulwich.repo import Repo
  1632. with tempfile.TemporaryDirectory() as tmpdir:
  1633. # Create a repository
  1634. repo_path = os.path.join(tmpdir, "myrepo")
  1635. r = Repo.init(repo_path, mkdir=True)
  1636. # Use realpath to resolve any symlinks (important on macOS)
  1637. repo_path = os.path.realpath(repo_path)
  1638. # Create an included config file
  1639. included_path = os.path.join(tmpdir, "work.config")
  1640. with open(included_path, "wb") as f:
  1641. f.write(b"[user]\n email = work@example.com\n")
  1642. # Add includeIf to the repo config
  1643. config_path = os.path.join(repo_path, ".git", "config")
  1644. with open(config_path, "ab") as f:
  1645. f.write(f'\n[includeIf "gitdir:{repo_path}/.git/"]\n'.encode())
  1646. escaped_path = included_path.replace("\\", "\\\\")
  1647. f.write(f" path = {escaped_path}\n".encode())
  1648. # Close and reopen to reload config
  1649. r.close()
  1650. r = Repo(repo_path)
  1651. # Check if include was processed
  1652. config = r.get_config()
  1653. self.assertEqual(b"work@example.com", config.get((b"user",), b"email"))
  1654. r.close()
  1655. def test_repo_config_includeif_gitdir_pattern(self) -> None:
  1656. """Test includeIf gitdir pattern matching in repository config."""
  1657. import tempfile
  1658. from dulwich.repo import Repo
  1659. with tempfile.TemporaryDirectory() as tmpdir:
  1660. # Create a repository under "work" directory
  1661. work_dir = os.path.join(tmpdir, "work", "project1")
  1662. os.makedirs(os.path.dirname(work_dir), exist_ok=True)
  1663. r = Repo.init(work_dir, mkdir=True)
  1664. # Create an included config file
  1665. included_path = os.path.join(tmpdir, "work.config")
  1666. with open(included_path, "wb") as f:
  1667. f.write(b"[user]\n email = work@company.com\n")
  1668. # Add includeIf with pattern to the repo config
  1669. config_path = os.path.join(work_dir, ".git", "config")
  1670. with open(config_path, "ab") as f:
  1671. # Use a pattern that will match paths containing /work/
  1672. f.write(b'\n[includeIf "gitdir:**/work/**"]\n')
  1673. escaped_path = included_path.replace("\\", "\\\\")
  1674. f.write(f" path = {escaped_path}\n".encode())
  1675. # Close and reopen to reload config
  1676. r.close()
  1677. r = Repo(work_dir)
  1678. # Check if include was processed
  1679. config = r.get_config()
  1680. self.assertEqual(b"work@company.com", config.get((b"user",), b"email"))
  1681. r.close()
  1682. def test_repo_config_includeif_no_match(self) -> None:
  1683. """Test that includeIf doesn't include when condition doesn't match."""
  1684. import tempfile
  1685. from dulwich.repo import Repo
  1686. with tempfile.TemporaryDirectory() as tmpdir:
  1687. # Create a repository
  1688. repo_path = os.path.join(tmpdir, "personal", "project")
  1689. os.makedirs(os.path.dirname(repo_path), exist_ok=True)
  1690. r = Repo.init(repo_path, mkdir=True)
  1691. # Create an included config file
  1692. included_path = os.path.join(tmpdir, "work.config")
  1693. with open(included_path, "wb") as f:
  1694. f.write(b"[user]\n email = work@company.com\n")
  1695. # Add includeIf that won't match
  1696. config_path = os.path.join(repo_path, ".git", "config")
  1697. with open(config_path, "ab") as f:
  1698. f.write(b'\n[includeIf "gitdir:**/work/**"]\n')
  1699. escaped_path = included_path.replace("\\", "\\\\")
  1700. f.write(f" path = {escaped_path}\n".encode())
  1701. # Close and reopen to reload config
  1702. r.close()
  1703. r = Repo(repo_path)
  1704. # Check that include was NOT processed
  1705. config = r.get_config()
  1706. with self.assertRaises(KeyError):
  1707. config.get((b"user",), b"email")
  1708. r.close()
  1709. def test_bare_repo_config_includeif(self) -> None:
  1710. """Test includeIf in bare repository."""
  1711. import tempfile
  1712. from dulwich.repo import Repo
  1713. with tempfile.TemporaryDirectory() as tmpdir:
  1714. # Create a bare repository
  1715. repo_path = os.path.join(tmpdir, "bare.git")
  1716. r = Repo.init_bare(repo_path, mkdir=True)
  1717. # Use realpath to resolve any symlinks (important on macOS)
  1718. repo_path = os.path.realpath(repo_path)
  1719. # Create an included config file
  1720. included_path = os.path.join(tmpdir, "server.config")
  1721. with open(included_path, "wb") as f:
  1722. f.write(b"[receive]\n denyNonFastForwards = true\n")
  1723. # Add includeIf to the repo config
  1724. config_path = os.path.join(repo_path, "config")
  1725. with open(config_path, "ab") as f:
  1726. f.write(f'\n[includeIf "gitdir:{repo_path}/"]\n'.encode())
  1727. escaped_path = included_path.replace("\\", "\\\\")
  1728. f.write(f" path = {escaped_path}\n".encode())
  1729. # Close and reopen to reload config
  1730. r.close()
  1731. r = Repo(repo_path)
  1732. # Check if include was processed
  1733. config = r.get_config()
  1734. self.assertEqual(b"true", config.get((b"receive",), b"denyNonFastForwards"))
  1735. r.close()
  1736. def test_repo_config_includeif_hasconfig(self) -> None:
  1737. """Test includeIf hasconfig conditions in repository config."""
  1738. import tempfile
  1739. from dulwich.repo import Repo
  1740. with tempfile.TemporaryDirectory() as tmpdir:
  1741. # Create a repository
  1742. repo_path = os.path.join(tmpdir, "myrepo")
  1743. r = Repo.init(repo_path, mkdir=True)
  1744. # Create an included config file
  1745. included_path = os.path.join(tmpdir, "work.config")
  1746. with open(included_path, "wb") as f:
  1747. f.write(b"[user]\n name = WorkUser\n")
  1748. # Add a remote and includeIf hasconfig to the repo config
  1749. config_path = os.path.join(repo_path, ".git", "config")
  1750. with open(config_path, "ab") as f:
  1751. f.write(b'\n[remote "origin"]\n')
  1752. f.write(b" url = ssh://org-work@github.com/company/project\n")
  1753. f.write(
  1754. b'[includeIf "hasconfig:remote.*.url:ssh://org-*@github.com/**"]\n'
  1755. )
  1756. escaped_path = included_path.replace("\\", "\\\\")
  1757. f.write(f" path = {escaped_path}\n".encode())
  1758. # Close and reopen to reload config
  1759. r.close()
  1760. r = Repo(repo_path)
  1761. # Check if include was processed
  1762. config = r.get_config()
  1763. self.assertEqual(b"WorkUser", config.get((b"user",), b"name"))
  1764. r.close()
  1765. def test_repo_config_includeif_onbranch(self) -> None:
  1766. """Test includeIf onbranch conditions in repository config."""
  1767. import tempfile
  1768. from dulwich.repo import Repo
  1769. with tempfile.TemporaryDirectory() as tmpdir:
  1770. # Create a repository
  1771. repo_path = os.path.join(tmpdir, "myrepo")
  1772. r = Repo.init(repo_path, mkdir=True)
  1773. # Create HEAD pointing to main branch
  1774. refs_heads_dir = os.path.join(repo_path, ".git", "refs", "heads")
  1775. os.makedirs(refs_heads_dir, exist_ok=True)
  1776. main_ref_path = os.path.join(refs_heads_dir, "main")
  1777. with open(main_ref_path, "wb") as f:
  1778. f.write(b"0123456789012345678901234567890123456789\n")
  1779. head_path = os.path.join(repo_path, ".git", "HEAD")
  1780. with open(head_path, "wb") as f:
  1781. f.write(b"ref: refs/heads/main\n")
  1782. # Create an included config file
  1783. included_path = os.path.join(tmpdir, "main.config")
  1784. with open(included_path, "wb") as f:
  1785. f.write(b"[core]\n autocrlf = true\n")
  1786. # Add includeIf onbranch to the repo config
  1787. config_path = os.path.join(repo_path, ".git", "config")
  1788. with open(config_path, "ab") as f:
  1789. f.write(b'\n[includeIf "onbranch:main"]\n')
  1790. escaped_path = included_path.replace("\\", "\\\\")
  1791. f.write(f" path = {escaped_path}\n".encode())
  1792. # Close and reopen to reload config
  1793. r.close()
  1794. r = Repo(repo_path)
  1795. # Check if include was processed
  1796. config = r.get_config()
  1797. self.assertEqual(b"true", config.get((b"core",), b"autocrlf"))
  1798. r.close()
  1799. @skipIf(sys.platform == "win32", "Windows does not support Unix file permissions")
  1800. class SharedRepositoryTests(TestCase):
  1801. """Tests for core.sharedRepository functionality."""
  1802. def setUp(self):
  1803. super().setUp()
  1804. self._orig_umask = os.umask(0o022)
  1805. def tearDown(self):
  1806. os.umask(self._orig_umask)
  1807. super().tearDown()
  1808. def _get_file_mode(self, path):
  1809. """Get the file mode bits (without file type bits)."""
  1810. return stat.S_IMODE(os.stat(path).st_mode)
  1811. def _check_permissions(self, repo, expected_file_mode, expected_dir_mode):
  1812. """Check that repository files and directories have expected permissions."""
  1813. objects_dir = os.path.join(repo.commondir(), "objects")
  1814. # Check objects directory
  1815. actual_dir_mode = self._get_file_mode(objects_dir)
  1816. self.assertEqual(
  1817. expected_dir_mode,
  1818. actual_dir_mode,
  1819. f"objects dir mode: expected {oct(expected_dir_mode)}, got {oct(actual_dir_mode)}",
  1820. )
  1821. # Check pack directory
  1822. pack_dir = os.path.join(objects_dir, "pack")
  1823. actual_dir_mode = self._get_file_mode(pack_dir)
  1824. self.assertEqual(
  1825. expected_dir_mode,
  1826. actual_dir_mode,
  1827. f"pack dir mode: expected {oct(expected_dir_mode)}, got {oct(actual_dir_mode)}",
  1828. )
  1829. # Check info directory
  1830. info_dir = os.path.join(objects_dir, "info")
  1831. actual_dir_mode = self._get_file_mode(info_dir)
  1832. self.assertEqual(
  1833. expected_dir_mode,
  1834. actual_dir_mode,
  1835. f"info dir mode: expected {oct(expected_dir_mode)}, got {oct(actual_dir_mode)}",
  1836. )
  1837. def test_init_bare_shared_group(self):
  1838. """Test initializing bare repo with sharedRepository=group."""
  1839. tmp_dir = tempfile.mkdtemp()
  1840. self.addCleanup(shutil.rmtree, tmp_dir)
  1841. # Set umask to 0 to see what permissions are actually set
  1842. os.umask(0)
  1843. repo = Repo.init_bare(tmp_dir, shared_repository="group")
  1844. self.addCleanup(repo.close)
  1845. # Expected permissions for group sharing
  1846. expected_dir_mode = 0o2775 # setgid + rwxrwxr-x
  1847. expected_file_mode = 0o664 # rw-rw-r--
  1848. self._check_permissions(repo, expected_file_mode, expected_dir_mode)
  1849. def test_init_bare_shared_all(self):
  1850. """Test initializing bare repo with sharedRepository=all."""
  1851. tmp_dir = tempfile.mkdtemp()
  1852. self.addCleanup(shutil.rmtree, tmp_dir)
  1853. # Set umask to 0 to see what permissions are actually set
  1854. os.umask(0)
  1855. repo = Repo.init_bare(tmp_dir, shared_repository="all")
  1856. self.addCleanup(repo.close)
  1857. # Expected permissions for world sharing
  1858. expected_dir_mode = 0o2777 # setgid + rwxrwxrwx
  1859. expected_file_mode = 0o666 # rw-rw-rw-
  1860. self._check_permissions(repo, expected_file_mode, expected_dir_mode)
  1861. def test_init_bare_shared_umask(self):
  1862. """Test initializing bare repo with sharedRepository=umask (default)."""
  1863. tmp_dir = tempfile.mkdtemp()
  1864. self.addCleanup(shutil.rmtree, tmp_dir)
  1865. repo = Repo.init_bare(tmp_dir, shared_repository="umask")
  1866. self.addCleanup(repo.close)
  1867. # With umask, no special permissions should be set
  1868. # The actual permissions will depend on the umask, but we can
  1869. # at least verify that setgid is NOT set
  1870. objects_dir = os.path.join(repo.commondir(), "objects")
  1871. actual_mode = os.stat(objects_dir).st_mode
  1872. # Verify setgid bit is NOT set
  1873. self.assertEqual(0, actual_mode & stat.S_ISGID)
  1874. def test_loose_object_permissions_group(self):
  1875. """Test that loose objects get correct permissions with sharedRepository=group."""
  1876. tmp_dir = tempfile.mkdtemp()
  1877. self.addCleanup(shutil.rmtree, tmp_dir)
  1878. # Set umask to 0 to see what permissions are actually set
  1879. os.umask(0)
  1880. repo = Repo.init_bare(tmp_dir, shared_repository="group")
  1881. self.addCleanup(repo.close)
  1882. # Create a blob object
  1883. blob = objects.Blob.from_string(b"test content")
  1884. repo.object_store.add_object(blob)
  1885. # Find the object file
  1886. obj_path = repo.object_store._get_shafile_path(blob.id)
  1887. # Check file permissions
  1888. actual_mode = self._get_file_mode(obj_path)
  1889. expected_mode = 0o664 # rw-rw-r--
  1890. self.assertEqual(
  1891. expected_mode,
  1892. actual_mode,
  1893. f"loose object mode: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  1894. )
  1895. # Check directory permissions
  1896. obj_dir = os.path.dirname(obj_path)
  1897. actual_dir_mode = self._get_file_mode(obj_dir)
  1898. expected_dir_mode = 0o2775 # setgid + rwxrwxr-x
  1899. self.assertEqual(
  1900. expected_dir_mode,
  1901. actual_dir_mode,
  1902. f"object dir mode: expected {oct(expected_dir_mode)}, got {oct(actual_dir_mode)}",
  1903. )
  1904. def test_loose_object_permissions_all(self):
  1905. """Test that loose objects get correct permissions with sharedRepository=all."""
  1906. tmp_dir = tempfile.mkdtemp()
  1907. self.addCleanup(shutil.rmtree, tmp_dir)
  1908. # Set umask to 0 to see what permissions are actually set
  1909. os.umask(0)
  1910. repo = Repo.init_bare(tmp_dir, shared_repository="all")
  1911. self.addCleanup(repo.close)
  1912. # Create a blob object
  1913. blob = objects.Blob.from_string(b"test content")
  1914. repo.object_store.add_object(blob)
  1915. # Find the object file
  1916. obj_path = repo.object_store._get_shafile_path(blob.id)
  1917. # Check file permissions
  1918. actual_mode = self._get_file_mode(obj_path)
  1919. expected_mode = 0o666 # rw-rw-rw-
  1920. self.assertEqual(
  1921. expected_mode,
  1922. actual_mode,
  1923. f"loose object mode: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  1924. )
  1925. def test_pack_file_permissions_group(self):
  1926. """Test that pack files get correct permissions with sharedRepository=group."""
  1927. tmp_dir = tempfile.mkdtemp()
  1928. self.addCleanup(shutil.rmtree, tmp_dir)
  1929. # Set umask to 0 to see what permissions are actually set
  1930. os.umask(0)
  1931. repo = Repo.init_bare(tmp_dir, shared_repository="group")
  1932. self.addCleanup(repo.close)
  1933. # Create some objects
  1934. blobs = [
  1935. objects.Blob.from_string(f"test content {i}".encode()) for i in range(5)
  1936. ]
  1937. repo.object_store.add_objects([(blob, None) for blob in blobs])
  1938. # Find the pack files
  1939. pack_dir = os.path.join(repo.commondir(), "objects", "pack")
  1940. pack_files = [f for f in os.listdir(pack_dir) if f.endswith(".pack")]
  1941. self.assertGreater(len(pack_files), 0, "No pack files created")
  1942. # Check pack file permissions
  1943. pack_path = os.path.join(pack_dir, pack_files[0])
  1944. actual_mode = self._get_file_mode(pack_path)
  1945. expected_mode = 0o664 # rw-rw-r--
  1946. self.assertEqual(
  1947. expected_mode,
  1948. actual_mode,
  1949. f"pack file mode: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  1950. )
  1951. def test_pack_index_permissions_group(self):
  1952. """Test that pack index files get correct permissions with sharedRepository=group."""
  1953. tmp_dir = tempfile.mkdtemp()
  1954. self.addCleanup(shutil.rmtree, tmp_dir)
  1955. # Set umask to 0 to see what permissions are actually set
  1956. os.umask(0)
  1957. repo = Repo.init_bare(tmp_dir, shared_repository="group")
  1958. self.addCleanup(repo.close)
  1959. # Create some objects
  1960. blobs = [
  1961. objects.Blob.from_string(f"test content {i}".encode()) for i in range(5)
  1962. ]
  1963. repo.object_store.add_objects([(blob, None) for blob in blobs])
  1964. # Find the pack index files
  1965. pack_dir = os.path.join(repo.commondir(), "objects", "pack")
  1966. idx_files = [f for f in os.listdir(pack_dir) if f.endswith(".idx")]
  1967. self.assertGreater(len(idx_files), 0, "No pack index files created")
  1968. # Check pack index file permissions
  1969. idx_path = os.path.join(pack_dir, idx_files[0])
  1970. actual_mode = self._get_file_mode(idx_path)
  1971. expected_mode = 0o664 # rw-rw-r--
  1972. self.assertEqual(
  1973. expected_mode,
  1974. actual_mode,
  1975. f"pack index mode: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  1976. )
  1977. def test_index_file_permissions_group(self):
  1978. """Test that index file gets correct permissions with sharedRepository=group."""
  1979. tmp_dir = tempfile.mkdtemp()
  1980. self.addCleanup(shutil.rmtree, tmp_dir)
  1981. # Set umask to 0 to see what permissions are actually set
  1982. os.umask(0)
  1983. # Create non-bare repo (index only exists in non-bare repos)
  1984. repo = Repo.init(tmp_dir, shared_repository="group")
  1985. self.addCleanup(repo.close)
  1986. # Make a change to trigger index write
  1987. blob = objects.Blob.from_string(b"test content")
  1988. repo.object_store.add_object(blob)
  1989. test_file = os.path.join(tmp_dir, "test.txt")
  1990. with open(test_file, "wb") as f:
  1991. f.write(b"test content")
  1992. # Stage the file
  1993. porcelain.add(repo, [test_file])
  1994. # Check index file permissions
  1995. index_path = repo.index_path()
  1996. actual_mode = self._get_file_mode(index_path)
  1997. expected_mode = 0o664 # rw-rw-r--
  1998. self.assertEqual(
  1999. expected_mode,
  2000. actual_mode,
  2001. f"index file mode: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  2002. )
  2003. def test_existing_repo_respects_config(self):
  2004. """Test that opening an existing repo respects core.sharedRepository config."""
  2005. tmp_dir = tempfile.mkdtemp()
  2006. self.addCleanup(shutil.rmtree, tmp_dir)
  2007. # Set umask to 0 to see what permissions are actually set
  2008. os.umask(0)
  2009. # Create repo with shared=group
  2010. repo = Repo.init_bare(tmp_dir, shared_repository="group")
  2011. repo.close()
  2012. # Reopen the repo
  2013. repo = Repo(tmp_dir)
  2014. self.addCleanup(repo.close)
  2015. # Add an object and check permissions
  2016. blob = objects.Blob.from_string(b"test content after reopen")
  2017. repo.object_store.add_object(blob)
  2018. obj_path = repo.object_store._get_shafile_path(blob.id)
  2019. actual_mode = self._get_file_mode(obj_path)
  2020. expected_mode = 0o664 # rw-rw-r--
  2021. self.assertEqual(
  2022. expected_mode,
  2023. actual_mode,
  2024. f"loose object mode after reopen: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  2025. )
  2026. def test_reflog_permissions_group(self):
  2027. """Test that reflog files get correct permissions with sharedRepository=group."""
  2028. tmp_dir = tempfile.mkdtemp()
  2029. self.addCleanup(shutil.rmtree, tmp_dir)
  2030. # Set umask to 0 to see what permissions are actually set
  2031. os.umask(0)
  2032. repo = Repo.init(tmp_dir, shared_repository="group")
  2033. self.addCleanup(repo.close)
  2034. # Create a commit to trigger reflog creation
  2035. blob = objects.Blob.from_string(b"test content")
  2036. tree = objects.Tree()
  2037. tree.add(b"test.txt", 0o100644, blob.id)
  2038. c = objects.Commit()
  2039. c.tree = tree.id
  2040. c.author = c.committer = b"Test <test@example.com>"
  2041. c.author_time = c.commit_time = int(time.time())
  2042. c.author_timezone = c.commit_timezone = 0
  2043. c.encoding = b"UTF-8"
  2044. c.message = b"Test commit"
  2045. repo.object_store.add_object(blob)
  2046. repo.object_store.add_object(tree)
  2047. repo.object_store.add_object(c)
  2048. # Update ref to trigger reflog creation
  2049. repo.refs.set_if_equals(
  2050. b"refs/heads/master", None, c.id, message=b"commit: initial commit"
  2051. )
  2052. # Check reflog file permissions
  2053. reflog_path = os.path.join(repo.controldir(), "logs", "refs", "heads", "master")
  2054. self.assertTrue(os.path.exists(reflog_path), "Reflog file should exist")
  2055. actual_mode = self._get_file_mode(reflog_path)
  2056. expected_mode = 0o664 # rw-rw-r--
  2057. self.assertEqual(
  2058. expected_mode,
  2059. actual_mode,
  2060. f"reflog file mode: expected {oct(expected_mode)}, got {oct(actual_mode)}",
  2061. )
  2062. # Check reflog directory permissions
  2063. reflog_dir = os.path.dirname(reflog_path)
  2064. actual_dir_mode = self._get_file_mode(reflog_dir)
  2065. expected_dir_mode = 0o2775 # setgid + rwxrwxr-x
  2066. self.assertEqual(
  2067. expected_dir_mode,
  2068. actual_dir_mode,
  2069. f"reflog dir mode: expected {oct(expected_dir_mode)}, got {oct(actual_dir_mode)}",
  2070. )