lib/eco/cli_default/input.rb in eco-helpers-3.0.20 vs lib/eco/cli_default/input.rb in eco-helpers-3.0.21
- old
+ new
@@ -1,8 +1,7 @@
-# rubocop:disable Metrics/BlockLength
-ASSETS.cli.config do |cnf|
- formats = {
+class Eco::CliDefault::Input < Eco::API::Common::Loaders::CliConfig
+ FORMATS = {
csv: {
option: ["-csv"],
extname: [".csv", ".txt"]
},
xml: {
@@ -15,55 +14,78 @@
},
json: {
option: ["-json"],
extname: [".json"]
}
- }
+ }.freeze
- cnf.input(default_option: "-entries-from") do |session, str_opt, options|
- input = []
+ class << self
+ attr_reader :options, :session
+ def encoding
+ options.dig(:input, :file, :encoding)
+ end
+
+ def format_by_cli
+ FORMATS.reduce(nil) do |matched, (frm, selectors)|
+ next matched if matched
+
+ used = selectors[:option].reduce(false) do |us, option|
+ SCR.get_arg(option) || us
+ end
+
+ next frm if used
+ end
+ end
+
+ def format_by_ext(ext)
+ FORMATS.reduce(nil) do |matched, (frm, selectors)|
+ next matched if matched
+ next frm if selectors[:extname].any? {|e| ext == e}
+ end
+ end
+ end
+
+ input(default_option: "-entries-from") do |session, str_opt, options|
+ @options = options
+ @session = session
+ input = []
next input unless SCR.get_arg(str_opt)
file = SCR.get_file(str_opt, required: true)
# Command line check
- format = formats.reduce(nil) do |matched, (frm, selectors)|
- used = selectors[:option].reduce(false) {|us, option| SCR.get_arg(option) || us}
- next matched if matched
- next frm if used
- end
+ format = format_by_cli
# File/Folder check
file = File.expand_path(file)
+
if File.directory?(file)
folder = file
file = Dir.glob("#{file}/*").reject {|f| File.directory?(f)}
- ext = (format && formats[format][:extname]) || [File.extname(file.first)]
- file = file.select {|f| ext.any? {|e| File.extname(f) == e}}.tap do |files|
- if files.empty?
- session.log(:error) {
- "Could not find any file with extension: #{ext} in folder '#{folder}'"
- }
- exit(1)
- end
+ ext = FORMATS.dig(format, :extname)
+ ext ||= [File.extname(file.first)]
+ file = file.select do |f|
+ ext.any? {|e| File.extname(f) == e}
+ end.tap do |files|
+ next unless files.empty?
+
+ session.log(:error) {
+ "Could not find any file with extension: #{ext} in folder '#{folder}'"
+ }
+ exit(1)
end
else
- ext = File.extname(file)
+ ext = [File.extname(file)]
end
- format ||= formats.reduce(nil) do |matched, (frm, selectors)|
- next matched if matched
- next frm if selectors[:extname].any? {|e| ext == e}
- end
+ format ||= format_by_ext(ext.first)
format ||= :csv
- options.deep_merge!(input: {file: {name: file}})
+ options.deep_merge!(input: {file: {name: file}})
options.deep_merge!(input: {file: {format: format}})
- encoding = options.dig(:input, :file, :encoding)
-
case format
when :xml
[file].flatten.each {|f| session.config.files.validate(:xml, f)}
kargs = {file: file, format: format}
kargs.merge!(encoding: encoding) if encoding
@@ -81,7 +103,5 @@
end
input
end
end
-
-# rubocop:enable Metrics/BlockLength