public
Created — forked from jstorimer/hilong.rb

hilong -- A simply utility to show character counts for each line of input and highlight lines longer than 80 characters.

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#!/usr/bin/env ruby
 
# hilong -- A simply utility to show character counts for each line of input and
# highlight lines longer than 80 characters.
#
# Written as an example for {post}
#
# Examples:
#
# $ hilong Gemfile
# $ hilong Gemfile | more
# $ hilong Gemfile > output.txt
# $ hilong Gemfile Gemfile.lock
# $ cat Gemfile* | hilong
# $ cat Gemfile | hilong - Gemfile.lock
 
# escaped bash color codes
red = "\e[31m"
reset_color = "\e[0m"
 
maximum_line_length = 80
 
# Read input from ARGF in one kb chunks.
def read_input
ARGF.readpartial(1024)
rescue EOFError
end
 
# Keep reading chunks of input as long as they're coming.
while input = read_input
input.each_line do |line|
# Construct a string that begins with the length of this line
# and ends with the content. The trailing newline is #chop'ped
# off of the content so we can control where the newline occurs.
# The string are joined with a tab character so that indentation
# is preserved.
output_line = [line.size, line.chop].join("\t")
 
# If the line is long and our $stdout is not being piped then we'll
# colorize this line.
if $stdout.tty? && line.size > maximum_line_length
# Turn the output to red starting at the first character.
output_line.insert(0, red)
# Reset the text color back to what it was at the end of the
# line.
output_line.insert(-1, reset_color)
end
 
$stdout.puts output_line
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.