exe/gloc in gloc-0.1.0 vs exe/gloc in gloc-0.2.0

- old
+ new

@@ -1,10 +1,10 @@ #!/usr/bin/env ruby -s require 'ostruct' -source_files = if STDIN.tty? +source_files = if STDIN.tty? || $tty `git rev-parse --show-toplevel &> /dev/null` if $?.success? # we're inside a git repo so # get list of files from git `git ls-files -z #{ARGV.join(' ')}`.split("\0") @@ -52,11 +52,11 @@ '*.html' => %r{\A\s*(<!--.*-->)\s*\Z}, '*.css' => %r{\A\s*(/\*.*\*/)\s*\Z}, '*.js' => %r{\A\s*(//.*|/\*.*\*/)\s*\Z}, }.freeze -source_stats = Hash[source_files.each_with_object({}) { |file, stats| +source_stats = source_files.each_with_object({}) { |file, stats| file_ext = '*' + File.extname(file) # e.g. '*.rb' or '*' if no ext! stats_for_ext = begin stats[file_ext] ||= OpenStruct.new({ file_count: 0, line_count: 0, @@ -67,18 +67,33 @@ source_lines = File.read(file).each_line stats_for_ext.file_count += 1 stats_for_ext.line_count += source_lines.count stats_for_ext.blank_count += source_lines.grep(BLANKS).count stats_for_ext.comment_count += source_lines.grep(COMMENTS[file_ext]).count -}.sort_by { |_, stats| stats.line_count }.reverse] +} source_stats.values.each do |stats_for_ext| stats_for_ext.code_count = stats_for_ext.line_count - ( stats_for_ext.blank_count + stats_for_ext.comment_count ) end +sort_metric = case + when $files then :file_count + when $lines then :line_count + when $blank then :blank_count + when $comment then :comment_count + when $code then :code_count + else :code_count +end + +source_stats = Hash[ + source_stats.sort_by { |_, stats| + stats.send(sort_metric) + }.reverse +] + source_stats["TOTAL"] = OpenStruct.new({ file_count: source_stats.values.map(&:file_count).reduce(:+), line_count: source_stats.values.map(&:line_count).reduce(:+), blank_count: source_stats.values.map(&:blank_count).reduce(:+), comment_count: source_stats.values.map(&:comment_count).reduce(:+), @@ -87,11 +102,11 @@ # # JSON formatting for non-TTY output # -unless STDOUT.tty? +unless STDOUT.tty? || $tty require 'json' class OpenStruct def to_json(*args) self.to_h.to_json(args) @@ -134,10 +149,10 @@ # widest_comment_count = source_stats.values.map(&:comment_count).map(&:length).max # widest_code_count = source_stats.values.map(&:code_count).map(&:length).max totals = source_stats.delete("TOTAL").to_h.values -TEMPLATE = " %-13s %12s %12s %12s %12s %12s ".freeze +TEMPLATE = " %-13s %12s %12s %12s %12s %12s".freeze DIVIDER = ('-' * 80).freeze # `loc` uses 80 columns puts format("%s\n#{TEMPLATE}\n%s", DIVIDER, *%w(Language Files Lines Blank Comment Code),