Skip to content

Instantly share code, notes, and snippets.

@fschwar4
Created December 19, 2023 20:06
Show Gist options
  • Save fschwar4/83144f7d30b86a27d9072ba8286b2b37 to your computer and use it in GitHub Desktop.
Save fschwar4/83144f7d30b86a27d9072ba8286b2b37 to your computer and use it in GitHub Desktop.
add git information for analysis metadata
from typing import Dict, Optional
from pathlib import Path
class MyClass:
@staticmethod
def get_git_infos() -> Dict[str, Optional[str]]:
"""Extract relevant git information for reproducibility.
This function should help to increase reproducibility of the results,
since it is than known which code version was used for the respective
analysis.
The git repository should be in the parent directory of the file.
Returns:
dict: Dictionary with git information including repository url,
branch name, and commit hash.
Notes:
This was foremost relevant before the code was distributed via pip.
Now the version number is sufficient to identify the code version.
The code is kept for now, but might be removed in the future.
"""
dict_infos = {}
try:
import git # not a necessary dependency of the package
repo_dir = Path(__file__).resolve().parent
repo = git.Repo(repo_dir)
dict_infos['git_url'] = repo.remotes.origin.url
dict_infos['git_branch'] = repo.active_branch.name
dict_infos['git_commit_sha'] = repo.head.object.hexsha
except Exception as e:
print(f'Could not extract git information due to the following error: {e}. '
'Either the code is not in a git repository or the gitpython package is not installed.'
)
dict_infos['git_url'] = None
dict_infos['git_branch'] = None
dict_infos['git_commit_sha'] = None
return dict_infos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment