Created
November 29, 2012 05:28
-
-
Save pacojp/4166996 to your computer and use it in GitHub Desktop.
ruby source code identer
This file contains hidden or 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/env ruby | |
# | |
# ruby source code indenter | |
# | |
# need ruby 1.9.3 | |
# need a lot of refactoring!!!(but too tired now) | |
# | |
# | |
src = ARGF.read | |
l_max = r_max = 0 | |
space_max = 0 | |
REGEX = /^(\s*)(.+?)\s*(=>|=)\s*(.+?)\s*(#[^"]+)?$/ | |
def print_size(string) | |
string.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+) | |
end | |
def ljust_print_size(string, size) | |
padding_size = size - print_size(string) | |
padding_size = 0 if size < 0 | |
string + (' ' * padding_size) | |
end | |
#src.scan(REGEX) do | |
src.each_line do |line| | |
if line =~ REGEX | |
space_max = [space_max,$1.length].max | |
r_max = [r_max, print_size($4) + $3.length].max | |
l_max = [l_max, print_size($2)].max | |
end | |
end | |
ar = [] | |
src.each_line do |line| | |
ar << line.strip.gsub(REGEX) do | |
if $5.nil? | |
"%s%s%-#{l_max}s %s %s" % [(' ' * space_max), $1, $2, $3, $4] | |
else | |
minus = $3.length - 1 | |
"%s%s%-#{l_max}s %s #{ljust_print_size($4,r_max - minus)}%s" % [(' ' * space_max), $1, $2, $3, $5] | |
end | |
end | |
end | |
print ar.join("\n") | |
#src.gsub!(REGEX) do | |
# if $5.nil? | |
# "%-#{l_max}s %s %s" % [ $2, $3, $4] | |
# else | |
# "%-#{l_max}s %s %-#{r_max}s %s" % [ $2, $3, $4, $5] | |
# end | |
#end | |
#print src |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment