Automatic version number both in setup.py (setuptools) AND source code?

前端 未结 7 1370
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 11:21

SITUATION:

I have a python library, which is controlled by git, and bundled with distutils/setuptools. And I want to automatically generate version

7条回答
  •  鱼传尺愫
    2020-12-24 11:40

    Following OGHaza's solution in a similar SO question I keep a file _version.py that I parse in setup.py. With the version string from there, I git tag in setup.py. Then I set the setup version variable to a combination of version string plus the git commit hash. So here is the relevant part of setup.py:

    from setuptools import setup, find_packages
    from codecs import open
    from os import path
    import subprocess
    
    here = path.abspath(path.dirname(__file__))
    
    import re, os
    VERSIONFILE=os.path.join(here,"_version.py")
    verstrline = open(VERSIONFILE, "rt").read()
    VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
    mo = re.search(VSRE, verstrline, re.M)
    if mo:
        verstr = mo.group(1)
    else:
        raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
    if os.path.exists(os.path.join(here, '.git')):
        cmd = 'git rev-parse --verify --short HEAD'
        git_hash = subprocess.check_output(cmd)
        # tag git
        gitverstr = 'v' + verstr
        tags =  subprocess.check_output('git tag')
        if not gitverstr in tags:
            cmd = 'git tag -a %s %s -m "tagged by setup.py to %s"' % (gitverstr, git_hash, verstr)        
            subprocess.check_output(cmd)
        # use the git hash in the setup
        verstr += ', git hash: %s' % git_hash
    
    setup(
        name='a_package',
        version = verstr,
        ....
    

提交回复
热议问题