test_repository.py 32 KB

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