Skip to content

Instantly share code, notes, and snippets.

@msharp
Created January 27, 2012 04:32
Show Gist options
  • Save msharp/1686998 to your computer and use it in GitHub Desktop.
Save msharp/1686998 to your computer and use it in GitHub Desktop.
Convert 4-space indents to 2-space indents
#!/usr/bin/ruby
#########################
#
# Convert rubycode with 4-space indents
# to regulation 2-space indenting format.
#
# supply directory as argument:
# > ruby indentity_correction.rb ./my_code_dir
#
#########################
def indents(num)
ind = ""
num.times {ind << " "}
ind
end
dir = ARGV[0]
# get all (ruby) files that have 4-space indents but NO 2-space indents
two_space = %x{egrep -r '^ {2}[^ ]' #{dir} | awk '{split($1,f,":");print f[1]}' | uniq}.split(/\n/)
four_space = %x{egrep -r '^ {4}[^ ]' #{dir} | awk '{split($1,f,":");print f[1]}' | egrep '\.(rb|rake)$' | uniq}.split(/\n/)
files = four_space - two_space
files.each do |f|
new_file = ""
File.open(f,"r") do |infile|
while (line = infile.gets)
indent = /^ {4,}[^ ]/.match(line)
if indent
len = indent[0].length-1
new_indent = len / 2
new_file << line.gsub(/^ {#{len}}/,indents(new_indent))
else
new_file << line
end
end
end
File.open(f,"w"){|f|f.puts new_file} if new_file != ""
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment