Selaa lähdekoodia

Add `discover` classmethod

bmcorser 9 vuotta sitten
vanhempi
commit
295c8c0d9e
2 muutettua tiedostoa jossa 23 lisäystä ja 0 poistoa
  1. 18 0
      dulwich/repo.py
  2. 5 0
      dulwich/tests/test_repository.py

+ 18 - 0
dulwich/repo.py

@@ -678,6 +678,24 @@ class Repo(BaseRepo):
         self.hooks['commit-msg'] = CommitMsgShellHook(self.controldir())
         self.hooks['post-commit'] = PostCommitShellHook(self.controldir())
 
+    @classmethod
+    def discover(cls, start):
+        """
+        Return a Repo object for the first parent directory that looks like a
+        Git repository.
+
+        :param start: The directory to start discovery from
+        """
+        abs_split = os.path.abspath(start)[1:].split(os.path.sep)
+        for _ in range(len(abs_split)):
+            try:
+                return cls(os.path.join('/', *abs_split))
+            except NotGitRepository:
+                abs_split.pop()
+        raise NotGitRepository(
+            "No git repository was found at %(path)s" % dict(path=start)
+        )
+
     def controldir(self):
         """Return the path of the control directory."""
         return self._controldir

+ 5 - 0
dulwich/tests/test_repository.py

@@ -765,3 +765,8 @@ class BuildRepoRootTests(TestCase):
             mode, id = tree_lookup_path(r.get_object, r[commit_sha].tree, name)
             self.assertEqual(stat.S_IFREG | 0o644, mode)
             self.assertEqual(encoding.encode('ascii'), r[id].data)
+
+    def test_discover(self):
+        path = os.path.join(self._repo_dir, 'b/c')
+        r = Repo.discover(path)
+        self.assertEqual(r.head(), self._repo.head())