Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed git hash into python file when installing

I want to embed the git hash into the version number of a python module if that module is installed from the git repository using ./setup.py install. How do I do that?

My thought was to define a function in setup.py to insert the hash and arrange to have it called when setup has copied the module to its build/lib/ directory, but before it has installed it to its final destination. Is there any way to hook into the build process at that point?

Edit: I know how to get the hash of the current version from the command line, I am asking about how to get such a command to run at the right time during the build/install.

like image 676
JanKanis Avatar asked Nov 02 '22 18:11

JanKanis


1 Answers

Another, possibly simpler way to do it, using gitpython, as in dd/setup.py:

from pkg_resources import parse_version  # part of `setuptools`


def git_version(version):
    """Return version with local version identifier."""
    import git
    repo = git.Repo('.git')
    repo.git.status()
    # assert versions are increasing
    latest_tag = repo.git.describe(
        match='v[0-9]*', tags=True, abbrev=0)
    assert parse_version(latest_tag) <= parse_version(version), (
        latest_tag, version)
    sha = repo.head.commit.hexsha
    if repo.is_dirty():
        return f'{version}.dev0+{sha}.dirty'
    # commit is clean
    # is it release of `version` ?
    try:
        tag = repo.git.describe(
            match='v[0-9]*', exact_match=True,
            tags=True, dirty=True)
    except git.GitCommandError:
        return f'{version}.dev0+{sha}'
    assert tag == f'v{version}', (tag, version)
    return version

cf also the discussion at https://github.com/tulip-control/tulip-control/pull/145

like image 184
Ioannis Filippidis Avatar answered Nov 15 '22 05:11

Ioannis Filippidis