Skip to content

Instantly share code, notes, and snippets.

@whylom
Created April 20, 2012 18:57
Show Gist options
  • Save whylom/2431034 to your computer and use it in GitHub Desktop.
Save whylom/2431034 to your computer and use it in GitHub Desktop.
Count the files and lines of code in a directory tree.
# 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"
@Yogu
Copy link

Yogu commented Oct 23, 2012

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").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment