test_repository.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. 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. InvalidUserIdentity,
  38. Repo,
  39. MemoryRepo,
  40. check_user_identity,
  41. )
  42. from dulwich.tests import (
  43. TestCase,
  44. skipIf,
  45. )
  46. from dulwich.tests.utils import (
  47. open_repo,
  48. tear_down_repo,
  49. setup_warning_catcher,
  50. )
  51. missing_sha = b'b91fa4d900e17e99b433218e988c4eb4a3e9a097'
  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(
  63. b'Unnamed repository', repo, 'description')
  64. self.assertFileContentsEqual(
  65. b'', repo, os.path.join('info', 'exclude'))
  66. self.assertFileContentsEqual(None, repo, 'nonexistent file')
  67. barestr = b'bare = ' + str(expect_bare).lower().encode('ascii')
  68. with repo.get_named_file('config') as f:
  69. config_text = f.read()
  70. self.assertTrue(barestr in config_text, "%r" % config_text)
  71. expect_filemode = sys.platform != 'win32'
  72. barestr = b'filemode = ' + str(expect_filemode).lower().encode('ascii')
  73. with repo.get_named_file('config') as f:
  74. config_text = f.read()
  75. self.assertTrue(barestr in config_text, "%r" % config_text)
  76. def test_create_memory(self):
  77. repo = MemoryRepo.init_bare([], {})
  78. self._check_repo_contents(repo, True)
  79. def test_create_disk_bare(self):
  80. tmp_dir = tempfile.mkdtemp()
  81. self.addCleanup(shutil.rmtree, tmp_dir)
  82. repo = Repo.init_bare(tmp_dir)
  83. self.assertEqual(tmp_dir, repo._controldir)
  84. self._check_repo_contents(repo, True)
  85. def test_create_disk_non_bare(self):
  86. tmp_dir = tempfile.mkdtemp()
  87. self.addCleanup(shutil.rmtree, tmp_dir)
  88. repo = Repo.init(tmp_dir)
  89. self.assertEqual(os.path.join(tmp_dir, '.git'), repo._controldir)
  90. self._check_repo_contents(repo, False)
  91. def test_create_disk_non_bare_mkdir(self):
  92. tmp_dir = tempfile.mkdtemp()
  93. target_dir = os.path.join(tmp_dir, "target")
  94. self.addCleanup(shutil.rmtree, tmp_dir)
  95. repo = Repo.init(target_dir, mkdir=True)
  96. self.assertEqual(os.path.join(target_dir, '.git'), repo._controldir)
  97. self._check_repo_contents(repo, False)
  98. def test_create_disk_bare_mkdir(self):
  99. tmp_dir = tempfile.mkdtemp()
  100. target_dir = os.path.join(tmp_dir, "target")
  101. self.addCleanup(shutil.rmtree, tmp_dir)
  102. repo = Repo.init_bare(target_dir, mkdir=True)
  103. self.assertEqual(target_dir, repo._controldir)
  104. self._check_repo_contents(repo, True)
  105. class MemoryRepoTests(TestCase):
  106. def test_set_description(self):
  107. r = MemoryRepo.init_bare([], {})
  108. description = b"Some description"
  109. r.set_description(description)
  110. self.assertEqual(description, r.get_description())
  111. class RepositoryRootTests(TestCase):
  112. def mkdtemp(self):
  113. return tempfile.mkdtemp()
  114. def open_repo(self, name):
  115. temp_dir = self.mkdtemp()
  116. repo = open_repo(name, temp_dir)
  117. self.addCleanup(tear_down_repo, repo)
  118. return repo
  119. def test_simple_props(self):
  120. r = self.open_repo('a.git')
  121. self.assertEqual(r.controldir(), r.path)
  122. def test_setitem(self):
  123. r = self.open_repo('a.git')
  124. r[b"refs/tags/foo"] = b'a90fa2d900a17e99b433217e988c4eb4a2e9a097'
  125. self.assertEqual(b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  126. r[b"refs/tags/foo"].id)
  127. def test_getitem_unicode(self):
  128. r = self.open_repo('a.git')
  129. test_keys = [
  130. (b'refs/heads/master', True),
  131. (b'a90fa2d900a17e99b433217e988c4eb4a2e9a097', True),
  132. (b'11' * 19 + b'--', False),
  133. ]
  134. for k, contained in test_keys:
  135. self.assertEqual(k in r, contained)
  136. # Avoid deprecation warning under Py3.2+
  137. if getattr(self, 'assertRaisesRegex', None):
  138. assertRaisesRegexp = self.assertRaisesRegex
  139. else:
  140. assertRaisesRegexp = self.assertRaisesRegexp
  141. for k, _ in test_keys:
  142. assertRaisesRegexp(
  143. TypeError, "'name' must be bytestring, not int",
  144. r.__getitem__, 12
  145. )
  146. def test_delitem(self):
  147. r = self.open_repo('a.git')
  148. del r[b'refs/heads/master']
  149. self.assertRaises(KeyError, lambda: r[b'refs/heads/master'])
  150. del r[b'HEAD']
  151. self.assertRaises(KeyError, lambda: r[b'HEAD'])
  152. self.assertRaises(ValueError, r.__delitem__, b'notrefs/foo')
  153. def test_get_refs(self):
  154. r = self.open_repo('a.git')
  155. self.assertEqual({
  156. b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  157. b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  158. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  159. b'refs/tags/mytag-packed':
  160. b'b0931cadc54336e78a1d980420e3268903b57a50',
  161. }, r.get_refs())
  162. def test_head(self):
  163. r = self.open_repo('a.git')
  164. self.assertEqual(r.head(), b'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  165. def test_get_object(self):
  166. r = self.open_repo('a.git')
  167. obj = r.get_object(r.head())
  168. self.assertEqual(obj.type_name, b'commit')
  169. def test_get_object_non_existant(self):
  170. r = self.open_repo('a.git')
  171. self.assertRaises(KeyError, r.get_object, missing_sha)
  172. def test_contains_object(self):
  173. r = self.open_repo('a.git')
  174. self.assertTrue(r.head() in r)
  175. def test_contains_ref(self):
  176. r = self.open_repo('a.git')
  177. self.assertTrue(b"HEAD" in r)
  178. def test_get_no_description(self):
  179. r = self.open_repo('a.git')
  180. self.assertIs(None, r.get_description())
  181. def test_get_description(self):
  182. r = self.open_repo('a.git')
  183. with open(os.path.join(r.path, 'description'), 'wb') as f:
  184. f.write(b"Some description")
  185. self.assertEqual(b"Some description", r.get_description())
  186. def test_set_description(self):
  187. r = self.open_repo('a.git')
  188. description = b"Some description"
  189. r.set_description(description)
  190. self.assertEqual(description, r.get_description())
  191. def test_contains_missing(self):
  192. r = self.open_repo('a.git')
  193. self.assertFalse(b"bar" in r)
  194. def test_get_peeled(self):
  195. # unpacked ref
  196. r = self.open_repo('a.git')
  197. tag_sha = b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a'
  198. self.assertNotEqual(r[tag_sha].sha().hexdigest(), r.head())
  199. self.assertEqual(r.get_peeled(b'refs/tags/mytag'), r.head())
  200. # packed ref with cached peeled value
  201. packed_tag_sha = b'b0931cadc54336e78a1d980420e3268903b57a50'
  202. parent_sha = r[r.head()].parents[0]
  203. self.assertNotEqual(r[packed_tag_sha].sha().hexdigest(), parent_sha)
  204. self.assertEqual(r.get_peeled(b'refs/tags/mytag-packed'), parent_sha)
  205. # TODO: add more corner cases to test repo
  206. def test_get_peeled_not_tag(self):
  207. r = self.open_repo('a.git')
  208. self.assertEqual(r.get_peeled(b'HEAD'), r.head())
  209. def test_get_walker(self):
  210. r = self.open_repo('a.git')
  211. # include defaults to [r.head()]
  212. self.assertEqual(
  213. [e.commit.id for e in r.get_walker()],
  214. [r.head(), b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  215. self.assertEqual(
  216. [e.commit.id for e in
  217. r.get_walker([b'2a72d929692c41d8554c07f6301757ba18a65d91'])],
  218. [b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  219. self.assertEqual(
  220. [e.commit.id for e in
  221. r.get_walker(b'2a72d929692c41d8554c07f6301757ba18a65d91')],
  222. [b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  223. def test_clone(self):
  224. r = self.open_repo('a.git')
  225. tmp_dir = self.mkdtemp()
  226. self.addCleanup(shutil.rmtree, tmp_dir)
  227. with r.clone(tmp_dir, mkdir=False) as t:
  228. self.assertEqual({
  229. b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  230. b'refs/remotes/origin/master':
  231. b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  232. b'refs/heads/master':
  233. b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  234. b'refs/tags/mytag':
  235. b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  236. b'refs/tags/mytag-packed':
  237. b'b0931cadc54336e78a1d980420e3268903b57a50',
  238. }, t.refs.as_dict())
  239. shas = [e.commit.id for e in r.get_walker()]
  240. self.assertEqual(shas, [t.head(),
  241. b'2a72d929692c41d8554c07f6301757ba18a65d91'])
  242. c = t.get_config()
  243. encoded_path = r.path
  244. if not isinstance(encoded_path, bytes):
  245. encoded_path = encoded_path.encode(sys.getfilesystemencoding())
  246. self.assertEqual(encoded_path,
  247. c.get((b'remote', b'origin'), b'url'))
  248. self.assertEqual(
  249. b'+refs/heads/*:refs/remotes/origin/*',
  250. c.get((b'remote', b'origin'), b'fetch'))
  251. def test_clone_no_head(self):
  252. temp_dir = self.mkdtemp()
  253. self.addCleanup(shutil.rmtree, temp_dir)
  254. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos')
  255. dest_dir = os.path.join(temp_dir, 'a.git')
  256. shutil.copytree(os.path.join(repo_dir, 'a.git'),
  257. dest_dir, symlinks=True)
  258. r = Repo(dest_dir)
  259. del r.refs[b"refs/heads/master"]
  260. del r.refs[b"HEAD"]
  261. t = r.clone(os.path.join(temp_dir, 'b.git'), mkdir=True)
  262. self.assertEqual({
  263. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  264. b'refs/tags/mytag-packed':
  265. b'b0931cadc54336e78a1d980420e3268903b57a50',
  266. }, t.refs.as_dict())
  267. def test_clone_empty(self):
  268. """Test clone() doesn't crash if HEAD points to a non-existing ref.
  269. This simulates cloning server-side bare repository either when it is
  270. still empty or if user renames master branch and pushes private repo
  271. to the server.
  272. Non-bare repo HEAD always points to an existing ref.
  273. """
  274. r = self.open_repo('empty.git')
  275. tmp_dir = self.mkdtemp()
  276. self.addCleanup(shutil.rmtree, tmp_dir)
  277. r.clone(tmp_dir, mkdir=False, bare=True)
  278. def test_clone_bare(self):
  279. r = self.open_repo('a.git')
  280. tmp_dir = self.mkdtemp()
  281. self.addCleanup(shutil.rmtree, tmp_dir)
  282. t = r.clone(tmp_dir, mkdir=False)
  283. t.close()
  284. def test_clone_checkout_and_bare(self):
  285. r = self.open_repo('a.git')
  286. tmp_dir = self.mkdtemp()
  287. self.addCleanup(shutil.rmtree, tmp_dir)
  288. self.assertRaises(ValueError, r.clone, tmp_dir, mkdir=False,
  289. checkout=True, bare=True)
  290. def test_merge_history(self):
  291. r = self.open_repo('simple_merge.git')
  292. shas = [e.commit.id for e in r.get_walker()]
  293. self.assertEqual(shas, [b'5dac377bdded4c9aeb8dff595f0faeebcc8498cc',
  294. b'ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd',
  295. b'4cffe90e0a41ad3f5190079d7c8f036bde29cbe6',
  296. b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  297. b'0d89f20333fbb1d2f3a94da77f4981373d8f4310'])
  298. def test_out_of_order_merge(self):
  299. """Test that revision history is ordered by date, not parent order."""
  300. r = self.open_repo('ooo_merge.git')
  301. shas = [e.commit.id for e in r.get_walker()]
  302. self.assertEqual(shas, [b'7601d7f6231db6a57f7bbb79ee52e4d462fd44d1',
  303. b'f507291b64138b875c28e03469025b1ea20bc614',
  304. b'fb5b0425c7ce46959bec94d54b9a157645e114f5',
  305. b'f9e39b120c68182a4ba35349f832d0e4e61f485c'])
  306. def test_get_tags_empty(self):
  307. r = self.open_repo('ooo_merge.git')
  308. self.assertEqual({}, r.refs.as_dict(b'refs/tags'))
  309. def test_get_config(self):
  310. r = self.open_repo('ooo_merge.git')
  311. self.assertIsInstance(r.get_config(), Config)
  312. def test_get_config_stack(self):
  313. r = self.open_repo('ooo_merge.git')
  314. self.assertIsInstance(r.get_config_stack(), Config)
  315. @skipIf(not getattr(os, 'symlink', None), 'Requires symlink support')
  316. def test_submodule(self):
  317. temp_dir = self.mkdtemp()
  318. self.addCleanup(shutil.rmtree, temp_dir)
  319. repo_dir = os.path.join(os.path.dirname(__file__), 'data', 'repos')
  320. shutil.copytree(os.path.join(repo_dir, 'a.git'),
  321. os.path.join(temp_dir, 'a.git'), symlinks=True)
  322. rel = os.path.relpath(os.path.join(repo_dir, 'submodule'), temp_dir)
  323. os.symlink(os.path.join(rel, 'dotgit'), os.path.join(temp_dir, '.git'))
  324. with Repo(temp_dir) as r:
  325. self.assertEqual(r.head(),
  326. b'a90fa2d900a17e99b433217e988c4eb4a2e9a097')
  327. def test_common_revisions(self):
  328. """
  329. This test demonstrates that ``find_common_revisions()`` actually
  330. returns common heads, not revisions; dulwich already uses
  331. ``find_common_revisions()`` in such a manner (see
  332. ``Repo.fetch_objects()``).
  333. """
  334. expected_shas = set([b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e'])
  335. # Source for objects.
  336. r_base = self.open_repo('simple_merge.git')
  337. # Re-create each-side of the merge in simple_merge.git.
  338. #
  339. # Since the trees and blobs are missing, the repository created is
  340. # corrupted, but we're only checking for commits for the purpose of
  341. # this test, so it's immaterial.
  342. r1_dir = self.mkdtemp()
  343. self.addCleanup(shutil.rmtree, r1_dir)
  344. r1_commits = [b'ab64bbdcc51b170d21588e5c5d391ee5c0c96dfd', # HEAD
  345. b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  346. b'0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  347. r2_dir = self.mkdtemp()
  348. self.addCleanup(shutil.rmtree, r2_dir)
  349. r2_commits = [b'4cffe90e0a41ad3f5190079d7c8f036bde29cbe6', # HEAD
  350. b'60dacdc733de308bb77bb76ce0fb0f9b44c9769e',
  351. b'0d89f20333fbb1d2f3a94da77f4981373d8f4310']
  352. r1 = Repo.init_bare(r1_dir)
  353. for c in r1_commits:
  354. r1.object_store.add_object(r_base.get_object(c))
  355. r1.refs[b'HEAD'] = r1_commits[0]
  356. r2 = Repo.init_bare(r2_dir)
  357. for c in r2_commits:
  358. r2.object_store.add_object(r_base.get_object(c))
  359. r2.refs[b'HEAD'] = r2_commits[0]
  360. # Finally, the 'real' testing!
  361. shas = r2.object_store.find_common_revisions(r1.get_graph_walker())
  362. self.assertEqual(set(shas), expected_shas)
  363. shas = r1.object_store.find_common_revisions(r2.get_graph_walker())
  364. self.assertEqual(set(shas), expected_shas)
  365. def test_shell_hook_pre_commit(self):
  366. if os.name != 'posix':
  367. self.skipTest('shell hook tests requires POSIX shell')
  368. pre_commit_fail = """#!/bin/sh
  369. exit 1
  370. """
  371. pre_commit_success = """#!/bin/sh
  372. exit 0
  373. """
  374. repo_dir = os.path.join(self.mkdtemp())
  375. self.addCleanup(shutil.rmtree, repo_dir)
  376. r = Repo.init(repo_dir)
  377. self.addCleanup(r.close)
  378. pre_commit = os.path.join(r.controldir(), 'hooks', 'pre-commit')
  379. with open(pre_commit, 'w') as f:
  380. f.write(pre_commit_fail)
  381. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  382. self.assertRaises(errors.CommitError, r.do_commit, 'failed commit',
  383. committer='Test Committer <test@nodomain.com>',
  384. author='Test Author <test@nodomain.com>',
  385. commit_timestamp=12345, commit_timezone=0,
  386. author_timestamp=12345, author_timezone=0)
  387. with open(pre_commit, 'w') as f:
  388. f.write(pre_commit_success)
  389. os.chmod(pre_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  390. commit_sha = r.do_commit(
  391. b'empty commit',
  392. committer=b'Test Committer <test@nodomain.com>',
  393. author=b'Test Author <test@nodomain.com>',
  394. commit_timestamp=12395, commit_timezone=0,
  395. author_timestamp=12395, author_timezone=0)
  396. self.assertEqual([], r[commit_sha].parents)
  397. def test_shell_hook_commit_msg(self):
  398. if os.name != 'posix':
  399. self.skipTest('shell hook tests requires POSIX shell')
  400. commit_msg_fail = """#!/bin/sh
  401. exit 1
  402. """
  403. commit_msg_success = """#!/bin/sh
  404. exit 0
  405. """
  406. repo_dir = self.mkdtemp()
  407. self.addCleanup(shutil.rmtree, repo_dir)
  408. r = Repo.init(repo_dir)
  409. self.addCleanup(r.close)
  410. commit_msg = os.path.join(r.controldir(), 'hooks', 'commit-msg')
  411. with open(commit_msg, 'w') as f:
  412. f.write(commit_msg_fail)
  413. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  414. self.assertRaises(errors.CommitError, r.do_commit, b'failed commit',
  415. committer=b'Test Committer <test@nodomain.com>',
  416. author=b'Test Author <test@nodomain.com>',
  417. commit_timestamp=12345, commit_timezone=0,
  418. author_timestamp=12345, author_timezone=0)
  419. with open(commit_msg, 'w') as f:
  420. f.write(commit_msg_success)
  421. os.chmod(commit_msg, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  422. commit_sha = r.do_commit(
  423. b'empty commit',
  424. committer=b'Test Committer <test@nodomain.com>',
  425. author=b'Test Author <test@nodomain.com>',
  426. commit_timestamp=12395, commit_timezone=0,
  427. author_timestamp=12395, author_timezone=0)
  428. self.assertEqual([], r[commit_sha].parents)
  429. def test_shell_hook_post_commit(self):
  430. if os.name != 'posix':
  431. self.skipTest('shell hook tests requires POSIX shell')
  432. repo_dir = self.mkdtemp()
  433. self.addCleanup(shutil.rmtree, repo_dir)
  434. r = Repo.init(repo_dir)
  435. self.addCleanup(r.close)
  436. (fd, path) = tempfile.mkstemp(dir=repo_dir)
  437. os.close(fd)
  438. post_commit_msg = """#!/bin/sh
  439. rm """ + path + """
  440. """
  441. root_sha = r.do_commit(
  442. b'empty commit',
  443. committer=b'Test Committer <test@nodomain.com>',
  444. author=b'Test Author <test@nodomain.com>',
  445. commit_timestamp=12345, commit_timezone=0,
  446. author_timestamp=12345, author_timezone=0)
  447. self.assertEqual([], r[root_sha].parents)
  448. post_commit = os.path.join(r.controldir(), 'hooks', 'post-commit')
  449. with open(post_commit, 'wb') as f:
  450. f.write(post_commit_msg.encode(locale.getpreferredencoding()))
  451. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  452. commit_sha = r.do_commit(
  453. b'empty commit',
  454. committer=b'Test Committer <test@nodomain.com>',
  455. author=b'Test Author <test@nodomain.com>',
  456. commit_timestamp=12345, commit_timezone=0,
  457. author_timestamp=12345, author_timezone=0)
  458. self.assertEqual([root_sha], r[commit_sha].parents)
  459. self.assertFalse(os.path.exists(path))
  460. post_commit_msg_fail = """#!/bin/sh
  461. exit 1
  462. """
  463. with open(post_commit, 'w') as f:
  464. f.write(post_commit_msg_fail)
  465. os.chmod(post_commit, stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
  466. warnings.simplefilter("always", UserWarning)
  467. self.addCleanup(warnings.resetwarnings)
  468. warnings_list, restore_warnings = setup_warning_catcher()
  469. self.addCleanup(restore_warnings)
  470. commit_sha2 = r.do_commit(
  471. b'empty commit',
  472. committer=b'Test Committer <test@nodomain.com>',
  473. author=b'Test Author <test@nodomain.com>',
  474. commit_timestamp=12345, commit_timezone=0,
  475. author_timestamp=12345, author_timezone=0)
  476. expected_warning = UserWarning(
  477. 'post-commit hook failed: Hook post-commit exited with '
  478. 'non-zero status',)
  479. for w in warnings_list:
  480. if (type(w) == type(expected_warning) and
  481. w.args == expected_warning.args):
  482. break
  483. else:
  484. raise AssertionError(
  485. 'Expected warning %r not in %r' %
  486. (expected_warning, warnings_list))
  487. self.assertEqual([commit_sha], r[commit_sha2].parents)
  488. def test_as_dict(self):
  489. def check(repo):
  490. self.assertEqual(
  491. repo.refs.subkeys(b'refs/tags'),
  492. repo.refs.subkeys(b'refs/tags/'))
  493. self.assertEqual(
  494. repo.refs.as_dict(b'refs/tags'),
  495. repo.refs.as_dict(b'refs/tags/'))
  496. self.assertEqual(
  497. repo.refs.as_dict(b'refs/heads'),
  498. repo.refs.as_dict(b'refs/heads/'))
  499. bare = self.open_repo('a.git')
  500. tmp_dir = self.mkdtemp()
  501. self.addCleanup(shutil.rmtree, tmp_dir)
  502. with bare.clone(tmp_dir, mkdir=False) as nonbare:
  503. check(nonbare)
  504. check(bare)
  505. def test_working_tree(self):
  506. temp_dir = tempfile.mkdtemp()
  507. self.addCleanup(shutil.rmtree, temp_dir)
  508. worktree_temp_dir = tempfile.mkdtemp()
  509. self.addCleanup(shutil.rmtree, worktree_temp_dir)
  510. r = Repo.init(temp_dir)
  511. self.addCleanup(r.close)
  512. root_sha = r.do_commit(
  513. b'empty commit',
  514. committer=b'Test Committer <test@nodomain.com>',
  515. author=b'Test Author <test@nodomain.com>',
  516. commit_timestamp=12345, commit_timezone=0,
  517. author_timestamp=12345, author_timezone=0)
  518. r.refs[b'refs/heads/master'] = root_sha
  519. w = Repo._init_new_working_directory(worktree_temp_dir, r)
  520. self.addCleanup(w.close)
  521. new_sha = w.do_commit(
  522. b'new commit',
  523. committer=b'Test Committer <test@nodomain.com>',
  524. author=b'Test Author <test@nodomain.com>',
  525. commit_timestamp=12345, commit_timezone=0,
  526. author_timestamp=12345, author_timezone=0)
  527. w.refs[b'HEAD'] = new_sha
  528. self.assertEqual(os.path.abspath(r.controldir()),
  529. os.path.abspath(w.commondir()))
  530. self.assertEqual(r.refs.keys(), w.refs.keys())
  531. self.assertNotEqual(r.head(), w.head())
  532. class BuildRepoRootTests(TestCase):
  533. """Tests that build on-disk repos from scratch.
  534. Repos live in a temp dir and are torn down after each test. They start with
  535. a single commit in master having single file named 'a'.
  536. """
  537. def get_repo_dir(self):
  538. return os.path.join(tempfile.mkdtemp(), 'test')
  539. def setUp(self):
  540. super(BuildRepoRootTests, self).setUp()
  541. self._repo_dir = self.get_repo_dir()
  542. os.makedirs(self._repo_dir)
  543. r = self._repo = Repo.init(self._repo_dir)
  544. self.addCleanup(tear_down_repo, r)
  545. self.assertFalse(r.bare)
  546. self.assertEqual(b'ref: refs/heads/master', r.refs.read_ref(b'HEAD'))
  547. self.assertRaises(KeyError, lambda: r.refs[b'refs/heads/master'])
  548. with open(os.path.join(r.path, 'a'), 'wb') as f:
  549. f.write(b'file contents')
  550. r.stage(['a'])
  551. commit_sha = r.do_commit(
  552. b'msg',
  553. committer=b'Test Committer <test@nodomain.com>',
  554. author=b'Test Author <test@nodomain.com>',
  555. commit_timestamp=12345, commit_timezone=0,
  556. author_timestamp=12345, author_timezone=0)
  557. self.assertEqual([], r[commit_sha].parents)
  558. self._root_commit = commit_sha
  559. def test_shallow(self):
  560. self.assertEqual(set(), self._repo.get_shallow())
  561. with open(os.path.join(self._repo.path, '.git', 'shallow'), 'wb') as f:
  562. f.write(b'a90fa2d900a17e99b433217e988c4eb4a2e9a097\n')
  563. self.assertEqual({b'a90fa2d900a17e99b433217e988c4eb4a2e9a097'},
  564. self._repo.get_shallow())
  565. def test_build_repo(self):
  566. r = self._repo
  567. self.assertEqual(b'ref: refs/heads/master', r.refs.read_ref(b'HEAD'))
  568. self.assertEqual(self._root_commit, r.refs[b'refs/heads/master'])
  569. expected_blob = objects.Blob.from_string(b'file contents')
  570. self.assertEqual(expected_blob.data, r[expected_blob.id].data)
  571. actual_commit = r[self._root_commit]
  572. self.assertEqual(b'msg', actual_commit.message)
  573. def test_commit_modified(self):
  574. r = self._repo
  575. with open(os.path.join(r.path, 'a'), 'wb') as f:
  576. f.write(b'new contents')
  577. r.stage(['a'])
  578. commit_sha = r.do_commit(
  579. b'modified a',
  580. committer=b'Test Committer <test@nodomain.com>',
  581. author=b'Test Author <test@nodomain.com>',
  582. commit_timestamp=12395, commit_timezone=0,
  583. author_timestamp=12395, author_timezone=0)
  584. self.assertEqual([self._root_commit], r[commit_sha].parents)
  585. a_mode, a_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b'a')
  586. self.assertEqual(stat.S_IFREG | 0o644, a_mode)
  587. self.assertEqual(b'new contents', r[a_id].data)
  588. @skipIf(not getattr(os, 'symlink', None), 'Requires symlink support')
  589. def test_commit_symlink(self):
  590. r = self._repo
  591. os.symlink('a', os.path.join(r.path, 'b'))
  592. r.stage(['a', 'b'])
  593. commit_sha = r.do_commit(
  594. b'Symlink b',
  595. committer=b'Test Committer <test@nodomain.com>',
  596. author=b'Test Author <test@nodomain.com>',
  597. commit_timestamp=12395, commit_timezone=0,
  598. author_timestamp=12395, author_timezone=0)
  599. self.assertEqual([self._root_commit], r[commit_sha].parents)
  600. b_mode, b_id = tree_lookup_path(r.get_object, r[commit_sha].tree, b'b')
  601. self.assertTrue(stat.S_ISLNK(b_mode))
  602. self.assertEqual(b'a', r[b_id].data)
  603. def test_commit_deleted(self):
  604. r = self._repo
  605. os.remove(os.path.join(r.path, 'a'))
  606. r.stage(['a'])
  607. commit_sha = r.do_commit(
  608. b'deleted a',
  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. self.assertEqual([self._root_commit], r[commit_sha].parents)
  614. self.assertEqual([], list(r.open_index()))
  615. tree = r[r[commit_sha].tree]
  616. self.assertEqual([], list(tree.iteritems()))
  617. def test_commit_follows(self):
  618. r = self._repo
  619. r.refs.set_symbolic_ref(b'HEAD', b'refs/heads/bla')
  620. commit_sha = r.do_commit(
  621. b'commit with strange character',
  622. committer=b'Test Committer <test@nodomain.com>',
  623. author=b'Test Author <test@nodomain.com>',
  624. commit_timestamp=12395, commit_timezone=0,
  625. author_timestamp=12395, author_timezone=0,
  626. ref=b'HEAD')
  627. self.assertEqual(commit_sha, r[b'refs/heads/bla'].id)
  628. def test_commit_encoding(self):
  629. r = self._repo
  630. commit_sha = r.do_commit(
  631. b'commit with strange character \xee',
  632. committer=b'Test Committer <test@nodomain.com>',
  633. author=b'Test Author <test@nodomain.com>',
  634. commit_timestamp=12395, commit_timezone=0,
  635. author_timestamp=12395, author_timezone=0,
  636. encoding=b"iso8859-1")
  637. self.assertEqual(b"iso8859-1", r[commit_sha].encoding)
  638. def test_commit_config_identity(self):
  639. # commit falls back to the users' identity if it wasn't specified
  640. r = self._repo
  641. c = r.get_config()
  642. c.set((b"user", ), b"name", b"Jelmer")
  643. c.set((b"user", ), b"email", b"jelmer@apache.org")
  644. c.write_to_path()
  645. commit_sha = r.do_commit(b'message')
  646. self.assertEqual(
  647. b"Jelmer <jelmer@apache.org>",
  648. r[commit_sha].author)
  649. self.assertEqual(
  650. b"Jelmer <jelmer@apache.org>",
  651. r[commit_sha].committer)
  652. def test_commit_config_identity_in_memoryrepo(self):
  653. # commit falls back to the users' identity if it wasn't specified
  654. r = MemoryRepo.init_bare([], {})
  655. c = r.get_config()
  656. c.set((b"user", ), b"name", b"Jelmer")
  657. c.set((b"user", ), b"email", b"jelmer@apache.org")
  658. commit_sha = r.do_commit(b'message', tree=objects.Tree().id)
  659. self.assertEqual(
  660. b"Jelmer <jelmer@apache.org>",
  661. r[commit_sha].author)
  662. self.assertEqual(
  663. b"Jelmer <jelmer@apache.org>",
  664. r[commit_sha].committer)
  665. def test_commit_fail_ref(self):
  666. r = self._repo
  667. def set_if_equals(name, old_ref, new_ref, **kwargs):
  668. return False
  669. r.refs.set_if_equals = set_if_equals
  670. def add_if_new(name, new_ref, **kwargs):
  671. self.fail('Unexpected call to add_if_new')
  672. r.refs.add_if_new = add_if_new
  673. old_shas = set(r.object_store)
  674. self.assertRaises(errors.CommitError, r.do_commit, b'failed commit',
  675. committer=b'Test Committer <test@nodomain.com>',
  676. author=b'Test Author <test@nodomain.com>',
  677. commit_timestamp=12345, commit_timezone=0,
  678. author_timestamp=12345, author_timezone=0)
  679. new_shas = set(r.object_store) - old_shas
  680. self.assertEqual(1, len(new_shas))
  681. # Check that the new commit (now garbage) was added.
  682. new_commit = r[new_shas.pop()]
  683. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  684. self.assertEqual(b'failed commit', new_commit.message)
  685. def test_commit_branch(self):
  686. r = self._repo
  687. commit_sha = r.do_commit(
  688. b'commit to branch',
  689. committer=b'Test Committer <test@nodomain.com>',
  690. author=b'Test Author <test@nodomain.com>',
  691. commit_timestamp=12395, commit_timezone=0,
  692. author_timestamp=12395, author_timezone=0,
  693. ref=b"refs/heads/new_branch")
  694. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  695. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  696. self.assertEqual([], r[commit_sha].parents)
  697. self.assertTrue(b"refs/heads/new_branch" in r)
  698. new_branch_head = commit_sha
  699. commit_sha = r.do_commit(
  700. b'commit to branch 2',
  701. committer=b'Test Committer <test@nodomain.com>',
  702. author=b'Test Author <test@nodomain.com>',
  703. commit_timestamp=12395, commit_timezone=0,
  704. author_timestamp=12395, author_timezone=0,
  705. ref=b"refs/heads/new_branch")
  706. self.assertEqual(self._root_commit, r[b"HEAD"].id)
  707. self.assertEqual(commit_sha, r[b"refs/heads/new_branch"].id)
  708. self.assertEqual([new_branch_head], r[commit_sha].parents)
  709. def test_commit_merge_heads(self):
  710. r = self._repo
  711. merge_1 = r.do_commit(
  712. b'commit to branch 2',
  713. committer=b'Test Committer <test@nodomain.com>',
  714. author=b'Test Author <test@nodomain.com>',
  715. commit_timestamp=12395, commit_timezone=0,
  716. author_timestamp=12395, author_timezone=0,
  717. ref=b"refs/heads/new_branch")
  718. commit_sha = r.do_commit(
  719. b'commit with merge',
  720. committer=b'Test Committer <test@nodomain.com>',
  721. author=b'Test Author <test@nodomain.com>',
  722. commit_timestamp=12395, commit_timezone=0,
  723. author_timestamp=12395, author_timezone=0,
  724. merge_heads=[merge_1])
  725. self.assertEqual(
  726. [self._root_commit, merge_1],
  727. r[commit_sha].parents)
  728. def test_commit_dangling_commit(self):
  729. r = self._repo
  730. old_shas = set(r.object_store)
  731. old_refs = r.get_refs()
  732. commit_sha = r.do_commit(
  733. b'commit with no ref',
  734. committer=b'Test Committer <test@nodomain.com>',
  735. author=b'Test Author <test@nodomain.com>',
  736. commit_timestamp=12395, commit_timezone=0,
  737. author_timestamp=12395, author_timezone=0,
  738. ref=None)
  739. new_shas = set(r.object_store) - old_shas
  740. # New sha is added, but no new refs
  741. self.assertEqual(1, len(new_shas))
  742. new_commit = r[new_shas.pop()]
  743. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  744. self.assertEqual([], r[commit_sha].parents)
  745. self.assertEqual(old_refs, r.get_refs())
  746. def test_commit_dangling_commit_with_parents(self):
  747. r = self._repo
  748. old_shas = set(r.object_store)
  749. old_refs = r.get_refs()
  750. commit_sha = r.do_commit(
  751. b'commit with no ref',
  752. committer=b'Test Committer <test@nodomain.com>',
  753. author=b'Test Author <test@nodomain.com>',
  754. commit_timestamp=12395, commit_timezone=0,
  755. author_timestamp=12395, author_timezone=0,
  756. ref=None, merge_heads=[self._root_commit])
  757. new_shas = set(r.object_store) - old_shas
  758. # New sha is added, but no new refs
  759. self.assertEqual(1, len(new_shas))
  760. new_commit = r[new_shas.pop()]
  761. self.assertEqual(r[self._root_commit].tree, new_commit.tree)
  762. self.assertEqual([self._root_commit], r[commit_sha].parents)
  763. self.assertEqual(old_refs, r.get_refs())
  764. def test_stage_absolute(self):
  765. r = self._repo
  766. os.remove(os.path.join(r.path, 'a'))
  767. self.assertRaises(ValueError, r.stage, [os.path.join(r.path, 'a')])
  768. def test_stage_deleted(self):
  769. r = self._repo
  770. os.remove(os.path.join(r.path, 'a'))
  771. r.stage(['a'])
  772. r.stage(['a']) # double-stage a deleted path
  773. def test_stage_directory(self):
  774. r = self._repo
  775. os.mkdir(os.path.join(r.path, 'c'))
  776. r.stage(['c'])
  777. self.assertEqual([b'a'], list(r.open_index()))
  778. @skipIf(sys.platform == 'win32' and sys.version_info[:2] >= (3, 6),
  779. 'tries to implicitly decode as utf8')
  780. def test_commit_no_encode_decode(self):
  781. r = self._repo
  782. repo_path_bytes = r.path.encode(sys.getfilesystemencoding())
  783. encodings = ('utf8', 'latin1')
  784. names = [u'À'.encode(encoding) for encoding in encodings]
  785. for name, encoding in zip(names, encodings):
  786. full_path = os.path.join(repo_path_bytes, name)
  787. with open(full_path, 'wb') as f:
  788. f.write(encoding.encode('ascii'))
  789. # These files are break tear_down_repo, so cleanup these files
  790. # ourselves.
  791. self.addCleanup(os.remove, full_path)
  792. r.stage(names)
  793. commit_sha = r.do_commit(
  794. b'Files with different encodings',
  795. committer=b'Test Committer <test@nodomain.com>',
  796. author=b'Test Author <test@nodomain.com>',
  797. commit_timestamp=12395, commit_timezone=0,
  798. author_timestamp=12395, author_timezone=0,
  799. ref=None, merge_heads=[self._root_commit])
  800. for name, encoding in zip(names, encodings):
  801. mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name)
  802. self.assertEqual(stat.S_IFREG | 0o644, mode)
  803. self.assertEqual(encoding.encode('ascii'), r[id].data)
  804. def test_discover_intended(self):
  805. path = os.path.join(self._repo_dir, 'b/c')
  806. r = Repo.discover(path)
  807. self.assertEqual(r.head(), self._repo.head())
  808. def test_discover_isrepo(self):
  809. r = Repo.discover(self._repo_dir)
  810. self.assertEqual(r.head(), self._repo.head())
  811. def test_discover_notrepo(self):
  812. with self.assertRaises(NotGitRepository):
  813. Repo.discover('/')
  814. class CheckUserIdentityTests(TestCase):
  815. def test_valid(self):
  816. check_user_identity(b'Me <me@example.com>')
  817. def test_invalid(self):
  818. self.assertRaises(InvalidUserIdentity,
  819. check_user_identity, b'No Email')
  820. self.assertRaises(InvalidUserIdentity,
  821. check_user_identity, b'Fullname <missing')
  822. self.assertRaises(InvalidUserIdentity,
  823. check_user_identity, b'Fullname missing>')
  824. self.assertRaises(InvalidUserIdentity,
  825. check_user_identity, b'Fullname >order<>')