将 Mercurial 的修订号包含到 python 文件模板 pycharm

include revision number from mercurial into python file template pycharm

我有一个 python 文件模板,定义如下 pycharm 2016.3

__author__ = ${USER}
__date__ = ${DATE}
__copyright__ = ""
__credits__ = [""]
__license__ = ""
__revision__ = ""
__maintainer__ = ${USER}
__status__ = "Development"

对于修订号,我想使用命令 "hg id -n" 的输出,它给出了从 mercurial 中提取的当前修订号。

最好的方法是什么?

产生一个子进程并调用 hg 以收集输出。我使用类似 this 的东西。本质上有点缩短(我希望我没有因为缩短基础知识而引入错误,虽然它是 py3):

def get_child_output(cmd):
    """
    Run a child process, and collect the generated output.

    @param cmd: Command to execute.
    @type  cmd: C{list} of C{str}

    @return: Generated output of the command, split on whitespace.
    @rtype:  C{list} of C{str}
    """
    return subprocess.check_output(cmd, universal_newlines = True).split()


def get_hg_version():
    path =     os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    version = ''
    version_list = get_child_output(['hg', '-R', path, 'id', '-n', '-i'])

    hash = version_list[0].rstrip('+')

    # Get the date of the commit of the current NML version in days since January 1st 2000
    ctimes = get_child_output(["hg", "-R", path, "parent", "--template='{date|hgdate} {date|shortdate}\n'"])
    ctime = (int((ctimes[0].split("'"))[1]) - 946684800) // (60 * 60 * 24)
    cversion = str(ctime)

    # Combine the version string
    version = "v{}:{} from {}".format(cversion, hash, ctimes[2].split("'", 1)[0])
    return version

# Save the revision in the proper variable
__revision__ = get_hg_version()

最后:考虑不要(仅)使用 hg id -n 的输出作为您的版本号:它是一个仅对回购的特定实例本地的值,并且在不同的版本之间可能会有很大差异同一个仓库的克隆。使用哈希 and/or 提交时间作为版本(以及)。