test_repository.py 55 KB

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