Skip to content

Commit 9d69c43

Browse files
authored
Make configuration files available (#30)
1 parent 41c0d37 commit 9d69c43

2 files changed

Lines changed: 70 additions & 1 deletion

File tree

lib/youplot/command.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,24 @@ def run
4040
return
4141
end
4242

43+
# config command
44+
if @command == :config
45+
if ENV['MYYOUPLOTRC']
46+
puts "config file : #{ENV['MYYOUPLOTRC']}"
47+
puts parser.config.inspect
48+
else
49+
puts <<~EOS
50+
You don't have a config file. The default config file paths are:
51+
./.youplot.yml, ./.youplotrc, ~/.youplot.yml, ~/.youplotrc
52+
You can specify a config file with the environment variable MYYOUPLOTRC.
53+
File format is YAML. For example:
54+
width : 40
55+
height : 20
56+
EOS
57+
end
58+
return
59+
end
60+
4361
# progressive mode
4462
if options[:progressive]
4563
stop = false

lib/youplot/parser.rb

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ class Parser
99
class Error < StandardError; end
1010

1111
attr_reader :command, :options, :params,
12-
:main_parser, :sub_parser
12+
:main_parser, :sub_parser,
13+
:config_file, :config
1314

1415
def initialize
1516
@command = nil
@@ -28,6 +29,54 @@ def initialize
2829
)
2930

3031
@params = Parameters.new
32+
33+
if @config_file = find_config_file
34+
ENV['MYYOUPLOTRC'] = @config_file
35+
@config = read_config_file(config_file)
36+
configure(config)
37+
end
38+
end
39+
40+
def candidate_paths
41+
paths = []
42+
paths << ENV['MYYOUPLOTRC'] if ENV['MYYOUPLOTRC']
43+
paths << '.youplot.yml'
44+
paths << '.youplotrc'
45+
paths << File.join(ENV['HOME'], '.youplotrc') if ENV['HOME']
46+
paths << File.join(ENV['HOME'], '.youplot.yml') if ENV['HOME']
47+
paths
48+
end
49+
50+
def find_config_file
51+
config_file_path = nil
52+
candidate_paths.each do |file|
53+
path = File.expand_path(file)
54+
if File.exist?(path)
55+
config_file_path = path
56+
break
57+
end
58+
end
59+
config_file_path
60+
end
61+
62+
def read_config_file(path)
63+
require 'yaml'
64+
YAML.load_file(path)
65+
end
66+
67+
def configure(config)
68+
option_member = @options.members
69+
params_member = @params.members
70+
config.each do |k, v|
71+
k = k.to_sym
72+
if option_member.include?(k)
73+
@options[k] = v
74+
elsif params_member.include?(k)
75+
@params[k] = v
76+
else
77+
raise Error, "Unknown option/param: #{k}"
78+
end
79+
end
3180
end
3281

3382
def create_base_parser
@@ -277,6 +326,8 @@ def create_sub_parser
277326
options[:color_names] = v
278327
end
279328

329+
when :config
330+
280331
else
281332
error_message = "uplot: unrecognized command '#{command}'"
282333
if YouPlot.run_as_executable?

0 commit comments

Comments
 (0)