def write_multiline_key(key, value, prefix_=" "): lines = value.replace("\n", "\\\n").split("\n") tty_color(stream, _diff_color_mapping.get(prefix_)) stream.write("{0}{1} = {2}\n".format(prefix_, key, lines.pop(0))) for line in lines: stream.write("{0}{1}\n".format(prefix_, line)) tty_color(stream, ANSI_RESET)
def header(sign, filename): try: mtime = os.stat(filename).st_mtime ts = datetime.datetime.fromtimestamp(mtime) except OSError: ts = "1970-01-01 00:00:00" stream.write("{0} {1:50} {2}\n".format(sign * 3, filename, ts)) tty_color(stream, ANSI_RESET)
def show_value(value, stanza_, key, prefix_=""): tty_color(stream, _diff_color_mapping.get(prefix_)) if isinstance(value, dict): if stanza_ is not GLOBAL_STANZA: stream.write("{0}[{1}]\n".format(prefix_, stanza_)) for x, y in sorted(six.iteritems(value)): write_key(x, y, prefix_) stream.write("\n") else: write_key(key, value, prefix_) tty_color(stream, ANSI_RESET)
def show_text_diff(stream, a, b): _show_diff_header(stream, (a, b), "--text") differ = difflib.Differ() lines_a = open(a, "r", encoding=default_encoding).readlines() lines_b = open(b, "r", encoding=default_encoding).readlines() for d in differ.compare(lines_a, lines_b): # Someday add "?" highlighting. Trick is this should change color mid-line on the # previous (one or two) lines. (Google and see if somebody else solved this one already) # https://stackoverflow.com/questions/774316/python-difflib-highlighting-differences-inline tty_color(stream, _diff_color_mapping.get(d[0], 0)) stream.write(d) tty_color(stream, ANSI_RESET)
def _show_diff_header(stream, files, diff_line=None): def header(sign, filename): try: mtime = os.stat(filename).st_mtime ts = datetime.datetime.fromtimestamp(mtime) except OSError: ts = "1970-01-01 00:00:00" stream.write("{0} {1:50} {2}\n".format(sign * 3, filename, ts)) tty_color(stream, ANSI_RESET) tty_color(stream, ANSI_YELLOW, ANSI_BOLD) if diff_line: stream.write("diff {} {} {}\n".format(diff_line, files[0], files[1])) tty_color(stream, ANSI_RESET) header("-", files[0]) header("+", files[1])
def show_multiline_diff(value_a, value_b, key): def f(v): r = "{0} = {1}".format(key, v) r = r.replace("\n", "\\\n") return r.splitlines() a = f(value_a) b = f(value_b) differ = difflib.Differ() for d in differ.compare(a, b): # Someday add "?" highlighting. Trick is this should change color mid-line on the # previous (one or two) lines. (Google and see if somebody else solved this one already) # https://stackoverflow.com/questions/774316/python-difflib-highlighting-differences-inline tty_color(stream, _diff_color_mapping.get(d[0], 0)) # Differences in how difflib returns bytes/unicode? if not isinstance(d, six.text_type): d = d.decode(default_encoding) stream.write(d) tty_color(stream, ANSI_RESET) stream.write("\n")