Last active
December 18, 2015 13:59
-
-
Save kainage/5793784 to your computer and use it in GitHub Desktop.
Tabs to spaces converter for files. Ruby 1.9 or greater.
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
require 'optparse' | |
module TabsToSpaces | |
def self.start(args, options) | |
@options = options | |
display_options_and_args(args) | |
process(args.first) | |
end | |
def self.process(arg) | |
substring = String.new.tap { |s| @options[:amount].to_i.times { s << ' ' } } | |
case | |
when is_not_file_or_dir?(arg) | |
# Do nothing | |
when File.directory?(arg) | |
p "Processing #{arg} as directory" if verbose? | |
Dir.open(arg).each do |dir| | |
next if is_not_file_or_dir?(dir) | |
next_dir = [arg, dir].join('/').gsub('//', '/') | |
# Recursively process directories | |
process(next_dir) | |
end if @options[:recursive] | |
when File.extname(arg) =~ /#{@options[:filetypes]}/ | |
p "Processing #{arg}" if verbose? | |
if File.extname(arg) =~ /#{@options[:exclusions]}/ | |
p "#{arg} matches the exclusion list. Skipping" | |
else | |
File .open(arg, 'r+') do |file| | |
subbed = file.read.gsub(/\t/, substring) | |
file.rewind | |
file.write subbed | |
end | |
end | |
else | |
p "#{arg} does not qualify to be parsed. Skipping" if verbose? | |
end | |
end | |
private | |
def self.is_not_file_or_dir?(arg) | |
arg == '.' || arg == '..' | |
end | |
def self.verbose? | |
@options[:verbose] | |
end | |
def self.display_options_and_args(args) | |
p @options if verbose? | |
p args if verbose? | |
end | |
end | |
if __FILE__ == $0 | |
options = { | |
amount: 2, | |
filetypes: ".rb|.erb|.css|.js|.rake", | |
exclusions: '.json|.yml|.scssc' | |
} | |
optparse = OptionParser.new do |opts| | |
opts.banner = "Usage: tabs2spaces.rb directory/file [options]" | |
opts.on("-v", "--verbose", "Run verbosely") do |v| | |
options[:verbose] = v | |
end | |
opts.on("-r", "--recursive", "Traverse through directories and process") do |r| | |
options[:recursive] = r | |
end | |
opts.on("-a", "--amount [INTEGER]", "Specify the amount of spaces to substitute (default 2)") do |a| | |
options[:amount] = a | |
end | |
opts.on("-f", "--filetypes [EXTENSIONS]", "Specify filetypes to process (Regex format. Default: '.rb|.erb|.css|.js|.rake')") do |f| | |
options[:filetypes] = f | |
end | |
opts.on("-e", "--exclude [EXTENSIONS]", "Specify exclude certain filetypes (Regex format. Default: '.json|.yml|.scssc')") do |e| | |
options[:exclusions] = e | |
end | |
end | |
optparse.parse! | |
if ARGV.size != 1 | |
puts optparse.help | |
exit | |
end | |
TabsToSpaces.start(ARGV, options) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment