From 80ff4b6677d6a57e05b90dceae3249bb4190174b Mon Sep 17 00:00:00 2001 From: Holger Just Date: Thu, 10 Mar 2016 18:11:23 +0100 Subject: [PATCH] Detect color options for json helper from environment --- bin/json | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/bin/json b/bin/json index b4a59a6..8d60597 100755 --- a/bin/json +++ b/bin/json @@ -3,6 +3,19 @@ require 'rubygems' # 1.8.7 require 'json' +def print_json(json, colorize=true) + if colorize + begin + require 'awesome_print' + ap json + rescue LoadError + print_json(json, false) + end + else + puts JSON.pretty_generate(json) + end +end + if STDIN.tty? if File.exist?("/usr/bin/pbpaste") data = IO.popen('/usr/bin/pbpaste', 'r+').read @@ -20,9 +33,6 @@ rescue JSON::ParserError => err $stderr.puts err.message exit 1 end -if ARGV.include?('--color') - require 'ap' - ap json -else - puts JSON.pretty_generate(json) -end + +colorize = !ARGV.include?('--no-color') && STDOUT.tty? +print_json(json, colorize)