test_repository.py 30 KB

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