class Eco::CliDefault::Input < Eco::API::Common::Loaders::CliConfig FORMATS = { csv: { option: ["-csv"], extname: [".csv", ".txt"] }, xml: { option: ["-xml"], extname: [".xml"] }, xls: { option: ["-xls", "-xlsx", "-excel"], extname: [".xls", ".xlsx", ".xlsm"] }, json: { option: ["-json"], extname: [".json"] } }.freeze 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 = 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 = 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)] end format ||= format_by_ext(ext.first) format ||= :csv options.deep_merge!(input: {file: {name: file}}) options.deep_merge!(input: {file: {format: format}}) 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 input = session.entries(**kargs) when :xls input = session.entries(file: file, format: format) when :json input = [file].flatten.reduce(Eco::API::Organization::People.new([])) do |people, filename| people.merge(JSON.parse(File.read(filename))) end else # :csv kargs = {check_headers: true} kargs.merge!(encoding: encoding) if encoding input = session.csv_entries(file, **kargs) end input end end