如何使用 unidiff 解析器解析 git diff -U 输出

How to parse git diff -U output using unidiff parser

我需要带有上下文的大块头(添加和删除的行)所以我使用 git diff -u 来获得差异。我可以做 line.is_added 以获得 lines_added 但这些行将不包含上下文行。我如何解析此差异以获取 lines_added 删除的行 以及一些上下文行。现在我有

  Line 1
  ......
  Line 5 
- Line 6 
+ Line 7
  ......
  Line n

本质上我想要

lines_deleted = context lines, Line 6, more context lines and 
lines_added = context lines , Line 7, more context lines
lines_added = []
for hunk in patched_file:
         for line in hunk:
             if line.is_added or line .is_context and line.value.strip() != '':
                 lines_added.append(line.value)

lines_deleted 也是如此。这应该 return:

  Line 1
  ......
  Line 5  
+ Line 7
  ......
  Line n

假设第 7 行以外的所有行都是上下文行。