Created
April 20, 2012 18:57
-
-
Save whylom/2431034 to your computer and use it in GitHub Desktop.
Count the files and lines of code in a directory tree.
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
# Shell out to the fast and reliable `wc` utility. | |
def lines(path) | |
# output of wc (returned by backticks) is formatted like this: | |
# " 111 filename.ext" | |
`wc -l #{path}`.strip.split(' ').first.to_i | |
end | |
# **/* gets all files and directories in all subdirectories. | |
files = Dir["/path/to/directory/**/*"] | |
# remove directories from the list (wc complains when you give it directories) | |
files.select! { |f| File.file?(f) } | |
# transform array of filepaths to an array of line counts, then sum them all up | |
total_lines_of_code = files.map { |f| lines(f) }.inject(:+) | |
number_of_files = files.size | |
average_lines_per_file = total_lines_of_code / number_of_files | |
puts "#{number_of_files} files" | |
puts "#{total_lines_of_code} total lines of code" | |
puts "#{average_lines_per_file} average lines of code per file" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to pass the directory per parameter, replace line 9 by
files = Dir[ARGV[0]]
, and - important - encapsulate the argument into strings (e.g../loc "/home/me/project/**/*.rb"
).