106
def unified_diff_bytes(a, b, fromfile=b'', tofile=b'', fromfiledate=b'',
107
tofiledate=b'', n=3, lineterm=b'\n', sequencematcher=None):
109
Compare two sequences of lines; generate the delta as a unified diff.
111
Unified diffs are a compact way of showing line changes and a few
112
lines of context. The number of context lines is set by 'n' which
115
By default, the diff control lines (those with ---, +++, or @@) are
116
created with a trailing newline. This is helpful so that inputs
117
created from file.readlines() result in diffs that are suitable for
118
file.writelines() since both the inputs and outputs have trailing
121
For inputs that do not have trailing newlines, set the lineterm
122
argument to "" so that the output will be uniformly newline free.
124
The unidiff format normally has a header for filenames and modification
125
times. Any or all of these may be specified using strings for
126
'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification
127
times are normally expressed in the format returned by time.ctime().
131
>>> for line in bytes_unified_diff(b'one two three four'.split(),
132
... b'zero one tree four'.split(), b'Original', b'Current',
133
... b'Sat Jan 26 23:30:50 1991', b'Fri Jun 06 10:20:52 2003',
136
--- Original Sat Jan 26 23:30:50 1991
137
+++ Current Fri Jun 06 10:20:52 2003
146
if sequencematcher is None:
147
sequencematcher = difflib.SequenceMatcher
150
fromfiledate = b'\t' + byes(fromfiledate)
152
tofiledate = b'\t' + bytes(tofiledate)
155
for group in sequencematcher(None, a, b).get_grouped_opcodes(n):
157
yield b'--- %s%s%s' % (fromfile, fromfiledate, lineterm)
158
yield b'+++ %s%s%s' % (tofile, tofiledate, lineterm)
160
i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
161
yield b"@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
162
for tag, i1, i2, j1, j2 in group:
164
for line in a[i1:i2]:
167
if tag == 'replace' or tag == 'delete':
168
for line in a[i1:i2]:
170
if tag == 'replace' or tag == 'insert':
171
for line in b[j1:j2]:
105
175
def unified_diff_files(a, b, sequencematcher=None):
106
176
"""Generate the diff for two files.