"""
@package pmsco.database.git
git metadata

this module retrieves the git hash of the running code for job metadata.
this requires that the code is run from a git repository
and that the gitpython package is installed.
gitpython is loaded on demand.
common errors (missing gitpython or invalid repository) are handled.

@author Matthias Muntwiler, matthias.muntwiler@psi.ch

@copyright (c) 2015-21 by Paul Scherrer Institut @n
Licensed under the Apache License, Version 2.0 (the "License"); @n
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
"""

import importlib


def git():
    """
    import the git module from GitPython

    @return: git module or None if an error occurred
    """
    try:
        return importlib.import_module('git')
    except ImportError:
        return None


def get_git_hash(repo_path=None):
    """
    get the git commit (hash) of the running code (HEAD)

    the method looks for a git repository in the source tree of this module.
    if successful, it returns the hash string of the HEAD commit.

    @return: hexadecimal hash string.
        empty string if the file is not in a git repository.
    """
    if repo_path is None:
        repo_path = __file__

    _git = git()
    if _git is not None:
        try:
            repo = _git.Repo(repo_path, search_parent_directories=True)
        except _git.exc.InvalidGitRepositoryError:
            return ""
        else:
            return repo.head.commit.hexsha
    else:
        return ""
