Python Mercurial 如何用 hg 库获取差异



我使用Python编写一个工具来获取Mercurial存储库的状态和差异。很容易获得状态,但是当我尝试获取差异时,我收到此错误:属性错误:"模块"对象没有属性"configbool"。这是我的代码和输出:

法典

#!/usr/bin/python
# coding:utf-8
import os
import sys
from mercurial import ui, hg, commands
from mercurial.i18n import gettext as _
path = '~/path_of/repo'
u = ui.ui()
repo = hg.repository(u, path)
status = repo.status()
print("===== status =====")
print(status)
diff = commands.diff(ui, repo)
print("===== diff =====")
print(diff)

输出

===== status =====
(['app/file/file_modified.py'], [], [], [], [], [], [])
Traceback (most recent call last):
File "test.py", line 19, in <module>
diff = commands.diff(ui, repo)
File "/usr/lib/python2.7/dist-packages/mercurial/commands.py", line 2940, in diff
diffopts = patch.diffopts(ui, opts)
File "/usr/lib/python2.7/dist-packages/mercurial/patch.py", line 1557, in diffopts
def get(key, name=None, getter=ui.configbool):
AttributeError: 'module' object has no attribute 'configbool'
zsh: exit 1     python test.py

你有办法用 Python 获取存储库的差异吗?

感谢ngoldbaum的评论,我安装了python-hglib

apt-get install python-hglib

然后,我对此函数进行编码以获取对象中的差异行:

#!/usr/bin/python
# coding:utf-8
import re
import hglib

def get_diff(path, include_empty_lines=False):
client = hglib.open(path) # get client of repo
diff = client.diff() # get plain text diff
added_lines = []
removed_lines = []
current_file = ''
for line in diff.split("n")[1:]:
if line.startswith('+++'):
current_file = re.split('s',line)[1][2:]
continue
if not line.startswith('+++') and not line.startswith('---'):
if line.startswith('+'):
if include_empty_lines or line[1:]:
added_lines.append({
"file": current_file,
"line_content": line[1:]
})
if line.startswith('-'):
if include_empty_lines or line[1:]:
removed_lines.append({
"file": current_file,
"line_content": line[1:]
})
return {"added_lines":added_lines, "removed_lines":removed_lines}

diff = get_diff('/path/to/repo')
print(diff)
# gives
# {
#   'added_lines': 
#       [
#           {
#               'line_content': 'import re', 
#               'file': 'bestfile.py'
#           }, 
#           {
#               'line_content': '        re.split("s", name)', 
#               'file': 'parsing_file.py'
#           }
#       ], 
#   'removed_lines': 
#       [
#           {
#               'line_content': '        name.split(" ")',
#               'file': 'parsing_file.py'
#           }
#       ]
#  }

我希望这段代码会有所帮助!

最新更新