2
0

test_refs.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. # test_refs.py -- tests for refs.py
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for dulwich.refs."""
  22. import os
  23. import sys
  24. import tempfile
  25. from io import BytesIO
  26. from typing import ClassVar
  27. from dulwich import errors
  28. from dulwich.file import GitFile
  29. from dulwich.objects import ZERO_SHA
  30. from dulwich.refs import (
  31. DictRefsContainer,
  32. InfoRefsContainer,
  33. SymrefLoop,
  34. _split_ref_line,
  35. check_ref_format,
  36. parse_symref_value,
  37. read_packed_refs,
  38. read_packed_refs_with_peeled,
  39. split_peeled_refs,
  40. strip_peeled_refs,
  41. write_packed_refs,
  42. )
  43. from dulwich.repo import Repo
  44. from dulwich.tests.utils import open_repo, tear_down_repo
  45. from . import SkipTest, TestCase
  46. class CheckRefFormatTests(TestCase):
  47. """Tests for the check_ref_format function.
  48. These are the same tests as in the git test suite.
  49. """
  50. def test_valid(self) -> None:
  51. self.assertTrue(check_ref_format(b"heads/foo"))
  52. self.assertTrue(check_ref_format(b"foo/bar/baz"))
  53. self.assertTrue(check_ref_format(b"refs///heads/foo"))
  54. self.assertTrue(check_ref_format(b"foo./bar"))
  55. self.assertTrue(check_ref_format(b"heads/foo@bar"))
  56. self.assertTrue(check_ref_format(b"heads/fix.lock.error"))
  57. def test_invalid(self) -> None:
  58. self.assertFalse(check_ref_format(b"foo"))
  59. self.assertFalse(check_ref_format(b"heads/foo/"))
  60. self.assertFalse(check_ref_format(b"./foo"))
  61. self.assertFalse(check_ref_format(b".refs/foo"))
  62. self.assertFalse(check_ref_format(b"heads/foo..bar"))
  63. self.assertFalse(check_ref_format(b"heads/foo?bar"))
  64. self.assertFalse(check_ref_format(b"heads/foo.lock"))
  65. self.assertFalse(check_ref_format(b"heads/v@{ation"))
  66. self.assertFalse(check_ref_format(b"heads/foo\bar"))
  67. ONES = b"1" * 40
  68. TWOS = b"2" * 40
  69. THREES = b"3" * 40
  70. FOURS = b"4" * 40
  71. class PackedRefsFileTests(TestCase):
  72. def test_split_ref_line_errors(self) -> None:
  73. self.assertRaises(errors.PackedRefsException, _split_ref_line, b"singlefield")
  74. self.assertRaises(errors.PackedRefsException, _split_ref_line, b"badsha name")
  75. self.assertRaises(
  76. errors.PackedRefsException,
  77. _split_ref_line,
  78. ONES + b" bad/../refname",
  79. )
  80. def test_read_without_peeled(self) -> None:
  81. f = BytesIO(b"\n".join([b"# comment", ONES + b" ref/1", TWOS + b" ref/2"]))
  82. self.assertEqual(
  83. [(ONES, b"ref/1"), (TWOS, b"ref/2")], list(read_packed_refs(f))
  84. )
  85. def test_read_without_peeled_errors(self) -> None:
  86. f = BytesIO(b"\n".join([ONES + b" ref/1", b"^" + TWOS]))
  87. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  88. def test_read_with_peeled(self) -> None:
  89. f = BytesIO(
  90. b"\n".join(
  91. [
  92. ONES + b" ref/1",
  93. TWOS + b" ref/2",
  94. b"^" + THREES,
  95. FOURS + b" ref/4",
  96. ]
  97. )
  98. )
  99. self.assertEqual(
  100. [
  101. (ONES, b"ref/1", None),
  102. (TWOS, b"ref/2", THREES),
  103. (FOURS, b"ref/4", None),
  104. ],
  105. list(read_packed_refs_with_peeled(f)),
  106. )
  107. def test_read_with_peeled_errors(self) -> None:
  108. f = BytesIO(b"\n".join([b"^" + TWOS, ONES + b" ref/1"]))
  109. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  110. f = BytesIO(b"\n".join([ONES + b" ref/1", b"^" + TWOS, b"^" + THREES]))
  111. self.assertRaises(errors.PackedRefsException, list, read_packed_refs(f))
  112. def test_write_with_peeled(self) -> None:
  113. f = BytesIO()
  114. write_packed_refs(f, {b"ref/1": ONES, b"ref/2": TWOS}, {b"ref/1": THREES})
  115. self.assertEqual(
  116. b"\n".join(
  117. [
  118. b"# pack-refs with: peeled",
  119. ONES + b" ref/1",
  120. b"^" + THREES,
  121. TWOS + b" ref/2",
  122. ]
  123. )
  124. + b"\n",
  125. f.getvalue(),
  126. )
  127. def test_write_without_peeled(self) -> None:
  128. f = BytesIO()
  129. write_packed_refs(f, {b"ref/1": ONES, b"ref/2": TWOS})
  130. self.assertEqual(
  131. b"\n".join([ONES + b" ref/1", TWOS + b" ref/2"]) + b"\n",
  132. f.getvalue(),
  133. )
  134. # Dict of refs that we expect all RefsContainerTests subclasses to define.
  135. _TEST_REFS = {
  136. b"HEAD": b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  137. b"refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa": b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  138. b"refs/heads/master": b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  139. b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  140. b"refs/tags/refs-0.1": b"df6800012397fb85c56e7418dd4eb9405dee075c",
  141. b"refs/tags/refs-0.2": b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8",
  142. b"refs/heads/loop": b"ref: refs/heads/loop",
  143. }
  144. class RefsContainerTests:
  145. def test_keys(self) -> None:
  146. actual_keys = set(self._refs.keys())
  147. self.assertEqual(set(self._refs.allkeys()), actual_keys)
  148. self.assertEqual(set(_TEST_REFS.keys()), actual_keys)
  149. actual_keys = self._refs.keys(b"refs/heads")
  150. actual_keys.discard(b"loop")
  151. self.assertEqual(
  152. [b"40-char-ref-aaaaaaaaaaaaaaaaaa", b"master", b"packed"],
  153. sorted(actual_keys),
  154. )
  155. self.assertEqual(
  156. [b"refs-0.1", b"refs-0.2"], sorted(self._refs.keys(b"refs/tags"))
  157. )
  158. def test_iter(self) -> None:
  159. actual_keys = set(self._refs.keys())
  160. self.assertEqual(set(self._refs), actual_keys)
  161. self.assertEqual(set(_TEST_REFS.keys()), actual_keys)
  162. def test_as_dict(self) -> None:
  163. # refs/heads/loop does not show up even if it exists
  164. expected_refs = dict(_TEST_REFS)
  165. del expected_refs[b"refs/heads/loop"]
  166. self.assertEqual(expected_refs, self._refs.as_dict())
  167. def test_get_symrefs(self) -> None:
  168. self._refs.set_symbolic_ref(b"refs/heads/src", b"refs/heads/dst")
  169. symrefs = self._refs.get_symrefs()
  170. if b"HEAD" in symrefs:
  171. symrefs.pop(b"HEAD")
  172. self.assertEqual(
  173. {
  174. b"refs/heads/src": b"refs/heads/dst",
  175. b"refs/heads/loop": b"refs/heads/loop",
  176. },
  177. symrefs,
  178. )
  179. def test_setitem(self) -> None:
  180. self._refs[b"refs/some/ref"] = b"42d06bd4b77fed026b154d16493e5deab78f02ec"
  181. self.assertEqual(
  182. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  183. self._refs[b"refs/some/ref"],
  184. )
  185. # should accept symref
  186. self._refs[b"refs/heads/symbolic"] = b"ref: refs/heads/master"
  187. self.assertEqual(
  188. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  189. self._refs[b"refs/heads/symbolic"],
  190. )
  191. # should not accept bad ref names
  192. self.assertRaises(
  193. errors.RefFormatError,
  194. self._refs.__setitem__,
  195. b"notrefs/foo",
  196. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  197. )
  198. # should not accept short sha
  199. self.assertRaises(
  200. ValueError,
  201. self._refs.__setitem__,
  202. b"refs/some/ref",
  203. b"42d06bd",
  204. )
  205. def test_set_if_equals(self) -> None:
  206. nines = b"9" * 40
  207. self.assertFalse(self._refs.set_if_equals(b"HEAD", b"c0ffee", nines))
  208. self.assertEqual(
  209. b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"HEAD"]
  210. )
  211. self.assertTrue(
  212. self._refs.set_if_equals(
  213. b"HEAD", b"42d06bd4b77fed026b154d16493e5deab78f02ec", nines
  214. )
  215. )
  216. self.assertEqual(nines, self._refs[b"HEAD"])
  217. # Setting the ref again is a no-op, but will return True.
  218. self.assertTrue(self._refs.set_if_equals(b"HEAD", nines, nines))
  219. self.assertEqual(nines, self._refs[b"HEAD"])
  220. self.assertTrue(self._refs.set_if_equals(b"refs/heads/master", None, nines))
  221. self.assertEqual(nines, self._refs[b"refs/heads/master"])
  222. self.assertTrue(
  223. self._refs.set_if_equals(b"refs/heads/nonexistent", ZERO_SHA, nines)
  224. )
  225. self.assertEqual(nines, self._refs[b"refs/heads/nonexistent"])
  226. def test_add_if_new(self) -> None:
  227. nines = b"9" * 40
  228. self.assertFalse(self._refs.add_if_new(b"refs/heads/master", nines))
  229. self.assertEqual(
  230. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  231. self._refs[b"refs/heads/master"],
  232. )
  233. self.assertTrue(self._refs.add_if_new(b"refs/some/ref", nines))
  234. self.assertEqual(nines, self._refs[b"refs/some/ref"])
  235. def test_set_symbolic_ref(self) -> None:
  236. self._refs.set_symbolic_ref(b"refs/heads/symbolic", b"refs/heads/master")
  237. self.assertEqual(
  238. b"ref: refs/heads/master",
  239. self._refs.read_loose_ref(b"refs/heads/symbolic"),
  240. )
  241. self.assertEqual(
  242. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  243. self._refs[b"refs/heads/symbolic"],
  244. )
  245. def test_set_symbolic_ref_overwrite(self) -> None:
  246. nines = b"9" * 40
  247. self.assertNotIn(b"refs/heads/symbolic", self._refs)
  248. self._refs[b"refs/heads/symbolic"] = nines
  249. self.assertEqual(nines, self._refs.read_loose_ref(b"refs/heads/symbolic"))
  250. self._refs.set_symbolic_ref(b"refs/heads/symbolic", b"refs/heads/master")
  251. self.assertEqual(
  252. b"ref: refs/heads/master",
  253. self._refs.read_loose_ref(b"refs/heads/symbolic"),
  254. )
  255. self.assertEqual(
  256. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  257. self._refs[b"refs/heads/symbolic"],
  258. )
  259. def test_check_refname(self) -> None:
  260. self._refs._check_refname(b"HEAD")
  261. self._refs._check_refname(b"refs/stash")
  262. self._refs._check_refname(b"refs/heads/foo")
  263. self.assertRaises(errors.RefFormatError, self._refs._check_refname, b"refs")
  264. self.assertRaises(
  265. errors.RefFormatError, self._refs._check_refname, b"notrefs/foo"
  266. )
  267. def test_contains(self) -> None:
  268. self.assertIn(b"refs/heads/master", self._refs)
  269. self.assertNotIn(b"refs/heads/bar", self._refs)
  270. def test_delitem(self) -> None:
  271. self.assertEqual(
  272. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  273. self._refs[b"refs/heads/master"],
  274. )
  275. del self._refs[b"refs/heads/master"]
  276. self.assertRaises(KeyError, lambda: self._refs[b"refs/heads/master"])
  277. def test_remove_if_equals(self) -> None:
  278. self.assertFalse(self._refs.remove_if_equals(b"HEAD", b"c0ffee"))
  279. self.assertEqual(
  280. b"42d06bd4b77fed026b154d16493e5deab78f02ec", self._refs[b"HEAD"]
  281. )
  282. self.assertTrue(
  283. self._refs.remove_if_equals(
  284. b"refs/tags/refs-0.2",
  285. b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8",
  286. )
  287. )
  288. self.assertTrue(self._refs.remove_if_equals(b"refs/tags/refs-0.2", ZERO_SHA))
  289. self.assertNotIn(b"refs/tags/refs-0.2", self._refs)
  290. def test_import_refs_name(self) -> None:
  291. self._refs[b"refs/remotes/origin/other"] = (
  292. b"48d01bd4b77fed026b154d16493e5deab78f02ec"
  293. )
  294. self._refs.import_refs(
  295. b"refs/remotes/origin",
  296. {b"master": b"42d06bd4b77fed026b154d16493e5deab78f02ec"},
  297. )
  298. self.assertEqual(
  299. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  300. self._refs[b"refs/remotes/origin/master"],
  301. )
  302. self.assertEqual(
  303. b"48d01bd4b77fed026b154d16493e5deab78f02ec",
  304. self._refs[b"refs/remotes/origin/other"],
  305. )
  306. def test_import_refs_name_prune(self) -> None:
  307. self._refs[b"refs/remotes/origin/other"] = (
  308. b"48d01bd4b77fed026b154d16493e5deab78f02ec"
  309. )
  310. self._refs.import_refs(
  311. b"refs/remotes/origin",
  312. {b"master": b"42d06bd4b77fed026b154d16493e5deab78f02ec"},
  313. prune=True,
  314. )
  315. self.assertEqual(
  316. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  317. self._refs[b"refs/remotes/origin/master"],
  318. )
  319. self.assertNotIn(b"refs/remotes/origin/other", self._refs)
  320. class DictRefsContainerTests(RefsContainerTests, TestCase):
  321. def setUp(self) -> None:
  322. TestCase.setUp(self)
  323. self._refs = DictRefsContainer(dict(_TEST_REFS))
  324. def test_invalid_refname(self) -> None:
  325. # FIXME: Move this test into RefsContainerTests, but requires
  326. # some way of injecting invalid refs.
  327. self._refs._refs[b"refs/stash"] = b"00" * 20
  328. expected_refs = dict(_TEST_REFS)
  329. del expected_refs[b"refs/heads/loop"]
  330. expected_refs[b"refs/stash"] = b"00" * 20
  331. self.assertEqual(expected_refs, self._refs.as_dict())
  332. class DiskRefsContainerTests(RefsContainerTests, TestCase):
  333. def setUp(self) -> None:
  334. TestCase.setUp(self)
  335. self._repo = open_repo("refs.git")
  336. self.addCleanup(tear_down_repo, self._repo)
  337. self._refs = self._repo.refs
  338. def test_get_packed_refs(self) -> None:
  339. self.assertEqual(
  340. {
  341. b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  342. b"refs/tags/refs-0.1": b"df6800012397fb85c56e7418dd4eb9405dee075c",
  343. },
  344. self._refs.get_packed_refs(),
  345. )
  346. def test_get_peeled_not_packed(self) -> None:
  347. # not packed
  348. self.assertEqual(None, self._refs.get_peeled(b"refs/tags/refs-0.2"))
  349. self.assertEqual(
  350. b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8",
  351. self._refs[b"refs/tags/refs-0.2"],
  352. )
  353. # packed, known not peelable
  354. self.assertEqual(
  355. self._refs[b"refs/heads/packed"],
  356. self._refs.get_peeled(b"refs/heads/packed"),
  357. )
  358. # packed, peeled
  359. self.assertEqual(
  360. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  361. self._refs.get_peeled(b"refs/tags/refs-0.1"),
  362. )
  363. def test_setitem(self) -> None:
  364. RefsContainerTests.test_setitem(self)
  365. path = os.path.join(self._refs.path, b"refs", b"some", b"ref")
  366. with open(path, "rb") as f:
  367. self.assertEqual(b"42d06bd4b77fed026b154d16493e5deab78f02ec", f.read()[:40])
  368. self.assertRaises(
  369. OSError,
  370. self._refs.__setitem__,
  371. b"refs/some/ref/sub",
  372. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  373. )
  374. def test_delete_refs_container(self) -> None:
  375. # We shouldn't delete the refs directory
  376. self._refs[b"refs/heads/blah"] = b"42d06bd4b77fed026b154d16493e5deab78f02ec"
  377. for ref in self._refs.allkeys():
  378. del self._refs[ref]
  379. self.assertTrue(os.path.exists(os.path.join(self._refs.path, b"refs")))
  380. def test_setitem_packed(self) -> None:
  381. with open(os.path.join(self._refs.path, b"packed-refs"), "w") as f:
  382. f.write("# pack-refs with: peeled fully-peeled sorted \n")
  383. f.write("42d06bd4b77fed026b154d16493e5deab78f02ec refs/heads/packed\n")
  384. # It's allowed to set a new ref on a packed ref, the new ref will be
  385. # placed outside on refs/
  386. self._refs[b"refs/heads/packed"] = b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8"
  387. packed_ref_path = os.path.join(self._refs.path, b"refs", b"heads", b"packed")
  388. with open(packed_ref_path, "rb") as f:
  389. self.assertEqual(b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8", f.read()[:40])
  390. self.assertRaises(
  391. OSError,
  392. self._refs.__setitem__,
  393. b"refs/heads/packed/sub",
  394. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  395. )
  396. # this shouldn't overwrite the packed refs
  397. self.assertEqual(
  398. {b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec"},
  399. self._refs.get_packed_refs(),
  400. )
  401. def test_add_packed_refs(self) -> None:
  402. # first, create a non-packed ref
  403. self._refs[b"refs/heads/packed"] = b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8"
  404. packed_ref_path = os.path.join(self._refs.path, b"refs", b"heads", b"packed")
  405. self.assertTrue(os.path.exists(packed_ref_path))
  406. # now overwrite that with a packed ref
  407. packed_refs_file_path = os.path.join(self._refs.path, b"packed-refs")
  408. self._refs.add_packed_refs(
  409. {
  410. b"refs/heads/packed": b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  411. }
  412. )
  413. # that should kill the file
  414. self.assertFalse(os.path.exists(packed_ref_path))
  415. # now delete the packed ref
  416. self._refs.add_packed_refs(
  417. {
  418. b"refs/heads/packed": None,
  419. }
  420. )
  421. # and it's gone!
  422. self.assertFalse(os.path.exists(packed_ref_path))
  423. self.assertRaises(
  424. KeyError,
  425. self._refs.__getitem__,
  426. b"refs/heads/packed",
  427. )
  428. # just in case, make sure we can't pack HEAD
  429. self.assertRaises(
  430. ValueError,
  431. self._refs.add_packed_refs,
  432. {b"HEAD": "02ac81614bcdbd585a37b4b0edf8cb8a"},
  433. )
  434. # delete all packed refs
  435. self._refs.add_packed_refs({ref: None for ref in self._refs.get_packed_refs()})
  436. self.assertEqual({}, self._refs.get_packed_refs())
  437. # remove the packed ref file, and check that adding nothing doesn't affect that
  438. os.remove(packed_refs_file_path)
  439. # adding nothing doesn't make it reappear
  440. self._refs.add_packed_refs({})
  441. self.assertFalse(os.path.exists(packed_refs_file_path))
  442. def test_setitem_symbolic(self) -> None:
  443. ones = b"1" * 40
  444. self._refs[b"HEAD"] = ones
  445. self.assertEqual(ones, self._refs[b"HEAD"])
  446. # ensure HEAD was not modified
  447. f = open(os.path.join(self._refs.path, b"HEAD"), "rb")
  448. v = next(iter(f)).rstrip(b"\n\r")
  449. f.close()
  450. self.assertEqual(b"ref: refs/heads/master", v)
  451. # ensure the symbolic link was written through
  452. f = open(os.path.join(self._refs.path, b"refs", b"heads", b"master"), "rb")
  453. self.assertEqual(ones, f.read()[:40])
  454. f.close()
  455. def test_set_if_equals(self) -> None:
  456. RefsContainerTests.test_set_if_equals(self)
  457. # ensure symref was followed
  458. self.assertEqual(b"9" * 40, self._refs[b"refs/heads/master"])
  459. # ensure lockfile was deleted
  460. self.assertFalse(
  461. os.path.exists(
  462. os.path.join(self._refs.path, b"refs", b"heads", b"master.lock")
  463. )
  464. )
  465. self.assertFalse(os.path.exists(os.path.join(self._refs.path, b"HEAD.lock")))
  466. def test_add_if_new_packed(self) -> None:
  467. # don't overwrite packed ref
  468. self.assertFalse(self._refs.add_if_new(b"refs/tags/refs-0.1", b"9" * 40))
  469. self.assertEqual(
  470. b"df6800012397fb85c56e7418dd4eb9405dee075c",
  471. self._refs[b"refs/tags/refs-0.1"],
  472. )
  473. def test_add_if_new_symbolic(self) -> None:
  474. # Use an empty repo instead of the default.
  475. repo_dir = os.path.join(tempfile.mkdtemp(), "test")
  476. os.makedirs(repo_dir)
  477. repo = Repo.init(repo_dir)
  478. self.addCleanup(tear_down_repo, repo)
  479. refs = repo.refs
  480. nines = b"9" * 40
  481. self.assertEqual(b"ref: refs/heads/master", refs.read_ref(b"HEAD"))
  482. self.assertNotIn(b"refs/heads/master", refs)
  483. self.assertTrue(refs.add_if_new(b"HEAD", nines))
  484. self.assertEqual(b"ref: refs/heads/master", refs.read_ref(b"HEAD"))
  485. self.assertEqual(nines, refs[b"HEAD"])
  486. self.assertEqual(nines, refs[b"refs/heads/master"])
  487. self.assertFalse(refs.add_if_new(b"HEAD", b"1" * 40))
  488. self.assertEqual(nines, refs[b"HEAD"])
  489. self.assertEqual(nines, refs[b"refs/heads/master"])
  490. def test_follow(self) -> None:
  491. self.assertEqual(
  492. (
  493. [b"HEAD", b"refs/heads/master"],
  494. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  495. ),
  496. self._refs.follow(b"HEAD"),
  497. )
  498. self.assertEqual(
  499. (
  500. [b"refs/heads/master"],
  501. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  502. ),
  503. self._refs.follow(b"refs/heads/master"),
  504. )
  505. self.assertRaises(SymrefLoop, self._refs.follow, b"refs/heads/loop")
  506. def test_set_overwrite_loop(self) -> None:
  507. self.assertRaises(SymrefLoop, self._refs.follow, b"refs/heads/loop")
  508. self._refs[b"refs/heads/loop"] = b"42d06bd4b77fed026b154d16493e5deab78f02ec"
  509. self.assertEqual(
  510. ([b"refs/heads/loop"], b"42d06bd4b77fed026b154d16493e5deab78f02ec"),
  511. self._refs.follow(b"refs/heads/loop"),
  512. )
  513. def test_delitem(self) -> None:
  514. RefsContainerTests.test_delitem(self)
  515. ref_file = os.path.join(self._refs.path, b"refs", b"heads", b"master")
  516. self.assertFalse(os.path.exists(ref_file))
  517. self.assertNotIn(b"refs/heads/master", self._refs.get_packed_refs())
  518. def test_delitem_symbolic(self) -> None:
  519. self.assertEqual(b"ref: refs/heads/master", self._refs.read_loose_ref(b"HEAD"))
  520. del self._refs[b"HEAD"]
  521. self.assertRaises(KeyError, lambda: self._refs[b"HEAD"])
  522. self.assertEqual(
  523. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  524. self._refs[b"refs/heads/master"],
  525. )
  526. self.assertFalse(os.path.exists(os.path.join(self._refs.path, b"HEAD")))
  527. def test_remove_if_equals_symref(self) -> None:
  528. # HEAD is a symref, so shouldn't equal its dereferenced value
  529. self.assertFalse(
  530. self._refs.remove_if_equals(
  531. b"HEAD", b"42d06bd4b77fed026b154d16493e5deab78f02ec"
  532. )
  533. )
  534. self.assertTrue(
  535. self._refs.remove_if_equals(
  536. b"refs/heads/master",
  537. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  538. )
  539. )
  540. self.assertRaises(KeyError, lambda: self._refs[b"refs/heads/master"])
  541. # HEAD is now a broken symref
  542. self.assertRaises(KeyError, lambda: self._refs[b"HEAD"])
  543. self.assertEqual(b"ref: refs/heads/master", self._refs.read_loose_ref(b"HEAD"))
  544. self.assertFalse(
  545. os.path.exists(
  546. os.path.join(self._refs.path, b"refs", b"heads", b"master.lock")
  547. )
  548. )
  549. self.assertFalse(os.path.exists(os.path.join(self._refs.path, b"HEAD.lock")))
  550. def test_remove_packed_without_peeled(self) -> None:
  551. refs_file = os.path.join(self._repo.path, "packed-refs")
  552. f = GitFile(refs_file)
  553. refs_data = f.read()
  554. f.close()
  555. f = GitFile(refs_file, "wb")
  556. f.write(
  557. b"\n".join(
  558. line
  559. for line in refs_data.split(b"\n")
  560. if not line or line[0] not in b"#^"
  561. )
  562. )
  563. f.close()
  564. self._repo = Repo(self._repo.path)
  565. refs = self._repo.refs
  566. self.assertTrue(
  567. refs.remove_if_equals(
  568. b"refs/heads/packed",
  569. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  570. )
  571. )
  572. def test_remove_if_equals_packed(self) -> None:
  573. # test removing ref that is only packed
  574. self.assertEqual(
  575. b"df6800012397fb85c56e7418dd4eb9405dee075c",
  576. self._refs[b"refs/tags/refs-0.1"],
  577. )
  578. self.assertTrue(
  579. self._refs.remove_if_equals(
  580. b"refs/tags/refs-0.1",
  581. b"df6800012397fb85c56e7418dd4eb9405dee075c",
  582. )
  583. )
  584. self.assertRaises(KeyError, lambda: self._refs[b"refs/tags/refs-0.1"])
  585. def test_remove_parent(self) -> None:
  586. self._refs[b"refs/heads/foo/bar"] = b"df6800012397fb85c56e7418dd4eb9405dee075c"
  587. del self._refs[b"refs/heads/foo/bar"]
  588. ref_file = os.path.join(
  589. self._refs.path,
  590. b"refs",
  591. b"heads",
  592. b"foo",
  593. b"bar",
  594. )
  595. self.assertFalse(os.path.exists(ref_file))
  596. ref_file = os.path.join(self._refs.path, b"refs", b"heads", b"foo")
  597. self.assertFalse(os.path.exists(ref_file))
  598. ref_file = os.path.join(self._refs.path, b"refs", b"heads")
  599. self.assertTrue(os.path.exists(ref_file))
  600. self._refs[b"refs/heads/foo"] = b"df6800012397fb85c56e7418dd4eb9405dee075c"
  601. def test_read_ref(self) -> None:
  602. self.assertEqual(b"ref: refs/heads/master", self._refs.read_ref(b"HEAD"))
  603. self.assertEqual(
  604. b"42d06bd4b77fed026b154d16493e5deab78f02ec",
  605. self._refs.read_ref(b"refs/heads/packed"),
  606. )
  607. self.assertEqual(None, self._refs.read_ref(b"nonexistent"))
  608. def test_read_loose_ref(self) -> None:
  609. self._refs[b"refs/heads/foo"] = b"df6800012397fb85c56e7418dd4eb9405dee075c"
  610. self.assertEqual(None, self._refs.read_ref(b"refs/heads/foo/bar"))
  611. def test_non_ascii(self) -> None:
  612. try:
  613. encoded_ref = os.fsencode("refs/tags/schön")
  614. except UnicodeEncodeError as exc:
  615. raise SkipTest(
  616. "filesystem encoding doesn't support special character"
  617. ) from exc
  618. p = os.path.join(os.fsencode(self._repo.path), encoded_ref)
  619. with open(p, "w") as f:
  620. f.write("00" * 20)
  621. expected_refs = dict(_TEST_REFS)
  622. expected_refs[encoded_ref] = b"00" * 20
  623. del expected_refs[b"refs/heads/loop"]
  624. self.assertEqual(expected_refs, self._repo.get_refs())
  625. def test_cyrillic(self) -> None:
  626. if sys.platform in ("darwin", "win32"):
  627. raise SkipTest("filesystem encoding doesn't support arbitrary bytes")
  628. # reported in https://github.com/dulwich/dulwich/issues/608
  629. name = b"\xcd\xee\xe2\xe0\xff\xe2\xe5\xf2\xea\xe01"
  630. encoded_ref = b"refs/heads/" + name
  631. with open(os.path.join(os.fsencode(self._repo.path), encoded_ref), "w") as f:
  632. f.write("00" * 20)
  633. expected_refs = set(_TEST_REFS.keys())
  634. expected_refs.add(encoded_ref)
  635. self.assertEqual(expected_refs, set(self._repo.refs.allkeys()))
  636. self.assertEqual(
  637. {r[len(b"refs/") :] for r in expected_refs if r.startswith(b"refs/")},
  638. set(self._repo.refs.subkeys(b"refs/")),
  639. )
  640. expected_refs.remove(b"refs/heads/loop")
  641. expected_refs.add(b"HEAD")
  642. self.assertEqual(expected_refs, set(self._repo.get_refs().keys()))
  643. _TEST_REFS_SERIALIZED = (
  644. b"42d06bd4b77fed026b154d16493e5deab78f02ec\t"
  645. b"refs/heads/40-char-ref-aaaaaaaaaaaaaaaaaa\n"
  646. b"42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/master\n"
  647. b"42d06bd4b77fed026b154d16493e5deab78f02ec\trefs/heads/packed\n"
  648. b"df6800012397fb85c56e7418dd4eb9405dee075c\trefs/tags/refs-0.1\n"
  649. b"3ec9c43c84ff242e3ef4a9fc5bc111fd780a76a8\trefs/tags/refs-0.2\n"
  650. )
  651. class InfoRefsContainerTests(TestCase):
  652. def test_invalid_refname(self) -> None:
  653. text = _TEST_REFS_SERIALIZED + b"00" * 20 + b"\trefs/stash\n"
  654. refs = InfoRefsContainer(BytesIO(text))
  655. expected_refs = dict(_TEST_REFS)
  656. del expected_refs[b"HEAD"]
  657. expected_refs[b"refs/stash"] = b"00" * 20
  658. del expected_refs[b"refs/heads/loop"]
  659. self.assertEqual(expected_refs, refs.as_dict())
  660. def test_keys(self) -> None:
  661. refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED))
  662. actual_keys = set(refs.keys())
  663. self.assertEqual(set(refs.allkeys()), actual_keys)
  664. expected_refs = dict(_TEST_REFS)
  665. del expected_refs[b"HEAD"]
  666. del expected_refs[b"refs/heads/loop"]
  667. self.assertEqual(set(expected_refs.keys()), actual_keys)
  668. actual_keys = refs.keys(b"refs/heads")
  669. actual_keys.discard(b"loop")
  670. self.assertEqual(
  671. [b"40-char-ref-aaaaaaaaaaaaaaaaaa", b"master", b"packed"],
  672. sorted(actual_keys),
  673. )
  674. self.assertEqual([b"refs-0.1", b"refs-0.2"], sorted(refs.keys(b"refs/tags")))
  675. def test_as_dict(self) -> None:
  676. refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED))
  677. # refs/heads/loop does not show up even if it exists
  678. expected_refs = dict(_TEST_REFS)
  679. del expected_refs[b"HEAD"]
  680. del expected_refs[b"refs/heads/loop"]
  681. self.assertEqual(expected_refs, refs.as_dict())
  682. def test_contains(self) -> None:
  683. refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED))
  684. self.assertIn(b"refs/heads/master", refs)
  685. self.assertNotIn(b"refs/heads/bar", refs)
  686. def test_get_peeled(self) -> None:
  687. refs = InfoRefsContainer(BytesIO(_TEST_REFS_SERIALIZED))
  688. # refs/heads/loop does not show up even if it exists
  689. self.assertEqual(
  690. _TEST_REFS[b"refs/heads/master"],
  691. refs.get_peeled(b"refs/heads/master"),
  692. )
  693. class ParseSymrefValueTests(TestCase):
  694. def test_valid(self) -> None:
  695. self.assertEqual(b"refs/heads/foo", parse_symref_value(b"ref: refs/heads/foo"))
  696. def test_invalid(self) -> None:
  697. self.assertRaises(ValueError, parse_symref_value, b"foobar")
  698. class StripPeeledRefsTests(TestCase):
  699. all_refs: ClassVar[dict[bytes, bytes]] = {
  700. b"refs/heads/master": b"8843d7f92416211de9ebb963ff4ce28125932878",
  701. b"refs/heads/testing": b"186a005b134d8639a58b6731c7c1ea821a6eedba",
  702. b"refs/tags/1.0.0": b"a93db4b0360cc635a2b93675010bac8d101f73f0",
  703. b"refs/tags/1.0.0^{}": b"a93db4b0360cc635a2b93675010bac8d101f73f0",
  704. b"refs/tags/2.0.0": b"0749936d0956c661ac8f8d3483774509c165f89e",
  705. b"refs/tags/2.0.0^{}": b"0749936d0956c661ac8f8d3483774509c165f89e",
  706. }
  707. non_peeled_refs: ClassVar[dict[bytes, bytes]] = {
  708. b"refs/heads/master": b"8843d7f92416211de9ebb963ff4ce28125932878",
  709. b"refs/heads/testing": b"186a005b134d8639a58b6731c7c1ea821a6eedba",
  710. b"refs/tags/1.0.0": b"a93db4b0360cc635a2b93675010bac8d101f73f0",
  711. b"refs/tags/2.0.0": b"0749936d0956c661ac8f8d3483774509c165f89e",
  712. }
  713. def test_strip_peeled_refs(self) -> None:
  714. # Simple check of two dicts
  715. self.assertEqual(strip_peeled_refs(self.all_refs), self.non_peeled_refs)
  716. def test_split_peeled_refs(self) -> None:
  717. (regular, peeled) = split_peeled_refs(self.all_refs)
  718. self.assertEqual(regular, self.non_peeled_refs)
  719. self.assertEqual(
  720. peeled,
  721. {
  722. b"refs/tags/2.0.0": b"0749936d0956c661ac8f8d3483774509c165f89e",
  723. b"refs/tags/1.0.0": b"a93db4b0360cc635a2b93675010bac8d101f73f0",
  724. },
  725. )