Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract basic git metadata #6

Merged
merged 1 commit into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")