Skip to content

Commit

Permalink
Add get_object_by_path.
Browse files Browse the repository at this point in the history
  • Loading branch information
jelmer committed Oct 20, 2018
1 parent 50b7a8d commit 4438e15
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
* Handle commit identity fields with multiple ">" characters.
(Nicolas Dandrimont)

IMPROVEMENTS

* ``dulwich.porcelain.get_object_by_path`` method for easily
accessing a path in another tree. (Jelmer Vernooij)

0.19.6 2018-08-11

BUG FIXES
Expand Down
20 changes: 20 additions & 0 deletions dulwich/porcelain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1385,3 +1385,23 @@ def describe(repo):

# Return plain commit if no parent tag can be found
return 'g{}'.format(latest_commit.id.decode('ascii')[:7])


def get_object_by_path(repo, path, committish=None):
"""Get an object by path.
:param repo: A path to the repository
:param path: Path to look up
:param committish: Commit to look up path in
:return: A `ShaFile` object
"""
if committish is None:
committish = "HEAD"
# Get the repository
with open_repo_closing(repo) as r:
commit = parse_commit(repo, committish)
base_tree = commit.tree
(mode, sha) = tree_lookup_path(
r.object_store.__getitem__,
base_tree, path)
return r[sha]
21 changes: 21 additions & 0 deletions dulwich/tests/test_porcelain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1541,3 +1541,24 @@ def test_path_to_tree_path_rel(self):
os.path.join(os.getcwd(), '..'), 'baz'))
finally:
os.chdir(cwd)


class GetObjectBypathTests(PorcelainTestCase):

def test_simple(self):
fullpath = os.path.join(self.repo.path, 'foo')
with open(fullpath, 'w') as f:
f.write("BAR")
porcelain.add(repo=self.repo.path, paths=[fullpath])
porcelain.commit(
self.repo.path, message=b"Some message",
author=b"Joe <joe@example.com>",
committer=b"Bob <bob@example.com>")
self.assertEqual(
b"BAR",
porcelain.get_object_by_path(self.repo, 'foo').data)

def test_missing(self):
self.assertRaises(
KeyError,
porcelain.get_object_by_path, self.repo, 'foo')

0 comments on commit 4438e15

Please sign in to comment.