Skip to content

Instantly share code, notes, and snippets.

@seanhenry seanhenry/LineCounter.rb
Last active Nov 6, 2015

Embed
What would you like to do?
A script which counts lines of code in Swift and Objective-C projects. It ignores blank lines and counts production code and test code separately. It provides the average number of lines per file and the standard deviation.
# Usage: ruby LineCounter.rb <directory to search>
class LineCounter
def initialize(lineCounts)
@lineCounts = lineCountsFromString(lineCounts)
end
def lineCountsFromString(string)
lineCountsStrings = string.split("\n")
return lineCountsStrings.map { |e| e.to_i }
end
def standardDeviation
variance = @lineCounts.reduce(0) { |v, e| v + (mean - e)**2 }
variance = variance / (entries - 1).to_f
standardDeviation = Math.sqrt(variance)
end
def mean
fileCount = @lineCounts.length
meanLineCount = sum / fileCount
end
def sum
return @lineCounts.reduce(:+)
end
def entries
@lineCounts.length
end
end
directory = ARGV.last
excludeDependencies = "--exclude-dir=Carthage --exclude-dir=Pods"
includeFiles = "--include=*.swift --include=*.m"
excludeTests = "--exclude-dir=*Tests"
emptyLinePattern = "'^[[:space:]]*$'"
includeTestFiles = "--include=*Tests.swift --include=*Tests.m"
productionLineCounter = LineCounter.new(`grep #{includeFiles} #{excludeTests} #{excludeDependencies} --no-filename -cvr -e #{emptyLinePattern} #{directory}`)
testLineCounter = LineCounter.new(`grep #{includeTestFiles} #{excludeDependencies} --no-filename -cvr -e #{emptyLinePattern} #{directory}`)
puts "There are #{productionLineCounter.sum} lines of production code."
puts "There are #{testLineCounter.sum} lines of test code."
puts "There are #{productionLineCounter.entries} production files."
puts "The mean line count for production code is #{productionLineCounter.mean}."
puts "The standard deviation for production code is #{productionLineCounter.standardDeviation}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.