使用python的Mercurial脚本

2024-05-14 05:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用python编程获取mercurial修订号/id(它是一个散列而不是一个数字)。

原因是我想将其添加到我们网站上的css/js文件中,如下所示:

<link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" />

因此,每当对样式表进行更改时,它将获得一个新的url,而不再使用旧的缓存版本。

如果您知道在哪里可以找到mercurialpython模块的好文档,这也会很有帮助。我好像哪儿也找不到。

我的解决方案

最后我使用subprocess运行一个命令来获取hg节点。我选择这个解决方案是因为api不能保证保持不变,但是bash接口可能会:

import subprocess

def get_hg_rev(file_path):
    pipe = subprocess.Popen(
        ["hg", "log", "-l", "1", "--template", "{node}", file_path],
        stdout=subprocess.PIPE
        )
    return pipe.stdout.read()

示例使用:

> path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css"
> get_hg_rev(path_to_file)
'0ed525cf38a7b7f4f1321763d964a39327db97c4'

Tags: topathgetexamplestdoutrev解决方案hg
3条回答

更新的、更干净的子流程版本(使用在Python 2.7/3.1中添加的.check_output()),我在Django设置文件中使用该版本进行粗略的端到端部署检查(将其转储到HTML注释中):

import subprocess

HG_REV = subprocess.check_output(['hg', 'id', '--id']).strip()

如果你不想让一些奇怪的小插曲阻止启动,你可以用try来包装它:

try:
    HG_REV = subprocess.check_output(['hg', 'id', '--id']).strip()
except OSError:
    HG_REV = "? (Couldn't find hg)"
except subprocess.CalledProcessError as e:
    HG_REV = "? (Error {})".format(e.returncode)
except Exception:  # don't use bare 'except', mis-catches Ctrl-C and more
    # should never have to deal with a hangup 
    HG_REV = "???"

你是说this documentation
注意,如该页所述,没有官方API,因为他们仍然保留随时更改的权利。但是你可以在最后几个版本中看到变更列表,它不是很广泛。

确实没有正式的API,但是您可以通过阅读其他扩展,特别是与hg捆绑在一起的扩展,了解最佳实践。对于这个特殊的问题,我会这样做:

from mercurial import ui, hg
from mercurial.node import hex

repo = hg.repository('/path/to/repo/root', ui.ui())
fctx = repo.filectx('/path/to/file', 'tip')
hexnode = hex(fctx.node())

更新在某个时刻,参数顺序发生了更改,现在如下所示:

   repo = hg.repository(ui.ui(), '/path/to/repo/root' )

相关问题 更多 >