我使用Python编写工具来获取Mercurial存储库的状态和差异。获取状态很容易,但是当我尝试获取差异时,我收到此错误: AttributeError:'module'对象没有属性'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获得repo的差异吗?
答案 0 :(得分:2)
感谢ngoldbaum的评论,我安装了 python-hglib :
apt-get install python-hglib
然后,我编写这个函数来获取对象中的diff行:
#!/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'
# }
# ]
# }
我希望这段代码会有所帮助!