From 2de751b775281d5577ec92a349a4c917ca2bc53e Mon Sep 17 00:00:00 2001 From: Jan David Mol <mol@astron.nl> Date: Tue, 18 May 2021 15:45:26 +0200 Subject: [PATCH] L2SS-176: Provide sane default where to look for a repo --- devices/util/lofar_git.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 devices/util/lofar_git.py diff --git a/devices/util/lofar_git.py b/devices/util/lofar_git.py new file mode 100644 index 000000000..7ba42cb01 --- /dev/null +++ b/devices/util/lofar_git.py @@ -0,0 +1,39 @@ +import git # pip3 install gitpython +import os + +def get_repo(starting_directory: str = os.path.dirname(__file__)) -> git.Repo: + """ Try finding the repository by traversing up the tree. + + By default, the repository containing this module is returned. + """ + + directory = starting_directory + + try: + return git.Repo(directory) + except git.InvalidGitRepositoryError: + pass + + # We now have to traverse up the tree + while directory != "/" and os.path.exists(directory): + # Go to parent + directory = os.path.abspath(directory + os.path.sep + "..") + + try: + return git.Repo(directory) + except git.InvalidGitRepositoryError: + pass + + raise git.InvalidGitRepositoryError("Could not find git repository root in {}".format(starting_directory)) + + +def get_version(repo: git.Repo = None) -> str: + """ Return a version string for the current commit. """ + + if repo is None: + repo = get_repo() + + return "{} [{}{}]".format(repo.active_branch, repo.commit(), " (dirty)" if repo.is_dirty() else "") + +if __name__ == "__main__": + print(get_version()) -- GitLab