test_repository.py 54 KB

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