test_repository.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. # -*- coding: utf-8 -*-
  2. # test_repository.py -- tests for repository.py
  3. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; version 2
  8. # of the License or (at your option) any later version of
  9. # the License.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. # MA 02110-1301, USA.
  20. """Tests for the repository."""
  21. from contextlib import closing
  22. import locale
  23. import os
  24. import stat
  25. import shutil
  26. import sys
  27. import tempfile
  28. import warnings
  29. from dulwich import errors
  30. from dulwich.object_store import (
  31. tree_lookup_path,
  32. )
  33. from dulwich import objects
  34. from dulwich.config import Config
  35. from dulwich.errors import NotGitRepository
  36. from dulwich.repo import (
  37. Repo,
  38. MemoryRepo,
  39. )
  40. from dulwich.tests import (
  41. TestCase,
  42. skipIf,
  43. )
  44. from dulwich.tests.utils import (
  45. open_repo,
  46. tear_down_repo,
  47. setup_warning_catcher,
  48. )
  49. missing_sha = b'b91fa4d900e17e99b433218e988c4eb4a3e9a097'
  50. class CreateRepositoryTests(TestCase):
  51. def assertFileContentsEqual(self, expected, repo, path):
  52. f = repo.get_named_file(path)
  53. if not f:
  54. self.assertEqual(expected, None)
  55. else:
  56. with f:
  57. self.assertEqual(expected, f.read())
  58. def _check_repo_contents(self, repo, expect_bare):
  59. self.assertEqual(expect_bare, repo.bare)
  60. self.assertFileContentsEqual(b'Unnamed repository', repo, 'description')
  61. self.assertFileContentsEqual(b'', repo, os.path.join('info', 'exclude'))
  62. self.assertFileContentsEqual(None, repo, 'nonexistent file')
  63. barestr = b'bare = ' + str(expect_bare).lower().encode('ascii')
  64. with repo.get_named_file('config') as f:
  65. config_text = f.read()
  66. self.assertTrue(barestr in config_text, "%r" % config_text)
  67. def test_create_memory(self):
  68. repo = MemoryRepo.init_bare([], {})
  69. self._check_repo_contents(repo, True)
  70. def test_create_disk_bare(self):
  71. tmp_dir = tempfile.mkdtemp()
  72. self.addCleanup(shutil.rmtree, tmp_dir)
  73. repo = Repo.init_bare(tmp_dir)
  74. self.assertEqual(tmp_dir, repo._controldir)
  75. self._check_repo_contents(repo, True)
  76. def test_create_disk_non_bare(self):
  77. tmp_dir = tempfile.mkdtemp()
  78. self.addCleanup(shutil.rmtree, tmp_dir)
  79. repo = Repo.init(tmp_dir)
  80. self.assertEqual(os.path.join(tmp_dir, '.git'), repo._controldir)
  81. self._check_repo_contents(repo, False)
  82. class RepositoryRootTests(TestCase):
  83. def mkdtemp(self):
  84. return tempfile.mkdtemp()
  85. def open_repo(self, name):
  86. temp_dir = self.mkdtemp()
  87. repo = open_repo(name, temp_dir)
  88. self.addCleanup(tear_down_repo, repo)
  89. return repo
  90. def test_simple_props(self):
  91. r = self.open_repo('a.git')
  92. self.assertEqual(r.controldir(), r.path)
  93. def test_setitem(self):
  94. r = self.open_repo('a.git')
  95. r[b"refs/tags/foo"] = b'a90fa2d900a17e99b433217e988c4eb4a2e9a097'
  96. self.assertEqual(b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  97. r[b"refs/tags/foo"].id)
  98. def test_getitem_unicode(self):
  99. r = self.open_repo('a.git')
  100. test_keys = [
  101. (b'refs/heads/master', True),
  102. (b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', True),
  103. (b'11' * 19 + b'--', False),
  104. ]
  105. for k, contained in test_keys:
  106. self.assertEqual(k in r, contained)
  107. # Avoid deprecation warning under Py3.2+
  108. if getattr(self, 'assertRaisesRegex', None):
  109. assertRaisesRegexp = self.assertRaisesRegex
  110. else:
  111. assertRaisesRegexp = self.assertRaisesRegexp
  112. for k, _ in test_keys:
  113. assertRaisesRegexp(
  114. TypeError, "'name' must be bytestring, not int",
  115. r.__getitem__, 12
  116. )
  117. def test_delitem(self):
  118. r = self.open_repo('a.git')
  119. del r[b'refs/heads/master']
  120. self.assertRaises(KeyError, lambda: r[b'refs/heads/master'])
  121. del r[b'HEAD']
  122. self.assertRaises(KeyError, lambda: r[b'HEAD'])
  123. self.assertRaises(ValueError, r.__delitem__, b'notrefs/foo')
  124. def test_get_refs(self):
  125. r = self.open_repo('a.git')
  126. self.assertEqual({
  127. b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  128. b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  129. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  130. b'refs/tags/mytag-packed': b'b0931cadc54336e78a1d980420e3268903b57a50',
  131. }, r.get_refs())
  132. def test_head(self):
  133. r = self.open_repo('a.git')
  134. self.assertEqual(r.head(), b'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  135. def test_get_object(self):
  136. r = self.open_repo('a.git')
  137. obj = r.get_object(r.head())
  138. self.assertEqual(obj.type_name, b'commit')
  139. def test_get_object_non_existant(self):
  140. r = self.open_repo('a.git')
  141. self.assertRaises(KeyError, r.get_object, missing_sha)
  142. def test_contains_object(self):
  143. r = self.open_repo('a.git')
  144. self.assertTrue(r.head() in r)
  145. def test_contains_ref(self):
  146. r = self.open_repo('a.git')
  147. self.assertTrue(b"HEAD" in r)
  148. def test_get_no_description(self):
  149. r = self.open_repo('a.git')
  150. self.assertIs(None, r.get_description())
  151. def test_get_description(self):
  152. r = self.open_repo('a.git')
  153. with open(os.path.join(r.path, 'description'), 'wb') as f:
  154. f.write(b"Some description")
  155. self.assertEqual(b"Some description", r.get_description())
  156. def test_set_description(self):
  157. r = self.open_repo('a.git')
  158. description = b"Some description"
  159. r.set_description(description)
  160. self.assertEqual(description, r.get_description())
  161. def test_contains_missing(self):
  162. r = self.open_repo('a.git')
  163. self.assertFalse(b"bar" in r)
  164. def test_get_peeled(self):
  165. # unpacked ref
  166. r = self.open_repo('a.git')
  167. tag_sha = b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a'
  168. self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head())
  169. self.assertEqual(r.get_peeled(b'refs/tags/mytag'), r.head())
  170. # packed ref with cached peeled value
  171. packed_tag_sha = b'b0931cadc54336e78a1d980420e3268903b57a50'
  172. parent_sha = r[r.head()].parents[0]
  173. self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha)
  174. self.assertEqual(r.get_peeled(b'refs/tags/mytag-packed'), parent_sha)
  175. # TODO: add more corner cases to test repo
  176. def test_get_peeled_not_tag(self):
  177. r = self.open_repo('a.git')
  178. self.assertEqual(r.get_peeled(b'HEAD'), r.head())
  179. def test_get_walker(self):
  180. r = self.open_repo('a.git')
  181. # include defaults to [r.head()]
  182. self.assertEqual([e.commit.id for e in r.get_walker()],
  183. [r.head(), b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  184. self.assertEqual(
  185. [e.commit.id for e in r.get_walker([b'2a72d929692c41d8554c07f6301757ba18a65d91'])],
  186. [b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  187. self.assertEqual(
  188. [e.commit.id for e in r.get_walker(b'2a72d929692c41d8554c07f6301757ba18a65d91')],
  189. [b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  190. def test_clone(self):
  191. r = self.open_repo('a.git')
  192. tmp_dir = self.mkdtemp()
  193. self.addCleanup(shutil.rmtree, tmp_dir)
  194. with closing(r.clone(tmp_dir, mkdir=False)) as t:
  195. self.assertEqual({
  196. b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  197. b'refs/remotes/origin/master':
  198. b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  199. b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  200. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  201. b'refs/tags/mytag-packed':
  202. b'b0931cadc54336e78a1d980420e3268903b57a50',
  203. }, t.refs.as_dict())
  204. shas = [e.commit.id for e in r.get_walker()]
  205. self.assertEqual(shas, [t.head(),
  206. b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  207. def test_clone_no_head(self):
  208. temp_dir = self.mkdtemp()
  209. self.addCleanup(shutil.rmtree, temp_dir)
  210. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos')
  211. dest_dir = os.path.join(temp_dir, 'a.git')
  212. shutil.copytree(os.path.join(repo_dir, 'a.git'),
  213. dest_dir, symlinks=True)
  214. r = Repo(dest_dir)
  215. del r.refs[b"refs/heads/master"]
  216. del r.refs[b"HEAD"]
  217. t = r.clone(os.path.join(temp_dir, 'b.git'), mkdir=True)
  218. self.assertEqual({
  219. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  220. b'refs/tags/mytag-packed':
  221. b'b0931cadc54336e78a1d980420e3268903b57a50',
  222. }, t.refs.as_dict())
  223. def test_clone_empty(self):
  224. """Test clone() doesn't crash if HEAD points to a non-existing ref.
  225. This simulates cloning server-side bare repository either when it is
  226. still empty or if user renames master branch and pushes private repo
  227. to the server.
  228. Non-bare repo HEAD always points to an existing ref.
  229. """
  230. r = self.open_repo('empty.git')
  231. tmp_dir = self.mkdtemp()
  232. self.addCleanup(shutil.rmtree, tmp_dir)
  233. r.clone(tmp_dir, mkdir=False, bare=True)
  234. def test_merge_history(self):
  235. r = self.open_repo('simple_merge.git')
  236. shas = [e.commit.id for e in r.get_walker()]
  237. self.assertEqual(shas, [b'5dac377bdded4c9aeb8dff595f0faeebcc8498cc',
  238. b'ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  239. b'4cffe90e0a41ad3f5190079d7c8f036bde29cbe6',
  240. b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  241. b'0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  242. def test_out_of_order_merge(self):
  243. """Test that revision history is ordered by date, not parent order."""
  244. r = self.open_repo('ooo_merge.git')
  245. shas = [e.commit.id for e in r.get_walker()]
  246. self.assertEqual(shas, [b'7601d7f6231db6a57f7bbb79ee52e4d462fd44d1',
  247. b'f507291b64138b875c28e03469025b1ea20bc614',
  248. b'fb5b0425c7ce46959bec94d54b9a157645e114f5',
  249. b'f9e39b120c68182a4ba35349f832d0e4e61f485c'])
  250. def test_get_tags_empty(self):
  251. r = self.open_repo('ooo_merge.git')
  252. self.assertEqual({}, r.refs.as_dict(b'refs/tags'))
  253. def test_get_config(self):
  254. r = self.open_repo('ooo_merge.git')
  255. self.assertIsInstance(r.get_config(), Config)
  256. def test_get_config_stack(self):
  257. self.addCleanup(os.environ.__setitem__, "HOME", os.environ["HOME"])
  258. os.environ["HOME"] = "/nonexistant"
  259. r = self.open_repo('ooo_merge.git')
  260. self.assertIsInstance(r.get_config_stack(), Config)
  261. @skipIf(not getattr(os, 'symlink', None), 'Requires symlink support')
  262. def test_submodule(self):
  263. temp_dir = self.mkdtemp()
  264. self.addCleanup(shutil.rmtree, temp_dir)
  265. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos')
  266. shutil.copytree(os.path.join(repo_dir, 'a.git'),
  267. os.path.join(temp_dir, 'a.git'), symlinks=True)
  268. rel = os.path.relpath(os.path.join(repo_dir, 'submodule'), temp_dir)
  269. os.symlink(os.path.join(rel, 'dotgit'), os.path.join(temp_dir, '.git'))
  270. with closing(Repo(temp_dir)) as r:
  271. self.assertEqual(r.head(), b'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  272. def test_common_revisions(self):
  273. """
  274. This test demonstrates that ``find_common_revisions()`` actually returns
  275. common heads, not revisions; dulwich already uses
  276. ``find_common_revisions()`` in such a manner (see
  277. ``Repo.fetch_objects()``).
  278. """
  279. expected_shas = set([b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e'])
  280. # Source for objects.
  281. r_base = self.open_repo('simple_merge.git')
  282. # Re-create each-side of the merge in simple_merge.git.
  283. #
  284. # Since the trees and blobs are missing, the repository created is
  285. # corrupted, but we're only checking for commits for the purpose of this
  286. # test, so it's immaterial.
  287. r1_dir = self.mkdtemp()
  288. self.addCleanup(shutil.rmtree, r1_dir)
  289. r1_commits = [b'ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd', # HEAD
  290. b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  291. b'0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  292. r2_dir = self.mkdtemp()
  293. self.addCleanup(shutil.rmtree, r2_dir)
  294. r2_commits = [b'4cffe90e0a41ad3f5190079d7c8f036bde29cbe6', # HEAD
  295. b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  296. b'0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  297. r1 = Repo.init_bare(r1_dir)
  298. for c in r1_commits:
  299. r1.object_store.add_object(r_base.get_object(c))
  300. r1.refs[b'HEAD'] = r1_commits[0]
  301. r2 = Repo.init_bare(r2_dir)
  302. for c in r2_commits:
  303. r2.object_store.add_object(r_base.get_object(c))
  304. r2.refs[b'HEAD'] = r2_commits[0]
  305. # Finally, the 'real' testing!
  306. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  307. self.assertEqual(set(shas), expected_shas)
  308. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  309. self.assertEqual(set(shas), expected_shas)
  310. def test_shell_hook_pre_commit(self):
  311. if os.name != 'posix':
  312. self.skipTest('shell hook tests requires POSIX shell')
  313. pre_commit_fail = """#!/bin/sh
  314. exit 1
  315. """
  316. pre_commit_success = """#!/bin/sh
  317. exit 0
  318. """
  319. repo_dir = os.path.join(self.mkdtemp())
  320. r = Repo.init(repo_dir)
  321. self.addCleanup(shutil.rmtree, repo_dir)
  322. pre_commit = os.path.join(r.controldir(), 'hooks', 'pre-commit')
  323. with open(pre_commit, 'w') as f:
  324. f.write(pre_commit_fail)
  325. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  326. self.assertRaises(errors.CommitError, r.do_commit, 'failed commit',
  327. committer='Test Committer <test@nodomain.com>',
  328. author='Test Author <test@nodomain.com>',
  329. commit_timestamp=12345, commit_timezone=0,
  330. author_timestamp=12345, author_timezone=0)
  331. with open(pre_commit, 'w') as f:
  332. f.write(pre_commit_success)
  333. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  334. commit_sha = r.do_commit(
  335. b'empty commit',
  336. committer=b'Test Committer <test@nodomain.com>',
  337. author=b'Test Author <test@nodomain.com>',
  338. commit_timestamp=12395, commit_timezone=0,
  339. author_timestamp=12395, author_timezone=0)
  340. self.assertEqual([], r[commit_sha].parents)
  341. def test_shell_hook_commit_msg(self):
  342. if os.name != 'posix':
  343. self.skipTest('shell hook tests requires POSIX shell')
  344. commit_msg_fail = """#!/bin/sh
  345. exit 1
  346. """
  347. commit_msg_success = """#!/bin/sh
  348. exit 0
  349. """
  350. repo_dir = self.mkdtemp()
  351. r = Repo.init(repo_dir)
  352. self.addCleanup(shutil.rmtree, repo_dir)
  353. commit_msg = os.path.join(r.controldir(), 'hooks', 'commit-msg')
  354. with open(commit_msg, 'w') as f:
  355. f.write(commit_msg_fail)
  356. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  357. self.assertRaises(errors.CommitError, r.do_commit, b'failed commit',
  358. committer=b'Test Committer <test@nodomain.com>',
  359. author=b'Test Author <test@nodomain.com>',
  360. commit_timestamp=12345, commit_timezone=0,
  361. author_timestamp=12345, author_timezone=0)
  362. with open(commit_msg, 'w') as f:
  363. f.write(commit_msg_success)
  364. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  365. commit_sha = r.do_commit(
  366. b'empty commit',
  367. committer=b'Test Committer <test@nodomain.com>',
  368. author=b'Test Author <test@nodomain.com>',
  369. commit_timestamp=12395, commit_timezone=0,
  370. author_timestamp=12395, author_timezone=0)
  371. self.assertEqual([], r[commit_sha].parents)
  372. def test_shell_hook_post_commit(self):
  373. if os.name != 'posix':
  374. self.skipTest('shell hook tests requires POSIX shell')
  375. repo_dir = self.mkdtemp()
  376. r = Repo.init(repo_dir)
  377. self.addCleanup(shutil.rmtree, repo_dir)
  378. (fd, path) = tempfile.mkstemp(dir=repo_dir)
  379. os.close(fd)
  380. post_commit_msg = """#!/bin/sh
  381. rm """ + path + """
  382. """
  383. root_sha = r.do_commit(
  384. b'empty commit',
  385. committer=b'Test Committer <test@nodomain.com>',
  386. author=b'Test Author <test@nodomain.com>',
  387. commit_timestamp=12345, commit_timezone=0,
  388. author_timestamp=12345, author_timezone=0)
  389. self.assertEqual([], r[root_sha].parents)
  390. post_commit = os.path.join(r.controldir(), 'hooks', 'post-commit')
  391. with open(post_commit, 'wb') as f:
  392. f.write(post_commit_msg.encode(locale.getpreferredencoding()))
  393. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  394. commit_sha = r.do_commit(
  395. b'empty commit',
  396. committer=b'Test Committer <test@nodomain.com>',
  397. author=b'Test Author <test@nodomain.com>',
  398. commit_timestamp=12345, commit_timezone=0,
  399. author_timestamp=12345, author_timezone=0)
  400. self.assertEqual([root_sha], r[commit_sha].parents)
  401. self.assertFalse(os.path.exists(path))
  402. post_commit_msg_fail = """#!/bin/sh
  403. exit 1
  404. """
  405. with open(post_commit, 'w') as f:
  406. f.write(post_commit_msg_fail)
  407. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  408. warnings.simplefilter("always", UserWarning)
  409. self.addCleanup(warnings.resetwarnings)
  410. warnings_list, restore_warnings = setup_warning_catcher()
  411. self.addCleanup(restore_warnings)
  412. commit_sha2 = r.do_commit(
  413. b'empty commit',
  414. committer=b'Test Committer <test@nodomain.com>',
  415. author=b'Test Author <test@nodomain.com>',
  416. commit_timestamp=12345, commit_timezone=0,
  417. author_timestamp=12345, author_timezone=0)
  418. self.assertEqual(len(warnings_list), 1, warnings_list)
  419. self.assertIsInstance(warnings_list[-1], UserWarning)
  420. self.assertTrue("post-commit hook failed: " in str(warnings_list[-1]))
  421. self.assertEqual([commit_sha], r[commit_sha2].parents)
  422. def test_as_dict(self):
  423. def check(repo):
  424. self.assertEqual(repo.refs.subkeys(b'refs/tags'), repo.refs.subkeys(b'refs/tags/'))
  425. self.assertEqual(repo.refs.as_dict(b'refs/tags'), repo.refs.as_dict(b'refs/tags/'))
  426. self.assertEqual(repo.refs.as_dict(b'refs/heads'), repo.refs.as_dict(b'refs/heads/'))
  427. bare = self.open_repo('a.git')
  428. tmp_dir = self.mkdtemp()
  429. self.addCleanup(shutil.rmtree, tmp_dir)
  430. with closing(bare.clone(tmp_dir, mkdir=False)) as nonbare:
  431. check(nonbare)
  432. check(bare)
  433. class BuildRepoRootTests(TestCase):
  434. """Tests that build on-disk repos from scratch.
  435. Repos live in a temp dir and are torn down after each test. They start with
  436. a single commit in master having single file named 'a'.
  437. """
  438. def get_repo_dir(self):
  439. return os.path.join(tempfile.mkdtemp(), 'test')
  440. def setUp(self):
  441. super(BuildRepoRootTests, self).setUp()
  442. self._repo_dir = self.get_repo_dir()
  443. os.makedirs(self._repo_dir)
  444. r = self._repo = Repo.init(self._repo_dir)
  445. self.addCleanup(tear_down_repo, r)
  446. self.assertFalse(r.bare)
  447. self.assertEqual(b'ref: refs/heads/master', r.refs.read_ref(b'HEAD'))
  448. self.assertRaises(KeyError, lambda: r.refs[b'refs/heads/master'])
  449. with open(os.path.join(r.path, 'a'), 'wb') as f:
  450. f.write(b'file contents')
  451. r.stage(['a'])
  452. commit_sha = r.do_commit(b'msg',
  453. committer=b'Test Committer <test@nodomain.com>',
  454. author=b'Test Author <test@nodomain.com>',
  455. commit_timestamp=12345, commit_timezone=0,
  456. author_timestamp=12345, author_timezone=0)
  457. self.assertEqual([], r[commit_sha].parents)
  458. self._root_commit = commit_sha
  459. def test_build_repo(self):
  460. r = self._repo
  461. self.assertEqual(b'ref: refs/heads/master', r.refs.read_ref(b'HEAD'))
  462. self.assertEqual(self._root_commit, r.refs[b'refs/heads/master'])
  463. expected_blob = objects.Blob.from_string(b'file contents')
  464. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  465. actual_commit = r[self._root_commit]
  466. self.assertEqual(b'msg', actual_commit.message)
  467. def test_commit_modified(self):
  468. r = self._repo
  469. with open(os.path.join(r.path, 'a'), 'wb') as f:
  470. f.write(b'new contents')
  471. r.stage(['a'])
  472. commit_sha = r.do_commit(b'modified a',
  473. committer=b'Test Committer <test@nodomain.com>',
  474. author=b'Test Author <test@nodomain.com>',
  475. commit_timestamp=12395, commit_timezone=0,
  476. author_timestamp=12395, author_timezone=0)
  477. self.assertEqual([self._root_commit], r[commit_sha].parents)
  478. a_mode, a_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b'a')
  479. self.assertEqual(stat.S_IFREG | 0o644, a_mode)
  480. self.assertEqual(b'new contents', r[a_id].data)
  481. @skipIf(not getattr(os, 'symlink', None), 'Requires symlink support')
  482. def test_commit_symlink(self):
  483. r = self._repo
  484. os.symlink('a', os.path.join(r.path, 'b'))
  485. r.stage(['a', 'b'])
  486. commit_sha = r.do_commit(b'Symlink b',
  487. committer=b'Test Committer <test@nodomain.com>',
  488. author=b'Test Author <test@nodomain.com>',
  489. commit_timestamp=12395, commit_timezone=0,
  490. author_timestamp=12395, author_timezone=0)
  491. self.assertEqual([self._root_commit], r[commit_sha].parents)
  492. b_mode, b_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b'b')
  493. self.assertTrue(stat.S_ISLNK(b_mode))
  494. self.assertEqual(b'a', r[b_id].data)
  495. def test_commit_deleted(self):
  496. r = self._repo
  497. os.remove(os.path.join(r.path, 'a'))
  498. r.stage(['a'])
  499. commit_sha = r.do_commit(b'deleted a',
  500. committer=b'Test Committer <test@nodomain.com>',
  501. author=b'Test Author <test@nodomain.com>',
  502. commit_timestamp=12395, commit_timezone=0,
  503. author_timestamp=12395, author_timezone=0)
  504. self.assertEqual([self._root_commit], r[commit_sha].parents)
  505. self.assertEqual([], list(r.open_index()))
  506. tree = r[r[commit_sha].tree]
  507. self.assertEqual([], list(tree.iteritems()))
  508. def test_commit_follows(self):
  509. r = self._repo
  510. r.refs.set_symbolic_ref(b'HEAD', b'refs/heads/bla')
  511. commit_sha = r.do_commit(b'commit with strange character',
  512. committer=b'Test Committer <test@nodomain.com>',
  513. author=b'Test Author <test@nodomain.com>',
  514. commit_timestamp=12395, commit_timezone=0,
  515. author_timestamp=12395, author_timezone=0,
  516. ref=b'HEAD')
  517. self.assertEqual(commit_sha, r[b'refs/heads/bla'].id)
  518. def test_commit_encoding(self):
  519. r = self._repo
  520. commit_sha = r.do_commit(b'commit with strange character \xee',
  521. committer=b'Test Committer <test@nodomain.com>',
  522. author=b'Test Author <test@nodomain.com>',
  523. commit_timestamp=12395, commit_timezone=0,
  524. author_timestamp=12395, author_timezone=0,
  525. encoding=b"iso8859-1")
  526. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  527. def test_commit_config_identity(self):
  528. self.addCleanup(os.environ.__setitem__, "HOME", os.environ["HOME"])
  529. os.environ["HOME"] = "/nonexistant"
  530. # commit falls back to the users' identity if it wasn't specified
  531. r = self._repo
  532. c = r.get_config()
  533. c.set((b"user", ), b"name", b"Jelmer")
  534. c.set((b"user", ), b"email", b"jelmer@apache.org")
  535. c.write_to_path()
  536. commit_sha = r.do_commit(b'message')
  537. self.assertEqual(
  538. b"Jelmer <jelmer@apache.org>",
  539. r[commit_sha].author)
  540. self.assertEqual(
  541. b"Jelmer <jelmer@apache.org>",
  542. r[commit_sha].committer)
  543. def test_commit_config_identity_in_memoryrepo(self):
  544. # commit falls back to the users' identity if it wasn't specified
  545. r = MemoryRepo.init_bare([], {})
  546. c = r.get_config()
  547. c.set((b"user", ), b"name", b"Jelmer")
  548. c.set((b"user", ), b"email", b"jelmer@apache.org")
  549. commit_sha = r.do_commit(b'message', tree=objects.Tree().id)
  550. self.assertEqual(
  551. b"Jelmer <jelmer@apache.org>",
  552. r[commit_sha].author)
  553. self.assertEqual(
  554. b"Jelmer <jelmer@apache.org>",
  555. r[commit_sha].committer)
  556. def test_commit_fail_ref(self):
  557. r = self._repo
  558. def set_if_equals(name, old_ref, new_ref):
  559. return False
  560. r.refs.set_if_equals = set_if_equals
  561. def add_if_new(name, new_ref):
  562. self.fail('Unexpected call to add_if_new')
  563. r.refs.add_if_new = add_if_new
  564. old_shas = set(r.object_store)
  565. self.assertRaises(errors.CommitError, r.do_commit, b'failed commit',
  566. committer=b'Test Committer <test@nodomain.com>',
  567. author=b'Test Author <test@nodomain.com>',
  568. commit_timestamp=12345, commit_timezone=0,
  569. author_timestamp=12345, author_timezone=0)
  570. new_shas = set(r.object_store) - old_shas
  571. self.assertEqual(1, len(new_shas))
  572. # Check that the new commit (now garbage) was added.
  573. new_commit = r[new_shas.pop()]
  574. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  575. self.assertEqual(b'failed commit', new_commit.message)
  576. def test_commit_branch(self):
  577. r = self._repo
  578. commit_sha = r.do_commit(b'commit to branch',
  579. committer=b'Test Committer <test@nodomain.com>',
  580. author=b'Test Author <test@nodomain.com>',
  581. commit_timestamp=12395, commit_timezone=0,
  582. author_timestamp=12395, author_timezone=0,
  583. ref=b"refs/heads/new_branch")
  584. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  585. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  586. self.assertEqual([], r[commit_sha].parents)
  587. self.assertTrue(b"refs/heads/new_branch" in r)
  588. new_branch_head = commit_sha
  589. commit_sha = r.do_commit(b'commit to branch 2',
  590. committer=b'Test Committer <test@nodomain.com>',
  591. author=b'Test Author <test@nodomain.com>',
  592. commit_timestamp=12395, commit_timezone=0,
  593. author_timestamp=12395, author_timezone=0,
  594. ref=b"refs/heads/new_branch")
  595. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  596. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  597. self.assertEqual([new_branch_head], r[commit_sha].parents)
  598. def test_commit_merge_heads(self):
  599. r = self._repo
  600. merge_1 = r.do_commit(b'commit to branch 2',
  601. committer=b'Test Committer <test@nodomain.com>',
  602. author=b'Test Author <test@nodomain.com>',
  603. commit_timestamp=12395, commit_timezone=0,
  604. author_timestamp=12395, author_timezone=0,
  605. ref=b"refs/heads/new_branch")
  606. commit_sha = r.do_commit(b'commit with merge',
  607. committer=b'Test Committer <test@nodomain.com>',
  608. author=b'Test Author <test@nodomain.com>',
  609. commit_timestamp=12395, commit_timezone=0,
  610. author_timestamp=12395, author_timezone=0,
  611. merge_heads=[merge_1])
  612. self.assertEqual(
  613. [self._root_commit, merge_1],
  614. r[commit_sha].parents)
  615. def test_commit_dangling_commit(self):
  616. r = self._repo
  617. old_shas = set(r.object_store)
  618. old_refs = r.get_refs()
  619. commit_sha = r.do_commit(b'commit with no ref',
  620. committer=b'Test Committer <test@nodomain.com>',
  621. author=b'Test Author <test@nodomain.com>',
  622. commit_timestamp=12395, commit_timezone=0,
  623. author_timestamp=12395, author_timezone=0,
  624. ref=None)
  625. new_shas = set(r.object_store) - old_shas
  626. # New sha is added, but no new refs
  627. self.assertEqual(1, len(new_shas))
  628. new_commit = r[new_shas.pop()]
  629. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  630. self.assertEqual([], r[commit_sha].parents)
  631. self.assertEqual(old_refs, r.get_refs())
  632. def test_commit_dangling_commit_with_parents(self):
  633. r = self._repo
  634. old_shas = set(r.object_store)
  635. old_refs = r.get_refs()
  636. commit_sha = r.do_commit(b'commit with no ref',
  637. committer=b'Test Committer <test@nodomain.com>',
  638. author=b'Test Author <test@nodomain.com>',
  639. commit_timestamp=12395, commit_timezone=0,
  640. author_timestamp=12395, author_timezone=0,
  641. ref=None, merge_heads=[self._root_commit])
  642. new_shas = set(r.object_store) - old_shas
  643. # New sha is added, but no new refs
  644. self.assertEqual(1, len(new_shas))
  645. new_commit = r[new_shas.pop()]
  646. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  647. self.assertEqual([self._root_commit], r[commit_sha].parents)
  648. self.assertEqual(old_refs, r.get_refs())
  649. def test_stage_deleted(self):
  650. r = self._repo
  651. os.remove(os.path.join(r.path, 'a'))
  652. r.stage(['a'])
  653. r.stage(['a']) # double-stage a deleted path
  654. def test_commit_no_encode_decode(self):
  655. r = self._repo
  656. repo_path_bytes = r.path.encode(sys.getfilesystemencoding())
  657. encodings = ('utf8', 'latin1')
  658. names = [u'À'.encode(encoding) for encoding in encodings]
  659. for name, encoding in zip(names, encodings):
  660. full_path = os.path.join(repo_path_bytes, name)
  661. with open(full_path, 'wb') as f:
  662. f.write(encoding.encode('ascii'))
  663. # These files are break tear_down_repo, so cleanup these files
  664. # ourselves.
  665. self.addCleanup(os.remove, full_path)
  666. r.stage(names)
  667. commit_sha = r.do_commit(b'Files with different encodings',
  668. committer=b'Test Committer <test@nodomain.com>',
  669. author=b'Test Author <test@nodomain.com>',
  670. commit_timestamp=12395, commit_timezone=0,
  671. author_timestamp=12395, author_timezone=0,
  672. ref=None, merge_heads=[self._root_commit])
  673. for name, encoding in zip(names, encodings):
  674. mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name)
  675. self.assertEqual(stat.S_IFREG | 0o644, mode)
  676. self.assertEqual(encoding.encode('ascii'), r[id].data)
  677. def test_discover_intended(self):
  678. path = os.path.join(self._repo_dir, 'b/c')
  679. r = Repo.discover(path)
  680. self.assertEqual(r.head(), self._repo.head())
  681. def test_discover_isrepo(self):
  682. r = Repo.discover(self._repo_dir)
  683. self.assertEqual(r.head(), self._repo.head())
  684. def test_discover_notrepo(self):
  685. with self.assertRaises(NotGitRepository):
  686. Repo.discover('/')