Created
August 20, 2010 17:07
-
-
Save andynu/540724 to your computer and use it in GitHub Desktop.
a filter to colorize output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# encoding: utf-8 | |
# | |
# filter to colorize output | |
# | |
# cat file | highlight aaa bbb cc | |
# | |
# aaa,bbb,ccc all get assigned different colors and are highlighted in the output | |
# | |
class String | |
def mgsub(key_value_pairs=[].freeze) | |
regexp_fragments = key_value_pairs.collect { |k,v| k } | |
gsub( Regexp.union(*regexp_fragments)) do |match| | |
key_value_pairs.detect{|k,v| k =~ match}[1] + $1 + "\x1b[0m" | |
end | |
end | |
end | |
class Highlight | |
COLORS = %w[ 01 02 11 12 13 166 03 10 190 196 207 208 136 217 226 39 46 104 172 23 22 157 181 ] | |
RESET_COLOR = "\x1b[0m" | |
def initialize(terms) | |
@colors = assign_colors(terms) | |
end | |
def stream(io_stream) | |
while line = io_stream.gets | |
#io_stream.each_line do |line| | |
if line =~ /highlight:\s+(.*)$/ | |
@colors = assign_colors($1.to_s.split(/\s+/)) | |
end | |
$stdout.puts line.mgsub(@colors) | |
end | |
end | |
private | |
def color(fg, bg) | |
c = "" | |
c += "\x1b[38;5;#{fg}m" if fg | |
c += "\x1b[48;5;#{bg}m" if bg | |
c | |
end | |
def assign_colors(terms) | |
colors = [] | |
unless terms.nil? || terms.empty? | |
if terms.size > COLORS.size | |
$stderr.puts "More terms than colors, some colors will repeat" | |
end | |
terms.each_with_index do |term,i| | |
attr = 1 | |
fg = COLORS[i % COLORS.size] | |
bg = nil | |
regex = Regexp.new("(%s)" % [term]) | |
colors << [regex, color(fg,bg)] | |
#p "%s - %d - %s" % [term,i,colors[regex]] | |
end | |
end | |
return colors | |
end | |
end | |
STDOUT.sync = true | |
Highlight.new(ARGV).stream($stdin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment