Skip to content

Instantly share code, notes, and snippets.

@xLaszlo
Created December 19, 2022 19:03
Show Gist options
  • Save xLaszlo/8ebaf62dcee32f76ddc8a45e0be37394 to your computer and use it in GitHub Desktop.
Save xLaszlo/8ebaf62dcee32f76ddc8a45e0be37394 to your computer and use it in GitHub Desktop.
How to get information about a git repository in python
# !pip install GitPython
from git import Repo
from git.exc import NoSuchPathError
from git.exc import InvalidGitRepositoryError
class RepoData:
def __init__(self, repo_directory):
self.repo_directory = repo_directory
self.repo_exists = False
try:
repo = Repo(path=self.repo_directory)
self.repo_exists = True
except NoSuchPathError:
print(f'Directory {self.repo_directory} does not exist')
return
except InvalidGitRepositoryError:
print(f'No git repository in {self.repo_directory}')
return
self.is_dirty = repo.is_dirty()
try:
commit = repo.commit()
except ValueError as ex:
print('No commits in this repo; please create an initial commit.')
raise ex
self.commit_hash = commit.hexsha
self.commit_message = commit.message
self.comitter_name = commit.committer.name
self.comitter_email = commit.committer.email
try:
self.branch_name = repo.active_branch.name
except TypeError:
self.branch_name = 'DETACHED'
repo_data = RepoData(repo_directory='.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment