← Back to team overview

dulwich-users team mailing list archive

[PATCH 09/34] objects: Add lookup_path method to Tree.

 

From: Dave Borowitz <dborowitz@xxxxxxxxxx>

The proximate reason for this change is to avoid a circular import in
diff_tree.

Change-Id: I5516556739b08b1ebfbef9caab03cd43457ec28c
---
 NEWS                    |    2 ++
 dulwich/object_store.py |   18 ++++++------------
 dulwich/objects.py      |   20 ++++++++++++++++++++
 3 files changed, 28 insertions(+), 12 deletions(-)

diff --git a/NEWS b/NEWS
index 838b717..7dba793 100644
--- a/NEWS
+++ b/NEWS
@@ -69,6 +69,8 @@
     value of unpack_object and various DeltaChainIterator methods.
     (Dave Borowitz)
 
+  * Add a lookup_path convenience method to Tree. (Dave Borowitz)
+
  TEST CHANGES
 
   * If setuptools is installed, "python setup.py test" will now run the testsuite.
diff --git a/dulwich/object_store.py b/dulwich/object_store.py
index 2ed160f..b772f6d 100644
--- a/dulwich/object_store.py
+++ b/dulwich/object_store.py
@@ -685,23 +685,17 @@ class ObjectStoreIterator(ObjectIterator):
 
 
 def tree_lookup_path(lookup_obj, root_sha, path):
-    """Lookup an object in a Git tree.
+    """Look up an object in a Git tree.
 
     :param lookup_obj: Callback for retrieving object by SHA1
     :param root_sha: SHA1 of the root tree
     :param path: Path to lookup
+    :return: A tuple of (mode, SHA) of the resulting path.
     """
-    parts = path.split("/")
-    sha = root_sha
-    mode = None
-    for p in parts:
-        obj = lookup_obj(sha)
-        if not isinstance(obj, Tree):
-            raise NotTreeError(sha)
-        if p == '':
-            continue
-        mode, sha = obj[p]
-    return mode, sha
+    tree = lookup_obj(root_sha)
+    if not isinstance(tree, Tree):
+        raise NotTreeError(root_sha)
+    return tree.lookup_path(lookup_obj, path)
 
 
 class MissingObjectFinder(object):
diff --git a/dulwich/objects.py b/dulwich/objects.py
index a3c3d25..51ee24d 100644
--- a/dulwich/objects.py
+++ b/dulwich/objects.py
@@ -919,6 +919,26 @@ class Tree(ShaFile):
             text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
         return "".join(text)
 
+    def lookup_path(self, lookup_obj, path):
+        """Look up an object in a Git tree.
+
+        :param lookup_obj: Callback for retrieving object by SHA1
+        :param root_sha: SHA1 of the root tree
+        :param path: Path to lookup
+        :return: A tuple of (mode, SHA) of the resulting path.
+        """
+        parts = path.split('/')
+        sha = self.id
+        mode = None
+        for p in parts:
+            if not p:
+                continue
+            obj = lookup_obj(sha)
+            if not isinstance(obj, Tree):
+                raise NotTreeError(sha)
+            mode, sha = obj[p]
+        return mode, sha
+
 
 def parse_timezone(text):
     """Parse a timezone text fragment (e.g. '+0100').
-- 
1.7.3.1



Follow ups

References