如何将mercurial"hg log"输出轻松地格式化为可解析的JSON?

Tw *_*ert 6 mercurial

我想要一个关于如何使用hg loghg过滤器轻松使用的命令行示例,并将其安全地输出到JSON(带有包含文件的数组).

多平台(windows/unix)会很棒.

Mat*_*sdm 12

Mercurial内置了对JSON的支持.您只需使用以下命令即可获得JSON格式的日志输出:

hg log -Tjson
Run Code Online (Sandbox Code Playgroud)

过滤器可以照常使用,要获取文件,可以添加'-v'(详细)参数.

请注意,这是一个相对较新的功能(有关更多详细信息,请参阅wiki),这可能是为什么它还没有明确记录.

使用以下方法也可以获得xml输出:

hg log -Txml
Run Code Online (Sandbox Code Playgroud)


Tw *_*ert 4

编辑:这里的答案适用于任何 hg 版本。对于较新的 hg 版本(3.1+),请参阅另一个性能更高且更简单的答案。

作为示例,这是一个实心单线。

它使用 Mercurials hg log,并将其输出传送到pythononeliner。hg 日志template配置为输出有效的 python 文字。onelinerpython将其转换为 JSON。

hg log --date ">2014-10-01" --no-merges --keyword "mantis@1953" --keyword "mantis@1955" --template "[\"{node|short}\",\"{author|user|urlescape}\",\"{date|rfc3339date}\",\"{desc|urlescape}\", [{files % '\"{file}\",'}]]\n" --user marinus --user develop | python -c "import sys,ast,json,urllib; x=[[z[0], urllib.unquote(z[1]).decode('utf8'), z[2], urllib.unquote(z[3]).decode('utf8'), z[4]] for z in [ast.literal_eval(y) for y in sys.stdin.readlines()]]; print(json.dumps(x,indent=2))"
Run Code Online (Sandbox Code Playgroud)

上面的示例适用于unix,但如果您需要Windows\"兼容性,您可以简单地替换for 。如果您想要未格式化的 JSON,请将“缩进”设置为。""None

python 代码是 2/3 兼容的(任何最新版本),并且不使用任何外部模块。

有关使用的 hg 命令的更多说明,请参阅:

hg help log
hg help dates
hg help templates
Run Code Online (Sandbox Code Playgroud)

python代码使用nested list comprehensions,谷歌搜索以获取更多信息。