From 4ec4c36e111254ebdfa8001f845003a99e81193e Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Sat, 7 Dec 2013 17:44:12 +0100 Subject: common-bytes: fix color termination Previously, the colors were not cleared as an attempt to optimize printing. New approach (requiring less LOC as well): print color if it does not equal the current state (previous color). --- common-bytes.py | 39 +++++++++++++++++---------------------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/common-bytes.py b/common-bytes.py index 1210ec0..2376fb6 100755 --- a/common-bytes.py +++ b/common-bytes.py @@ -129,12 +129,19 @@ def mark_skippable(colormap, line_width): return skip_mask +colors = { +CELL_ALLSAME: CLEAR_COLOR, +CELL_COMMON: "\033[0;32m", # green, +CELL_COMMON_SHARED: "\033[0;33m", # yellow +CELL_OUTLIER: "\033[1;31m", # red +} + # Display input, coloring changes def display_changes(lines, line_width, colormap, skip_mask, enable_skip): skipping = False for lineno, line in enumerate(lines): line_out = "" - is_colored = False + prev_color = CLEAR_COLOR line_color = colormap[lineno] for col in range(0, line_width): # skip common cells? @@ -144,37 +151,25 @@ def display_changes(lines, line_width, colormap, skip_mask, enable_skip): continue elif skip_mask[col] > 0: # N columns can be skipped (N = skip_mask[col]) - line_out += "\033[1;30m..{}..".format(skip_mask[col]) - is_colored = True + prev_color = "\033[1;30m" + line_out += prev_color + "..{}..".format(skip_mask[col]) skipping = True continue else: # end of skippable columns skipping = False - # only change colors if not skipping - if skip_mask[col] != -1: - coloring = line_color[col] - if coloring == CELL_ALLSAME: - if is_colored: - line_out += CLEAR_COLOR - is_colored = False - elif coloring == CELL_COMMON: - line_out += "\033[0;32m" # green - is_colored = True - elif coloring == CELL_COMMON_SHARED: - line_out += "\033[0;33m" # yellow - is_colored = True - elif coloring == CELL_OUTLIER: - line_out += "\033[1;31m" # red - is_colored = True - else: - raise AssertionError("Invalid coloring state") + # apply coloring + coloring = line_color[col] + new_color = colors[coloring] + if prev_color != new_color: + line_out += new_color + prev_color = new_color line_out += line[col] # Any colors must be cleared at the end of the line - if is_colored: + if prev_color != CLEAR_COLOR: line_out += CLEAR_COLOR print(line_out) -- cgit v1.2.1