如何在 setuptools 包中包含 VCS 信息

How to include VCS information in setuptools packages

我正在(尝试)使用 setuptools 构建一个包。我试图使用版本号 major.minor.mercurial_revision 但它抱怨说:

The version specified ('1.0.7ae7970a82c1') is an invalid version, this may
not work as expected with newer versions of setuptools, pip, and PyPI.
Please see PEP 440 for more details.`

很好。所以我看一下 PEP 440,它基本上说 "don't do that":

As hashes cannot be ordered reliably such versions are not permitted in the
public version field. As with semantic versioning, the public  .devN  
suffix may be used to uniquely identify such releases for publication, 
while the original DVCS based label can be stored in the project metadata. 

我理解这里的逻辑。但是如何 我可以在项目元数据中包含 hg 修订版?我找不到关于 setup.py:setup() 的参数可以包含什么的任何(最新)文档,但是我发现 here 的 distutils 似乎没有为此提供一个字段。

将其作为属性包含在您的 Python 代码中怎么样?

echo '__revision__ = $HG_HASH' > mypackage/revision.py

安装后,您可以:

from mypackage.revision import __revision__
print 'build from', __revision__

或者您可以将其写入文件,并通过 MANIFEST.in.

将其包含在您的源代码分发中

您甚至可以将它直接包含在 setup() 的参数中,这似乎只是忽略了未知的关键字参数:

setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
      revision='7ae7970a82c1',
     )

这不会在任何地方记录,但如果有人需要了解它以获取调试信息或其他内容,则始终可以通过检查获得它。因为这依赖于 setup() 忽略未知参数——我不确定这是明确记录的行为——我不知道这个想法实际上是我推荐的。

您可以使用 local version identifier 来完成此操作。

Local version identifiers MUST comply with the following scheme:

<public version identifier>[+<local version label>]

在您的情况下,这将是 <major>.<minor>+<mercurial_version>,这将导致 1.0+7ae7970a82c1