From c46939b5308c31cb792ecb8f7f9b3f76191deb71 Mon Sep 17 00:00:00 2001 From: Rich FitzJohn Date: Fri, 11 Aug 2023 10:11:34 +0100 Subject: [PATCH] Extract basic git metadata --- pyproject.toml | 3 ++- src/outpack/tools.py | 12 ++++++++++ tests/test_tools.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/outpack/tools.py create mode 100644 tests/test_tools.py diff --git a/pyproject.toml b/pyproject.toml index dbbaea7..b053eb0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,8 @@ classifiers = [ "Programming Language :: Python :: Implementation :: PyPy", ] dependencies = [ - "dataclasses-json" + "dataclasses-json", + "pygit2" ] [project.urls] diff --git a/src/outpack/tools.py b/src/outpack/tools.py new file mode 100644 index 0000000..1216fcf --- /dev/null +++ b/src/outpack/tools.py @@ -0,0 +1,12 @@ +import pygit2 + + +def git_info(path): + repo = pygit2.discover_repository(path) + if not repo: + return None + repo = pygit2.Repository(repo) + sha = str(repo.head.target) + branch = repo.head.shorthand + url = [x.url for x in repo.remotes] + return {"sha": sha, "branch": branch, "url": url} diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..3ffdfea --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,57 @@ +import pygit2 + +from outpack.tools import git_info + + +def simple_git_example(path, remote=None): + d = path / "subdir" + d.mkdir() + f = d / "file" + f.write_text("hello") + repo = pygit2.init_repository(path) + repo.index.add_all() + author = pygit2.Signature("Alice Author", "alice@example.com") + message = "Initial commit" + tree = repo.index.write_tree() + result = repo.create_commit("HEAD", author, author, message, tree, []) + if remote: + for name, url in remote: + repo.remotes.create(name, url) + return str(result) + + +def test_git_report_no_info_without_git_repo(tmp_path): + p = tmp_path / "sub" + p.mkdir() + assert git_info(p) is None + + +def test_git_report_git_info_if_possible(tmp_path): + sha = simple_git_example(tmp_path) + res = git_info(tmp_path) + # This default branch name won't be robust to changes in future + # git versions + assert res == {"branch": "master", "sha": sha, "url": []} + + +def test_git_report_single_url(tmp_path): + simple_git_example(tmp_path, [("origin", "https://example.com/git")]) + res = git_info(tmp_path) + assert res["url"] == ["https://example.com/git"] + + +def test_git_report_several_urls(tmp_path): + simple_git_example( + tmp_path, + [ + ("origin", "https://example.com/git"), + ("other", "https://example.com/git2"), + ], + ) + res = git_info(tmp_path) + assert res["url"] == ["https://example.com/git", "https://example.com/git2"] + + +def test_git_report_from_subdir(tmp_path): + simple_git_example(tmp_path) + assert git_info(tmp_path) == git_info(tmp_path / "subdir")