2024-07-02 22:44:35 +09:00
|
|
|
# frozen_string_literal: true
|
2024-07-01 09:32:50 +09:00
|
|
|
|
2024-07-02 22:44:35 +09:00
|
|
|
require 'optparse'
|
2024-07-01 09:32:50 +09:00
|
|
|
|
2024-07-25 08:33:11 +09:00
|
|
|
def main
|
|
|
|
options, input_sources = parse_options
|
|
|
|
all_stats = collect_all_stats(input_sources)
|
|
|
|
total_stats = calculate_total_stats(all_stats)
|
|
|
|
max_widths = calculate_max_widths(all_stats, total_stats)
|
|
|
|
print_all_stats(all_stats, max_widths, options)
|
|
|
|
print_all_stats([['合計', total_stats]], max_widths, options) if input_sources.size > 1
|
|
|
|
end
|
|
|
|
|
2024-07-12 13:18:19 +09:00
|
|
|
def parse_options
|
|
|
|
options = {}
|
|
|
|
OptionParser.new do |opts|
|
|
|
|
opts.on('-l') { options[:lines] = true }
|
|
|
|
opts.on('-w') { options[:words] = true }
|
|
|
|
opts.on('-c') { options[:bytes] = true }
|
|
|
|
end.parse!
|
|
|
|
options = { bytes: true, lines: true, words: true } if options.empty?
|
2024-07-25 08:33:11 +09:00
|
|
|
sources = ARGV.empty? ? [''] : ARGV
|
2024-07-21 09:50:07 +09:00
|
|
|
[options, sources]
|
2024-07-12 13:18:19 +09:00
|
|
|
end
|
2024-07-10 14:55:39 +09:00
|
|
|
|
2024-07-25 08:33:11 +09:00
|
|
|
def collect_all_stats(input_sources)
|
|
|
|
input_sources.map do |source|
|
|
|
|
input = source.empty? ? ARGF.read : File.read(source)
|
|
|
|
stats = { lines: input.lines.count, words: input.split.size, bytes: input.bytesize }
|
|
|
|
[source, stats]
|
2024-07-23 22:48:32 +09:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-07-25 08:33:11 +09:00
|
|
|
def calculate_total_stats(all_stats)
|
|
|
|
all_stats.reduce({ lines: 0, words: 0, bytes: 0 }) do |total, (_, stats)|
|
|
|
|
total.merge(stats) { |_, a, b| a + b }
|
2024-07-19 14:57:01 +09:00
|
|
|
end
|
2024-07-12 13:18:19 +09:00
|
|
|
end
|
2024-07-10 14:55:39 +09:00
|
|
|
|
2024-07-25 08:33:11 +09:00
|
|
|
def calculate_max_widths(all_stats, total_stats)
|
|
|
|
(all_stats.map(&:last) + [total_stats]).each_with_object({ lines: 0, words: 0, bytes: 0 }) do |stats, max_widths|
|
|
|
|
max_widths.merge!(stats) { |_, max, stat| [max, stat.to_s.length].max }
|
2024-07-20 22:01:46 +09:00
|
|
|
end
|
2024-07-12 13:18:19 +09:00
|
|
|
end
|
2024-07-10 14:55:39 +09:00
|
|
|
|
2024-07-12 13:18:19 +09:00
|
|
|
def format_result(stats, max_widths, options)
|
2024-07-25 08:33:11 +09:00
|
|
|
%i[lines words bytes].map { |key| stats[key].to_s.rjust(max_widths[key]) if options[key] }.compact.join(' ')
|
2024-07-12 13:18:19 +09:00
|
|
|
end
|
2024-07-02 22:44:35 +09:00
|
|
|
|
2024-07-25 08:33:11 +09:00
|
|
|
def print_all_stats(all_stats, max_widths, options)
|
|
|
|
all_stats.each do |source, stats|
|
|
|
|
result = format_result(stats, max_widths, options)
|
|
|
|
puts "#{result} #{source}"
|
|
|
|
end
|
2024-07-10 14:55:39 +09:00
|
|
|
end
|
2024-07-20 22:45:14 +09:00
|
|
|
|
2024-07-25 08:33:11 +09:00
|
|
|
main
|