Skip to content

Commit

Permalink
Introduce smarter coloring and --colorize option
Browse files Browse the repository at this point in the history
By default, do not colorize when stdout is not a tty. The --colorize option,
with possible values 'auto', 'always', and 'never' -- defaults to 'auto' when
not specified, and registers as 'always' when specified without a value -- is
similar to the --color option found in many well known *nix tools, with
coreutils ls(1) being a notable example. (Our option is named --colorize since
we already have a --colors option.) The old -C, --nocolor option is now a
shortcut for --colorize=never.

Limitation: due to limitations of Python argparse, specifically not being able
to make the equal sign between a long option and its value mandatory, one might
expect the following to work:

    googler --colorize google

but it does not, due to "google" being parsed as an argument to --colorize. One
has to write

    googler --colorize -- google

instead.
  • Loading branch information
zmwangx committed Apr 10, 2019
1 parent 63744b3 commit c9eb8c8
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions googler
Expand Up @@ -3126,8 +3126,13 @@ def parse_args(args=None, namespace=None):
addarg('-l', '--lang', metavar='LANG', help='display in language LANG')
addarg('-x', '--exact', action='store_true',
help='disable automatic spelling correction')
addarg('-C', '--nocolor', dest='colorize', action='store_false',
help='disable color output')
addarg('--colorize', nargs='?', choices=['auto', 'always', 'never'],
const='always', default='auto',
help="""whether to colorize output; defaults to 'auto', which enables
color when stdout is a tty device; using --colorize without an argument
is equivalent to --colorize=always""")
addarg('-C', '--nocolor', action='store_true',
help='equivalent to --colorize=never')
addarg('--colors', dest='colorstr', type=argparser.is_colorstr,
default=colorstr_env if colorstr_env else 'GKlgxy', metavar='COLORS',
help='set output colors (see man page for details)')
Expand Down Expand Up @@ -3165,7 +3170,11 @@ def parse_args(args=None, namespace=None):
addarg('-D', '--debugger', action='store_true', help=argparse.SUPPRESS)
addarg('--complete', help=argparse.SUPPRESS)

return argparser.parse_args(args, namespace)
parsed = argparser.parse_args(args, namespace)
if parsed.nocolor:
parsed.colorize = 'never'

return parsed


def main():
Expand Down Expand Up @@ -3203,7 +3212,16 @@ def main():
pass

# Set colors
if opts.colorize:
if opts.colorize == 'always':
colorize = True
elif opts.colorize == 'auto':
colorize = sys.stdout.isatty()
elif opts.colorize == 'never':
colorize = False
else:
raise ValueError("invalid --colorize value '%s'" % opts.colorize)

if colorize:
colors = Colors(*[COLORMAP[c] for c in opts.colorstr], reset=COLORMAP['x'])
else:
colors = None
Expand Down

0 comments on commit c9eb8c8

Please sign in to comment.