Skip to content

Commit

Permalink
Extract basic git metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
richfitz committed Aug 11, 2023
1 parent fe20476 commit c46939b
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ classifiers = [
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = [
"dataclasses-json"
"dataclasses-json",
"pygit2"
]

[project.urls]
Expand Down
12 changes: 12 additions & 0 deletions src/outpack/tools.py
Original file line number Diff line number Diff line change
@@ -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}
57 changes: 57 additions & 0 deletions tests/test_tools.py
Original file line number Diff line number Diff line change
@@ -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")

0 comments on commit c46939b

Please sign in to comment.