2
0

test_repository.py 57 KB

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