YouPlot/lib/youplot/command.rb

111 lines
2.6 KiB
Ruby
Raw Normal View History

2020-09-18 23:08:09 +08:00
# frozen_string_literal: true
2020-12-21 13:25:52 +08:00
require_relative 'dsv'
2020-09-17 09:06:31 +08:00
require_relative 'command/parser'
# FIXME
require_relative 'backends/unicode_plot_backend'
2020-11-23 12:09:16 +08:00
module YouPlot
2020-08-15 21:12:42 +08:00
Data = Struct.new(:headers, :series)
2020-07-29 16:01:39 +08:00
class Command
2020-12-14 14:54:54 +08:00
attr_accessor :command, :params, :options
attr_reader :data, :parser
2020-08-15 16:10:41 +08:00
def initialize(argv = ARGV)
@argv = argv
@parser = Parser.new
2020-12-14 14:54:54 +08:00
@command = nil
@params = nil
@options = nil
@backend = YouPlot::Backends::UnicodePlotBackend
2020-09-15 17:51:32 +08:00
end
2020-07-29 16:01:39 +08:00
def run
parser.parse_options(@argv)
2020-12-14 14:54:54 +08:00
@command ||= parser.command
@options ||= parser.options
@params ||= parser.params
2020-09-15 17:58:34 +08:00
2020-12-17 11:37:27 +08:00
if %i[colors color colours colour].include? @command
plot = create_plot
output_plot(plot)
else
# Sometimes the input file does not end with a newline code.
while (input = Kernel.gets(nil))
main(input)
end
2020-12-14 21:02:18 +08:00
end
end
2020-12-14 21:02:18 +08:00
private
def main(input)
output_data(input)
@data = read_dsv(input)
pp @data if options[:debug]
plot = create_plot
output_plot(plot)
end
2020-12-14 21:02:18 +08:00
def read_dsv(input)
input = input.dup.force_encoding(options[:encoding]).encode('utf-8') if options[:encoding]
2020-12-21 15:09:37 +08:00
DSV.parse(input, options[:delimiter], options[:headers], options[:transpose])
2020-12-14 21:02:18 +08:00
end
def create_plot
case command
when :bar, :barplot
@backend.barplot(data, params, options[:fmt])
when :count, :c
@backend.barplot(data, params, count: true)
when :hist, :histogram
@backend.histogram(data, params)
when :line, :lineplot
@backend.line(data, params, options[:fmt])
when :lines, :lineplots
@backend.lines(data, params, options[:fmt])
when :scatter, :s
@backend.scatter(data, params, options[:fmt])
when :density, :d
@backend.density(data, params, options[:fmt])
when :box, :boxplot
@backend.boxplot(data, params)
2020-12-17 11:37:27 +08:00
when :colors, :color, :colours, :colour
@backend.colors(options[:color_names])
2020-12-14 21:02:18 +08:00
else
raise "unrecognized plot_type: #{command}"
end
end
def output_data(input)
# Pass the input to subsequent pipelines
case options[:pass]
when IO
options[:pass].print(input)
else
if options[:pass]
File.open(options[:pass], 'w') do |f|
f.print(input)
2020-09-29 17:13:03 +08:00
end
end
2020-12-14 21:02:18 +08:00
end
end
2020-07-29 16:01:39 +08:00
2020-12-14 21:02:18 +08:00
def output_plot(plot)
case options[:output]
when IO
plot.render(options[:output])
else
File.open(options[:output], 'w') do |f|
plot.render(f)
end
2020-07-30 09:37:20 +08:00
end
2020-07-29 16:01:39 +08:00
end
end
end