Friday 29 July 2016

Color Diff

Few months ago I have found I feel lack of the highlighting capability of the diff output. To cover this lack I began to look for solutions. A lot of resources refer to the colordiff, the tool written in Perl. But I wasn't satisfied with it. Question on StackOverflow and this article have inspired me to develop the Bash function having the same (or almost the same) functionality as colordiff and having mechanism as described in the early mentioned article.

Some of you can say I have re-invented the wheel because a) there is colordiff, b) diff has the special options to format output. But I'd like to have simple solution with full support of many output formats as much as possible and the simple usage as the command itself. It uses sed to format (colorize) diff output. It has the following features:

  • The wrapper and can be called as the replacement instead the standard tool;
  • Analyzes command line options and generates the special sed commands colorizing output;
  • Covers all known formatting options (--context, --unified, --ed, --rcs, --side-by-side, --show-c-function);
  • It supports CDIFF_COLORS and CDIFF_WHEN, the special environment variables having impact on the function behavior (they works similar to GREP_COLORS for grep).

There is help page below. Just follow this link, download the script and try.

$ diff
Usage: colordiff [OPTION]... FILES

Wrapper for diff to colorize the diff's output for better readability.
Try "diff --help" for more information.

OPTIONS

Diff options

All options will be passed to "diff".

Coloring options

--color[=WHEN], --colour[=WHEN]

Controls the colorizing method. WHEN can be one of "never", "auto" or
"always" (the default value if not specified explicitly). To make affect
globally, set one of these values to CDIFF_WHEN environment variable.

ENVIRONMENT VARIABLES

CDIFF_COLORS
This environment variable is used to specify colors to highlight the
separate parts of the diff output. Its value is a colon-separated list
of capabilities. Names and responsibility of each capability correspond
to the configuration parameters "color.diff." used in "git config".
Values are integers in decimal representation and can be concatenated with
semicolons. Further these values are assembled into ANSI escape codes.

meta=40;1;37
Metainformation (names of compared files)

frag=36
Hunk header (line numbers of changed lines)

old=31
Removed lines

new=32
Added lines

mod=34
Modified lines

CDIFF_WHEN
Colorizing method does effect on all runs; assumes the same values as for
the "--color" option. The default value is "auto" and can be superseded
by the "--color" option.