Python 统一的差异比较工具,包含来自“文件”的行号

3
我正在尝试找到一种方法,创建带有行号的统一差异,并且只显示N行上下文。我无法使用difflib.unified_diff来实现这一点。我需要显示两个文件中的更改内容。最接近的解决方案是在命令行上使用diff,如下所示: /usr/bin/diff --unchanged-line-format=' %.2dn %L' --old-line-format="-%.2dn %L" --new-line-format="+%.2dn %L" file1.py file2.py 但是,我只想显示N行上下文,并且/usr/bin/diff似乎不支持自定义行格式的上下文(例如,-U2与--line-format“conflicting output style options”不兼容)。下面是我想要完成的示例(与上面的差异输出相同,但仅显示围绕更改的1行上下文):
1个回答

0

我成功地找到了非常接近我想要的东西。不过它比普通的差异算法慢。以下是整个代码,来自我的项目GitGate

def unified_diff(to_file_path, from_file_path, context=1):

    """ Returns a list of differences between two files based
    on some context. This is probably over-complicated. """

    pat_diff = re.compile(r'@@ (.[0-9]+\,[0-9]+) (.[0-9]+,[0-9]+) @@')

    from_lines = []
    if os.path.exists(from_file_path):
        from_fh = open(from_file_path,'r')
        from_lines = from_fh.readlines()
        from_fh.close()

    to_lines = []
    if os.path.exists(to_file_path):
        to_fh = open(to_file_path,'r')
        to_lines = to_fh.readlines()
        to_fh.close()

    diff_lines = []

    lines = difflib.unified_diff(to_lines, from_lines, n=context)
    for line in lines:
        if line.startswith('--') or line.startswith('++'):
            continue

        m = pat_diff.match(line)
        if m:
            left = m.group(1)
            right = m.group(2)
            lstart = left.split(',')[0][1:]
            rstart = right.split(',')[0][1:]
            diff_lines.append("@@ %s %s @@\n"%(left, right))
            to_lnum = int(lstart)
            from_lnum = int(rstart)
            continue

        code = line[0]

        lnum = from_lnum
        if code == '-':
            lnum = to_lnum
        diff_lines.append("%s%.4d: %s"%(code, lnum, line[1:]))

        if code == '-':
            to_lnum += 1
        elif code == '+':
            from_lnum += 1
        else:
            to_lnum += 1
            from_lnum += 1

    return diff_lines

我们如何通过管道传输git diff的不同之处,而不是读取不同的文件,无论是“HEAD^ HEAD”还是不同的头位置? - Ciasto piekarz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接