test_repository.py 55 KB

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