Skip to content

Instantly share code, notes, and snippets.

@tiennou
Created July 29, 2016 13:05
Show Gist options
  • Save tiennou/0e5de476075bbfb82fc7dabecb5f8268 to your computer and use it in GitHub Desktop.
Save tiennou/0e5de476075bbfb82fc7dabecb5f8268 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -W
# encoding: utf-8
# This script takes a glob pattern as input (eg. "*.[hm]"), and reports
# indentation statistics for files matching the pattern in the current
# directory, recursively.
require 'set'
pattern = ARGV.shift
if pattern.nil?
puts "No pattern given"
exit 1
end
root_pattern = File.join(Dir.getwd, '**', pattern)
stats = {}
Dir.glob(root_pattern) do |file|
stats[file] ||= {
lines: 0,
tabs: 0,
spaces: 0,
}
IO.foreach(file) do |line|
stats[file][:lines] += 1
begin
if /^ /.match(line) then
stats[file][:tabs] += 1
end
if /^ /.match(line) then
stats[file][:spaces] += 1
end
rescue
puts "Failed to match #{file}:#{line}"
end
end
end
line_count = stats.collect {|file, stat| stat[:lines]}.reduce :+
tabs_count = stats.collect {|file, stat| stat[:tabs]}.reduce :+
spaces_count = stats.collect {|file, stat| stat[:spaces]}.reduce :+
file_tabs_count = stats.select {|file, stat| stat[:tabs] != 0 && stat[:spaces] == 0}.collect { 1 }.reduce :+
file_spaces_count = stats.select {|file, stat| stat[:tabs] == 0 && stat[:spaces] != 0}.collect { 1 }.reduce :+
mismatched_files = stats.select {|file, stat| stat[:tabs] != 0 and stat[:spaces] != 0 }
puts "Processed #{line_count} lines in #{stats.count} files, #{tabs_count} tab lines, #{spaces_count} spaces lines"
puts "#{file_tabs_count} tab files, #{file_spaces_count} space files"
mismatch_stats = {tabs: 0, spaces: 0}
puts "#{mismatched_files.count} files have mismatching indent :"
mismatched_files.each do |file, stat|
file = file.sub Dir.getwd+'', "."
msg = case
when stat[:tabs] > stat[:spaces] then
mismatch_stats[:tabs] += 1
"has more tabs"
when stat[:tabs] < stat[:spaces] then
mismatch_stats[:spaces] += 1
"has more spaces"
else "has same number"
end
puts "#{file} #{msg}"
end
puts "#{mismatch_stats[:tabs]} mismatching files have more tabs, #{mismatch_stats[:spaces]} have more spaces"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment