test_repository.py 73 KB

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