Last active
January 23, 2024 12:04
-
-
Save alanbchristie/823ea1a25ccb4a2ae70de071e8ba4ee2 to your computer and use it in GitHub Desktop.
Querying a repository with GitPython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Here we assume you've installed the GitPython package | |
# and you're running this code from a repository clone. | |
from typing import Optional | |
from git import Repo | |
from git.refs.tag import TagReference | |
repo: Repo = Repo() | |
print('---') | |
# Does the repo have local modifications? | |
local_mods: bool = repo.is_dirty() | |
if local_mods: | |
print('Repo has local modifications') | |
else: | |
print('Repo does not have local modifications') | |
# Repository commit reference? | |
# The first 7 characters is often all that's needed. | |
commit_ref: str = repo.head.commit.hexsha[:7] | |
print(f'Repo commit reference is "{commit_ref}"') | |
# Are we on a tag? | |
tag: Optional[TagReference] = next((tag for tag in repo.tags if tag.commit == repo.head.commit), None) | |
if tag: | |
print(f'Repo commit tag is "{tag.name}"') | |
else: | |
print('Repo is not on a tag') | |
# And the origin? | |
origin_url: Optional[str] = None | |
for remote in repo.remotes: | |
if remote.name == 'origin': | |
origin_url = remote.config_reader.get("url") | |
if origin_url: | |
print(f'Repo origin URL="{origin_url}"') | |
else: | |
print('Repo has no origin URL') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment