| 1 |
|
| 2 |
|
| 3 |
"""icdiff.py |
| 4 |
|
| 5 |
Author: Jeff Kaufman, derived from difflib.HtmlDiff |
| 6 |
|
| 7 |
License: This code is usable under the same open terms as the rest of |
| 8 |
python. See: http://www.python.org/psf/license/ |
| 9 |
|
| 10 |
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation; |
| 11 |
All Rights Reserved |
| 12 |
|
| 13 |
Based on Python's difflib.HtmlDiff, |
| 14 |
with changes to provide console output instead of html output.""" |
| 15 |
|
| 16 |
import os |
| 17 |
import stat |
| 18 |
import sys |
| 19 |
import errno |
| 20 |
import difflib |
| 21 |
from optparse import Option, OptionParser |
| 22 |
import re |
| 23 |
import filecmp |
| 24 |
import unicodedata |
| 25 |
import fnmatch |
| 26 |
|
| 27 |
__version__ = "2.0.10" |
| 28 |
|
| 29 |
|
| 30 |
EXIT_CODE_SUCCESS = 0 |
| 31 |
EXIT_CODE_DIFF = 1 |
| 32 |
EXIT_CODE_ERROR = 2 |
| 33 |
|
| 34 |
color_codes = { |
| 35 |
"black": "\033[0;30m", |
| 36 |
"red": "\033[0;31m", |
| 37 |
"green": "\033[0;32m", |
| 38 |
"yellow": "\033[0;33m", |
| 39 |
"blue": "\033[0;34m", |
| 40 |
"magenta": "\033[0;35m", |
| 41 |
"cyan": "\033[0;36m", |
| 42 |
"white": "\033[0;37m", |
| 43 |
"none": "\033[m", |
| 44 |
"black_bold": "\033[1;30m", |
| 45 |
"red_bold": "\033[1;31m", |
| 46 |
"green_bold": "\033[1;32m", |
| 47 |
"yellow_bold": "\033[1;33m", |
| 48 |
"blue_bold": "\033[1;34m", |
| 49 |
"magenta_bold": "\033[1;35m", |
| 50 |
"cyan_bold": "\033[1;36m", |
| 51 |
"white_bold": "\033[1;37m", |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
color_mapping = { |
| 56 |
"add": "green_bold", |
| 57 |
"subtract": "red_bold", |
| 58 |
"change": "yellow_bold", |
| 59 |
"separator": "blue", |
| 60 |
"description": "blue", |
| 61 |
"permissions": "yellow", |
| 62 |
"meta": "magenta", |
| 63 |
"line-numbers": "white", |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
class ConsoleDiff(object): |
| 68 |
"""Console colored side by side comparison with change highlights. |
| 69 |
|
| 70 |
Based on difflib.HtmlDiff |
| 71 |
|
| 72 |
This class can be used to create a text-mode table showing a side |
| 73 |
|
| 74 |
by side, line by line comparison of text with inter-line and |
| 75 |
intra-line change highlights in ansi color escape sequences as |
| 76 |
intra-line change highlights in ansi color escape sequences as |
| 77 |
read by xterm. The table can be generated in either full or |
| 78 |
contextual difference mode. |
| 79 |
|
| 80 |
To generate the table, call make_table. |
| 81 |
|
| 82 |
Usage is the almost the same as HtmlDiff except only make_table is |
| 83 |
implemented and the file can be invoked on the command line. |
| 84 |
Run:: |
| 85 |
|
| 86 |
python icdiff.py --help |
| 87 |
|
| 88 |
for command line usage information. |
| 89 |
|
| 90 |
""" |
| 91 |
|
| 92 |
def __init__( |
| 93 |
self, |
| 94 |
tabsize=8, |
| 95 |
wrapcolumn=None, |
| 96 |
linejunk=None, |
| 97 |
charjunk=difflib.IS_CHARACTER_JUNK, |
| 98 |
cols=80, |
| 99 |
line_numbers=False, |
| 100 |
show_all_spaces=False, |
| 101 |
show_no_spaces=False, |
| 102 |
highlight=False, |
| 103 |
truncate=False, |
| 104 |
strip_trailing_cr=False, |
| 105 |
): |
| 106 |
"""ConsoleDiff instance initializer |
| 107 |
|
| 108 |
Arguments: |
| 109 |
tabsize -- tab stop spacing, defaults to 8. |
| 110 |
wrapcolumn -- column number where lines are broken and wrapped, |
| 111 |
defaults to None where lines are not wrapped. |
| 112 |
linejunk, charjunk -- keyword arguments passed into ndiff() (used by |
| 113 |
ConsoleDiff() to generate the side by side differences). See |
| 114 |
ndiff() documentation for argument default values and descriptions. |
| 115 |
""" |
| 116 |
|
| 117 |
self._tabsize = tabsize |
| 118 |
self.line_numbers = line_numbers |
| 119 |
self.cols = cols |
| 120 |
self.show_all_spaces = show_all_spaces |
| 121 |
self.show_no_spaces = show_no_spaces |
| 122 |
self.highlight = highlight |
| 123 |
self.strip_trailing_cr = strip_trailing_cr |
| 124 |
self.truncate = truncate |
| 125 |
|
| 126 |
if wrapcolumn is None: |
| 127 |
if not line_numbers: |
| 128 |
wrapcolumn = self.cols // 2 - 2 |
| 129 |
else: |
| 130 |
wrapcolumn = self.cols // 2 - 10 |
| 131 |
|
| 132 |
self._wrapcolumn = wrapcolumn |
| 133 |
self._linejunk = linejunk |
| 134 |
self._charjunk = charjunk |
| 135 |
|
| 136 |
def _tab_newline_replace(self, fromlines, tolines): |
| 137 |
"""Returns from/to line lists with tabs expanded and newlines removed. |
| 138 |
|
| 139 |
Instead of tab characters being replaced by the number of spaces |
| 140 |
needed to fill in to the next tab stop, this function will fill |
| 141 |
the space with tab characters. This is done so that the difference |
| 142 |
algorithms can identify changes in a file when tabs are replaced by |
| 143 |
spaces and vice versa. At the end of the table generation, the tab |
| 144 |
characters will be replaced with a space. |
| 145 |
""" |
| 146 |
|
| 147 |
def expand_tabs(line): |
| 148 |
|
| 149 |
line = line.replace(" ", "\0") |
| 150 |
|
| 151 |
line = line.expandtabs(self._tabsize) |
| 152 |
|
| 153 |
|
| 154 |
line = line.replace(" ", "\t") |
| 155 |
return line.replace("\0", " ").rstrip("\n") |
| 156 |
|
| 157 |
fromlines = [expand_tabs(line) for line in fromlines] |
| 158 |
tolines = [expand_tabs(line) for line in tolines] |
| 159 |
return fromlines, tolines |
| 160 |
|
| 161 |
def _strip_trailing_cr(self, lines): |
| 162 |
"""Remove windows return carriage""" |
| 163 |
lines = [line.rstrip("\r") for line in lines] |
| 164 |
return lines |
| 165 |
|
| 166 |
def _all_cr_nl(self, lines): |
| 167 |
"""Whether a file is entirely \r\n line endings""" |
| 168 |
return all(line.endswith("\r") for line in lines) |
| 169 |
|
| 170 |
def _display_len(self, s): |
| 171 |
|
| 172 |
def width(c): |
| 173 |
if isinstance(c, type("")) and unicodedata.east_asian_width(c) in [ |
| 174 |
"F", |
| 175 |
"W", |
| 176 |
]: |
| 177 |
return 2 |
| 178 |
elif c == "\r": |
| 179 |
return 2 |
| 180 |
return 1 |
| 181 |
|
| 182 |
return sum(width(c) for c in s) |
| 183 |
|
| 184 |
def _split_line(self, data_list, line_num, text): |
| 185 |
"""Builds list of text lines by splitting text lines at wrap point |
| 186 |
|
| 187 |
This function will determine if the input text line needs to be |
| 188 |
wrapped (split) into separate lines. If so, the first wrap point |
| 189 |
will be determined and the first line appended to the output |
| 190 |
text line list. This function is used recursively to handle |
| 191 |
the second part of the split line to further split it. |
| 192 |
""" |
| 193 |
|
| 194 |
while True: |
| 195 |
|
| 196 |
|
| 197 |
if not line_num: |
| 198 |
data_list.append((line_num, text)) |
| 199 |
return |
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
if ( |
| 204 |
self._display_len(text) - (text.count("\0") * 3) |
| 205 |
<= self._wrapcolumn |
| 206 |
): |
| 207 |
data_list.append((line_num, text)) |
| 208 |
return |
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
i = 0 |
| 213 |
n = 0 |
| 214 |
mark = "" |
| 215 |
while n < self._wrapcolumn and i < len(text): |
| 216 |
if text[i] == "\0": |
| 217 |
i += 1 |
| 218 |
mark = text[i] |
| 219 |
i += 1 |
| 220 |
elif text[i] == "\1": |
| 221 |
i += 1 |
| 222 |
mark = "" |
| 223 |
else: |
| 224 |
n += self._display_len(text[i]) |
| 225 |
i += 1 |
| 226 |
|
| 227 |
|
| 228 |
line1 = text[:i] |
| 229 |
line2 = text[i:] |
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
if mark: |
| 235 |
line1 = line1 + "\1" |
| 236 |
line2 = "\0" + mark + line2 |
| 237 |
|
| 238 |
|
| 239 |
data_list.append((line_num, line1)) |
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
if self.truncate: |
| 244 |
return |
| 245 |
line_num = ">" |
| 246 |
text = line2 |
| 247 |
|
| 248 |
def _line_wrapper(self, diffs): |
| 249 |
"""Returns iterator that splits (wraps) mdiff text lines""" |
| 250 |
|
| 251 |
|
| 252 |
for fromdata, todata, flag in diffs: |
| 253 |
|
| 254 |
if flag is None: |
| 255 |
yield fromdata, todata, flag |
| 256 |
continue |
| 257 |
(fromline, fromtext), (toline, totext) = fromdata, todata |
| 258 |
|
| 259 |
|
| 260 |
fromlist, tolist = [], [] |
| 261 |
self._split_line(fromlist, fromline, fromtext) |
| 262 |
self._split_line(tolist, toline, totext) |
| 263 |
|
| 264 |
|
| 265 |
while fromlist or tolist: |
| 266 |
if fromlist: |
| 267 |
fromdata = fromlist.pop(0) |
| 268 |
else: |
| 269 |
fromdata = ("", " ") |
| 270 |
if tolist: |
| 271 |
todata = tolist.pop(0) |
| 272 |
else: |
| 273 |
todata = ("", " ") |
| 274 |
yield fromdata, todata, flag |
| 275 |
|
| 276 |
def _collect_lines(self, diffs): |
| 277 |
"""Collects mdiff output into separate lists |
| 278 |
|
| 279 |
Before storing the mdiff from/to data into a list, it is converted |
| 280 |
into a single line of text with console markup. |
| 281 |
""" |
| 282 |
|
| 283 |
|
| 284 |
for fromdata, todata, flag in diffs: |
| 285 |
if (fromdata, todata, flag) == (None, None, None): |
| 286 |
yield None |
| 287 |
else: |
| 288 |
yield ( |
| 289 |
self._format_line(*fromdata), |
| 290 |
self._format_line(*todata), |
| 291 |
) |
| 292 |
|
| 293 |
def _format_line(self, linenum, text): |
| 294 |
text = text.rstrip() |
| 295 |
if not self.line_numbers: |
| 296 |
return text |
| 297 |
return self._add_line_numbers(linenum, text) |
| 298 |
|
| 299 |
def _add_line_numbers(self, linenum, text): |
| 300 |
try: |
| 301 |
lid = "%d" % linenum |
| 302 |
except TypeError: |
| 303 |
|
| 304 |
lid = "" |
| 305 |
return text |
| 306 |
return "%s %s" % ( |
| 307 |
self._rpad(simple_colorize(str(lid), "line-numbers"), 8), |
| 308 |
text, |
| 309 |
) |
| 310 |
|
| 311 |
def _real_len(self, s): |
| 312 |
s_len = 0 |
| 313 |
in_esc = False |
| 314 |
prev = " " |
| 315 |
for c in replace_all( |
| 316 |
{"\0+": "", "\0-": "", "\0^": "", "\1": "", "\t": " "}, s |
| 317 |
): |
| 318 |
if in_esc: |
| 319 |
if c == "m": |
| 320 |
in_esc = False |
| 321 |
else: |
| 322 |
if c == "[" and prev == "\033": |
| 323 |
in_esc = True |
| 324 |
s_len -= 1 |
| 325 |
else: |
| 326 |
s_len += self._display_len(c) |
| 327 |
prev = c |
| 328 |
|
| 329 |
return s_len |
| 330 |
|
| 331 |
def _rpad(self, s, field_width): |
| 332 |
return self._pad(s, field_width) + s |
| 333 |
|
| 334 |
def _pad(self, s, field_width): |
| 335 |
return " " * (field_width - self._real_len(s)) |
| 336 |
|
| 337 |
def _lpad(self, s, field_width): |
| 338 |
return s + self._pad(s, field_width) |
| 339 |
|
| 340 |
def make_table( |
| 341 |
self, |
| 342 |
fromlines, |
| 343 |
tolines, |
| 344 |
fromdesc="", |
| 345 |
todesc="", |
| 346 |
fromperms=None, |
| 347 |
toperms=None, |
| 348 |
context=False, |
| 349 |
numlines=5, |
| 350 |
): |
| 351 |
"""Generates table of side by side comparison with change highlights |
| 352 |
|
| 353 |
Arguments: |
| 354 |
fromlines -- list of "from" lines |
| 355 |
tolines -- list of "to" lines |
| 356 |
fromdesc -- "from" file column header string |
| 357 |
todesc -- "to" file column header string |
| 358 |
fromperms -- "from" file permissions |
| 359 |
toperms -- "to" file permissions |
| 360 |
context -- set to True for contextual differences (defaults to False |
| 361 |
which shows full differences). |
| 362 |
numlines -- number of context lines. When context is set True, |
| 363 |
controls number of lines displayed before and after the change. |
| 364 |
When context is False, controls the number of lines to place |
| 365 |
the "next" link anchors before the next change (so click of |
| 366 |
"next" link jumps to just before the change). |
| 367 |
""" |
| 368 |
if context: |
| 369 |
context_lines = numlines |
| 370 |
else: |
| 371 |
context_lines = None |
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
fromlines, tolines = self._tab_newline_replace(fromlines, tolines) |
| 376 |
|
| 377 |
if self.strip_trailing_cr or ( |
| 378 |
self._all_cr_nl(fromlines) and self._all_cr_nl(tolines) |
| 379 |
): |
| 380 |
fromlines = self._strip_trailing_cr(fromlines) |
| 381 |
tolines = self._strip_trailing_cr(tolines) |
| 382 |
|
| 383 |
|
| 384 |
diffs = difflib._mdiff( |
| 385 |
fromlines, |
| 386 |
tolines, |
| 387 |
context_lines, |
| 388 |
linejunk=self._linejunk, |
| 389 |
charjunk=self._charjunk, |
| 390 |
) |
| 391 |
|
| 392 |
|
| 393 |
if self._wrapcolumn: |
| 394 |
diffs = self._line_wrapper(diffs) |
| 395 |
diffs = self._collect_lines(diffs) |
| 396 |
|
| 397 |
for left, right in self._generate_table( |
| 398 |
fromdesc, todesc, fromperms, toperms, diffs |
| 399 |
): |
| 400 |
yield self.colorize( |
| 401 |
"%s %s" |
| 402 |
% ( |
| 403 |
self._lpad(left, self.cols // 2 - 1), |
| 404 |
self._lpad(right, self.cols // 2 - 1), |
| 405 |
) |
| 406 |
) |
| 407 |
|
| 408 |
def _generate_table(self, fromdesc, todesc, fromperms, toperms, diffs): |
| 409 |
if fromdesc or todesc: |
| 410 |
yield ( |
| 411 |
simple_colorize(fromdesc, "description"), |
| 412 |
simple_colorize(todesc, "description"), |
| 413 |
) |
| 414 |
|
| 415 |
if fromperms != toperms: |
| 416 |
yield ( |
| 417 |
simple_colorize( |
| 418 |
f"{stat.filemode(fromperms)} ({fromperms:o})", |
| 419 |
"permissions", |
| 420 |
), |
| 421 |
simple_colorize( |
| 422 |
f"{stat.filemode(toperms)} ({toperms:o})", "permissions" |
| 423 |
), |
| 424 |
) |
| 425 |
|
| 426 |
for i, line in enumerate(diffs): |
| 427 |
if line is None: |
| 428 |
|
| 429 |
|
| 430 |
if i > 0: |
| 431 |
yield ( |
| 432 |
simple_colorize("---", "separator"), |
| 433 |
simple_colorize("---", "separator"), |
| 434 |
) |
| 435 |
else: |
| 436 |
yield line |
| 437 |
|
| 438 |
def colorize(self, s): |
| 439 |
def background(color): |
| 440 |
return replace_all( |
| 441 |
{"\033[1;": "\033[7;1;", "\033[0;": "\033[7;"}, color |
| 442 |
) |
| 443 |
|
| 444 |
C_ADD = color_codes[color_mapping["add"]] |
| 445 |
C_SUB = color_codes[color_mapping["subtract"]] |
| 446 |
C_CHG = color_codes[color_mapping["change"]] |
| 447 |
|
| 448 |
if self.highlight: |
| 449 |
C_ADD, C_SUB, C_CHG = ( |
| 450 |
background(C_ADD), |
| 451 |
background(C_SUB), |
| 452 |
background(C_CHG), |
| 453 |
) |
| 454 |
|
| 455 |
C_NONE = color_codes["none"] |
| 456 |
colors = (C_ADD, C_SUB, C_CHG, C_NONE) |
| 457 |
|
| 458 |
s = replace_all( |
| 459 |
{ |
| 460 |
"\0+": C_ADD, |
| 461 |
"\0-": C_SUB, |
| 462 |
"\0^": C_CHG, |
| 463 |
"\1": C_NONE, |
| 464 |
"\t": " ", |
| 465 |
"\r": "\\r", |
| 466 |
}, |
| 467 |
s, |
| 468 |
) |
| 469 |
|
| 470 |
if self.highlight: |
| 471 |
return s |
| 472 |
|
| 473 |
if self.show_no_spaces: |
| 474 |
|
| 475 |
return re.sub( |
| 476 |
"\033\\[[01];3([01234567])m(\\s+)(\033\\[)", |
| 477 |
"\033[0;3\\1m\\2\\3", |
| 478 |
s, |
| 479 |
) |
| 480 |
|
| 481 |
elif not self.show_all_spaces: |
| 482 |
|
| 483 |
|
| 484 |
return re.sub( |
| 485 |
"\033\\[[01];3([01234567])m(\\s+)(\033\\[)", |
| 486 |
"\033[7;3\\1m\\2\\3", |
| 487 |
s, |
| 488 |
) |
| 489 |
|
| 490 |
def will_see_coloredspace(i, s): |
| 491 |
while i < len(s) and s[i].isspace(): |
| 492 |
i += 1 |
| 493 |
if i < len(s) and s[i] == "\033": |
| 494 |
return False |
| 495 |
return True |
| 496 |
|
| 497 |
n_s = [] |
| 498 |
in_color = False |
| 499 |
seen_coloredspace = False |
| 500 |
for i, c in enumerate(s): |
| 501 |
if len(n_s) > 6 and n_s[-1] == "m": |
| 502 |
ns_end = "".join(n_s[-7:]) |
| 503 |
for color in colors: |
| 504 |
if ns_end.endswith(color): |
| 505 |
if color != in_color: |
| 506 |
seen_coloredspace = False |
| 507 |
in_color = color |
| 508 |
if ns_end.endswith(C_NONE): |
| 509 |
in_color = False |
| 510 |
|
| 511 |
if ( |
| 512 |
c.isspace() |
| 513 |
and in_color |
| 514 |
and ( |
| 515 |
self.show_all_spaces |
| 516 |
or not (seen_coloredspace or will_see_coloredspace(i, s)) |
| 517 |
) |
| 518 |
): |
| 519 |
n_s.extend([C_NONE, background(in_color), c, C_NONE, in_color]) |
| 520 |
else: |
| 521 |
if in_color: |
| 522 |
seen_coloredspace = True |
| 523 |
n_s.append(c) |
| 524 |
|
| 525 |
joined = "".join(n_s) |
| 526 |
|
| 527 |
return joined |
| 528 |
|
| 529 |
|
| 530 |
def raw_colorize(s, color): |
| 531 |
return "%s%s%s" % (color_codes[color], s, color_codes["none"]) |
| 532 |
|
| 533 |
|
| 534 |
def simple_colorize(s, category): |
| 535 |
return raw_colorize(s, color_mapping[category]) |
| 536 |
|
| 537 |
|
| 538 |
def replace_all(replacements, string): |
| 539 |
for search, replace in replacements.items(): |
| 540 |
string = string.replace(search, replace) |
| 541 |
return string |
| 542 |
|
| 543 |
|
| 544 |
class MultipleOption(Option): |
| 545 |
ACTIONS = Option.ACTIONS + ("extend",) |
| 546 |
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) |
| 547 |
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) |
| 548 |
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",) |
| 549 |
|
| 550 |
def take_action(self, action, dest, opt, value, values, parser): |
| 551 |
if action == "extend": |
| 552 |
values.ensure_value(dest, []).append(value) |
| 553 |
else: |
| 554 |
Option.take_action(self, action, dest, opt, value, values, parser) |
| 555 |
|
| 556 |
|
| 557 |
def create_option_parser(): |
| 558 |
|
| 559 |
parser = OptionParser( |
| 560 |
usage="usage: %prog [options] left_file right_file", |
| 561 |
version="icdiff version %s" % __version__, |
| 562 |
description="Show differences between files in a " "two column view.", |
| 563 |
option_class=MultipleOption, |
| 564 |
) |
| 565 |
parser.add_option( |
| 566 |
"--cols", |
| 567 |
default=None, |
| 568 |
help="specify the width of the screen. Autodetection is " "Unix only", |
| 569 |
) |
| 570 |
parser.add_option( |
| 571 |
"--encoding", |
| 572 |
default="utf-8", |
| 573 |
help="specify the file encoding; defaults to utf8", |
| 574 |
) |
| 575 |
parser.add_option( |
| 576 |
"-E", |
| 577 |
"--exclude-lines", |
| 578 |
action="store", |
| 579 |
type="string", |
| 580 |
dest="matcher", |
| 581 |
help="Do not diff lines that match this regex. Not " |
| 582 |
"compatible with the 'line-numbers' option", |
| 583 |
) |
| 584 |
parser.add_option( |
| 585 |
"--head", |
| 586 |
default=0, |
| 587 |
help="consider only the first N lines of each file", |
| 588 |
) |
| 589 |
parser.add_option( |
| 590 |
"-H", |
| 591 |
"--highlight", |
| 592 |
default=False, |
| 593 |
action="store_true", |
| 594 |
help="color by changing the background color instead of " |
| 595 |
"the foreground color. Very fast, ugly, displays all " |
| 596 |
"changes", |
| 597 |
) |
| 598 |
parser.add_option( |
| 599 |
"-L", |
| 600 |
"--label", |
| 601 |
action="extend", |
| 602 |
type="string", |
| 603 |
dest="labels", |
| 604 |
help="override file labels with arbitrary tags. " |
| 605 |
"Use twice, one for each file. You may include the " |
| 606 |
"formatting strings '{path}' and '{basename}'", |
| 607 |
) |
| 608 |
parser.add_option( |
| 609 |
"-N", |
| 610 |
"--line-numbers", |
| 611 |
default=False, |
| 612 |
action="store_true", |
| 613 |
help="generate output with line numbers. Not compatible " |
| 614 |
"with the 'exclude-lines' option.", |
| 615 |
) |
| 616 |
parser.add_option( |
| 617 |
"--no-bold", |
| 618 |
default=False, |
| 619 |
action="store_true", |
| 620 |
help="use non-bold colors; recommended for solarized", |
| 621 |
) |
| 622 |
parser.add_option( |
| 623 |
"--no-headers", |
| 624 |
default=False, |
| 625 |
action="store_true", |
| 626 |
help="don't label the left and right sides " "with their file names", |
| 627 |
) |
| 628 |
parser.add_option( |
| 629 |
"--output-encoding", |
| 630 |
default="utf-8", |
| 631 |
help="specify the output encoding; defaults to utf8", |
| 632 |
) |
| 633 |
parser.add_option( |
| 634 |
"-r", |
| 635 |
"--recursive", |
| 636 |
default=False, |
| 637 |
action="store_true", |
| 638 |
help="recursively compare subdirectories", |
| 639 |
) |
| 640 |
parser.add_option( |
| 641 |
"-s", |
| 642 |
"--report-identical-files", |
| 643 |
default=False, |
| 644 |
action="store_true", |
| 645 |
help="report when two files are the same", |
| 646 |
) |
| 647 |
parser.add_option( |
| 648 |
"--show-all-spaces", |
| 649 |
default=False, |
| 650 |
action="store_true", |
| 651 |
help="color all non-matching whitespace including " |
| 652 |
"that which is not needed for drawing the eye to " |
| 653 |
"changes. Slow, ugly, displays all changes", |
| 654 |
) |
| 655 |
parser.add_option( |
| 656 |
"--show-no-spaces", |
| 657 |
default=False, |
| 658 |
action="store_true", |
| 659 |
help="don't color whitespace-only changes", |
| 660 |
) |
| 661 |
parser.add_option("--tabsize", default=8, help="tab stop spacing") |
| 662 |
parser.add_option( |
| 663 |
"-t", |
| 664 |
"--truncate", |
| 665 |
default=False, |
| 666 |
action="store_true", |
| 667 |
help="truncate long lines instead of wrapping them", |
| 668 |
) |
| 669 |
parser.add_option( |
| 670 |
"-u", |
| 671 |
"--patch", |
| 672 |
default=True, |
| 673 |
action="store_true", |
| 674 |
help="generate patch. This is always true, " |
| 675 |
"and only exists for compatibility", |
| 676 |
) |
| 677 |
parser.add_option( |
| 678 |
"-U", |
| 679 |
"--unified", |
| 680 |
"--numlines", |
| 681 |
default=5, |
| 682 |
metavar="NUM", |
| 683 |
help="how many lines of context to print; " |
| 684 |
"can't be combined with --whole-file", |
| 685 |
) |
| 686 |
parser.add_option( |
| 687 |
"-W", |
| 688 |
"--whole-file", |
| 689 |
default=False, |
| 690 |
action="store_true", |
| 691 |
help="show the whole file instead of just changed " |
| 692 |
"lines and context", |
| 693 |
) |
| 694 |
parser.add_option( |
| 695 |
"-P", |
| 696 |
"--permissions", |
| 697 |
default=False, |
| 698 |
action="store_true", |
| 699 |
help="compare the file permissions as well as the " |
| 700 |
"content of the file", |
| 701 |
) |
| 702 |
parser.add_option( |
| 703 |
"--strip-trailing-cr", |
| 704 |
default=False, |
| 705 |
action="store_true", |
| 706 |
help="strip any trailing carriage return at the end of " |
| 707 |
"an input line", |
| 708 |
) |
| 709 |
parser.add_option( |
| 710 |
"--color-map", |
| 711 |
default=None, |
| 712 |
help="choose which colors are used for which items. " |
| 713 |
"Default is --color-map='" |
| 714 |
+ ",".join("%s:%s" % x for x in sorted(color_mapping.items())) |
| 715 |
+ "'" |
| 716 |
". You don't have to override all of them: " |
| 717 |
"'--color-map=separator:white,description:cyan", |
| 718 |
) |
| 719 |
parser.add_option( |
| 720 |
"--is-git-diff", |
| 721 |
default=False, |
| 722 |
action="store_true", |
| 723 |
help="Show the real file name when displaying " "git-diff result", |
| 724 |
) |
| 725 |
parser.add_option( |
| 726 |
"-x", |
| 727 |
"--exclude", |
| 728 |
metavar="PAT", |
| 729 |
action="append", |
| 730 |
default=[], |
| 731 |
help="exclude files that match PAT", |
| 732 |
) |
| 733 |
return parser |
| 734 |
|
| 735 |
|
| 736 |
def set_cols_option(options): |
| 737 |
if os.name == "nt": |
| 738 |
try: |
| 739 |
import struct |
| 740 |
from ctypes import windll, create_string_buffer |
| 741 |
|
| 742 |
fh = windll.kernel32.GetStdHandle(-12) |
| 743 |
csbi = create_string_buffer(22) |
| 744 |
windll.kernel32.GetConsoleScreenBufferInfo(fh, csbi) |
| 745 |
res = struct.unpack("hhhhHhhhhhh", csbi.raw) |
| 746 |
options.cols = res[7] - res[5] + 1 |
| 747 |
return |
| 748 |
|
| 749 |
except Exception: |
| 750 |
pass |
| 751 |
|
| 752 |
else: |
| 753 |
|
| 754 |
def ioctl_GWINSZ(fd): |
| 755 |
try: |
| 756 |
import fcntl |
| 757 |
import termios |
| 758 |
import struct |
| 759 |
|
| 760 |
cr = struct.unpack( |
| 761 |
"hhhh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "12345678") |
| 762 |
) |
| 763 |
except Exception: |
| 764 |
return None |
| 765 |
return cr |
| 766 |
|
| 767 |
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) |
| 768 |
if cr and cr[1] > 0: |
| 769 |
options.cols = cr[1] |
| 770 |
return |
| 771 |
options.cols = 80 |
| 772 |
|
| 773 |
|
| 774 |
def validate_has_two_arguments(parser, args): |
| 775 |
if len(args) != 2: |
| 776 |
parser.print_help() |
| 777 |
sys.exit(EXIT_CODE_DIFF) |
| 778 |
|
| 779 |
|
| 780 |
def start(): |
| 781 |
diffs_found = False |
| 782 |
parser = create_option_parser() |
| 783 |
options, args = parser.parse_args() |
| 784 |
validate_has_two_arguments(parser, args) |
| 785 |
if not options.cols: |
| 786 |
set_cols_option(options) |
| 787 |
try: |
| 788 |
diffs_found = diff(options, *args) |
| 789 |
except KeyboardInterrupt: |
| 790 |
pass |
| 791 |
except IOError as e: |
| 792 |
if e.errno == errno.EPIPE: |
| 793 |
pass |
| 794 |
else: |
| 795 |
raise |
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
sys.stderr.close() |
| 803 |
sys.exit(EXIT_CODE_DIFF if diffs_found else EXIT_CODE_SUCCESS) |
| 804 |
|
| 805 |
|
| 806 |
def codec_print(s, options): |
| 807 |
s = "%s\n" % s |
| 808 |
if hasattr(sys.stdout, "buffer"): |
| 809 |
sys.stdout.buffer.write(s.encode(options.output_encoding)) |
| 810 |
else: |
| 811 |
sys.stdout.write(s.encode(options.output_encoding)) |
| 812 |
|
| 813 |
|
| 814 |
def cmp_perms(options, a, b): |
| 815 |
return not options.permissions or ( |
| 816 |
os.lstat(a).st_mode == os.lstat(b).st_mode |
| 817 |
) |
| 818 |
|
| 819 |
|
| 820 |
def should_be_excluded(name, pats): |
| 821 |
return any(fnmatch.fnmatchcase(name, pat) for pat in pats) |
| 822 |
|
| 823 |
|
| 824 |
def diff(options, a, b): |
| 825 |
def print_meta(s): |
| 826 |
codec_print(simple_colorize(s, "meta"), options) |
| 827 |
|
| 828 |
|
| 829 |
diffs_found = False |
| 830 |
|
| 831 |
|
| 832 |
|
| 833 |
is_a_file = not os.path.isdir(a) |
| 834 |
is_b_file = not os.path.isdir(b) |
| 835 |
|
| 836 |
if is_a_file and is_b_file: |
| 837 |
try: |
| 838 |
if not ( |
| 839 |
filecmp.cmp(a, b, shallow=False) and cmp_perms(options, a, b) |
| 840 |
): |
| 841 |
diffs_found = diffs_found | diff_files(options, a, b) |
| 842 |
elif options.report_identical_files: |
| 843 |
print("Files %s and %s are identical." % (a, b)) |
| 844 |
except OSError as e: |
| 845 |
if e.errno == errno.ENOENT: |
| 846 |
print_meta("error: file '%s' was not found" % e.filename) |
| 847 |
sys.exit(EXIT_CODE_ERROR) |
| 848 |
else: |
| 849 |
raise (e) |
| 850 |
|
| 851 |
elif not is_a_file and not is_b_file: |
| 852 |
a_contents = set(os.listdir(a)) |
| 853 |
b_contents = set(os.listdir(b)) |
| 854 |
|
| 855 |
for child in sorted(a_contents.union(b_contents)): |
| 856 |
if should_be_excluded(child, options.exclude): |
| 857 |
continue |
| 858 |
if child not in b_contents: |
| 859 |
print_meta("Only in %s: %s" % (a, child)) |
| 860 |
elif child not in a_contents: |
| 861 |
print_meta("Only in %s: %s" % (b, child)) |
| 862 |
elif options.recursive: |
| 863 |
diffs_found = diffs_found | diff( |
| 864 |
options, os.path.join(a, child), os.path.join(b, child) |
| 865 |
) |
| 866 |
elif not is_a_file and is_b_file: |
| 867 |
print_meta("File %s is a directory while %s is a file" % (a, b)) |
| 868 |
diffs_found = True |
| 869 |
|
| 870 |
elif is_a_file and not is_b_file: |
| 871 |
print_meta("File %s is a file while %s is a directory" % (a, b)) |
| 872 |
diffs_found = True |
| 873 |
|
| 874 |
return diffs_found |
| 875 |
|
| 876 |
|
| 877 |
def read_file(fname, options): |
| 878 |
try: |
| 879 |
with open(fname, encoding=options.encoding, newline="") as inf: |
| 880 |
return inf.readlines() |
| 881 |
except UnicodeDecodeError as e: |
| 882 |
codec_print( |
| 883 |
"error: file '%s' not valid with encoding '%s': <%s> at %s-%s." |
| 884 |
% (fname, options.encoding, e.reason, e.start, e.end), |
| 885 |
options, |
| 886 |
) |
| 887 |
raise |
| 888 |
except LookupError: |
| 889 |
codec_print( |
| 890 |
"error: encoding '%s' was not found." % (options.encoding), options |
| 891 |
) |
| 892 |
sys.exit(EXIT_CODE_ERROR) |
| 893 |
|
| 894 |
|
| 895 |
def format_label(path, label="{path}"): |
| 896 |
"""Format a label using a file's path and basename. |
| 897 |
|
| 898 |
Example: |
| 899 |
For file `/foo/bar.py` and label "Yours: {basename}" - |
| 900 |
The output is "Yours: bar.py" |
| 901 |
""" |
| 902 |
return label.format(path=path, basename=os.path.basename(path)) |
| 903 |
|
| 904 |
|
| 905 |
def diff_files(options, a, b): |
| 906 |
diff_found = False |
| 907 |
if options.is_git_diff is True: |
| 908 |
|
| 909 |
base = os.getenv("BASE") |
| 910 |
headers = [format_label(a, base), format_label(b, base)] |
| 911 |
else: |
| 912 |
if options.labels: |
| 913 |
if len(options.labels) == 2: |
| 914 |
headers = [ |
| 915 |
format_label(a, options.labels[0]), |
| 916 |
format_label(b, options.labels[1]), |
| 917 |
] |
| 918 |
else: |
| 919 |
codec_print( |
| 920 |
"error: to use arbitrary file labels, " |
| 921 |
"specify -L twice.", |
| 922 |
options, |
| 923 |
) |
| 924 |
sys.exit(EXIT_CODE_ERROR) |
| 925 |
else: |
| 926 |
headers = a, b |
| 927 |
if options.no_headers: |
| 928 |
headers = None, None |
| 929 |
|
| 930 |
head = int(options.head) |
| 931 |
|
| 932 |
assert not os.path.isdir(a) |
| 933 |
assert not os.path.isdir(b) |
| 934 |
|
| 935 |
try: |
| 936 |
lines_a = read_file(a, options) |
| 937 |
lines_b = read_file(b, options) |
| 938 |
except UnicodeDecodeError: |
| 939 |
return diff_found |
| 940 |
|
| 941 |
if head != 0: |
| 942 |
lines_a = lines_a[:head] |
| 943 |
lines_b = lines_b[:head] |
| 944 |
|
| 945 |
if options.matcher: |
| 946 |
lines_a = [ |
| 947 |
line_a |
| 948 |
for line_a in lines_a |
| 949 |
if not re.search(options.matcher, line_a) |
| 950 |
] |
| 951 |
lines_b = [ |
| 952 |
line_b |
| 953 |
for line_b in lines_b |
| 954 |
if not re.search(options.matcher, line_b) |
| 955 |
] |
| 956 |
|
| 957 |
|
| 958 |
diff_found = lines_a != lines_b or not cmp_perms(options, a, b) |
| 959 |
|
| 960 |
if options.no_bold: |
| 961 |
for key in color_mapping: |
| 962 |
color_mapping[key] = color_mapping[key].replace("_bold", "") |
| 963 |
|
| 964 |
if options.color_map: |
| 965 |
command_for_errors = '--color-map="%s"' % (options.color_map) |
| 966 |
for mapping in options.color_map.split(","): |
| 967 |
category, color = mapping.split(":", 1) |
| 968 |
|
| 969 |
if category not in color_mapping: |
| 970 |
print( |
| 971 |
"Invalid category '%s' in '%s'. Valid categories are: %s." |
| 972 |
% ( |
| 973 |
category, |
| 974 |
command_for_errors, |
| 975 |
", ".join(sorted(color_mapping.keys())), |
| 976 |
) |
| 977 |
) |
| 978 |
sys.exit(EXIT_CODE_ERROR) |
| 979 |
|
| 980 |
if color not in color_codes: |
| 981 |
print( |
| 982 |
"Invalid color '%s' in '%s'. Valid colors are: %s." |
| 983 |
% ( |
| 984 |
color, |
| 985 |
command_for_errors, |
| 986 |
", ".join( |
| 987 |
[ |
| 988 |
raw_colorize(x, x) |
| 989 |
for x in sorted(color_codes.keys()) |
| 990 |
] |
| 991 |
), |
| 992 |
) |
| 993 |
) |
| 994 |
sys.exit(EXIT_CODE_ERROR) |
| 995 |
|
| 996 |
color_mapping[category] = color |
| 997 |
|
| 998 |
if options.permissions: |
| 999 |
mode_a = os.lstat(a).st_mode |
| 1000 |
mode_b = os.lstat(b).st_mode |
| 1001 |
else: |
| 1002 |
mode_a = None |
| 1003 |
mode_b = None |
| 1004 |
|
| 1005 |
cd = ConsoleDiff( |
| 1006 |
cols=int(options.cols), |
| 1007 |
show_all_spaces=options.show_all_spaces, |
| 1008 |
show_no_spaces=options.show_no_spaces, |
| 1009 |
highlight=options.highlight, |
| 1010 |
line_numbers=options.line_numbers, |
| 1011 |
tabsize=int(options.tabsize), |
| 1012 |
truncate=options.truncate, |
| 1013 |
strip_trailing_cr=options.strip_trailing_cr, |
| 1014 |
) |
| 1015 |
for line in cd.make_table( |
| 1016 |
lines_a, |
| 1017 |
lines_b, |
| 1018 |
headers[0], |
| 1019 |
headers[1], |
| 1020 |
mode_a, |
| 1021 |
mode_b, |
| 1022 |
context=(not options.whole_file), |
| 1023 |
numlines=int(options.unified), |
| 1024 |
): |
| 1025 |
codec_print(line, options) |
| 1026 |
sys.stdout.flush() |
| 1027 |
|
| 1028 |
return diff_found |
| 1029 |
|
| 1030 |
|
| 1031 |
if __name__ == "__main__": |
| 1032 |
start() |