lib/eco/cli/config/default/input.rb in eco-helpers-2.0.21 vs lib/eco/cli/config/default/input.rb in eco-helpers-2.0.22

- old
+ new

@@ -1,19 +1,72 @@ ASSETS.cli.config do |cnf| + 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"] + } + } + cnf.input(default_option: "-entries-from") do |session, str_opt, options| input = [] if SCR.get_arg(str_opt) file = SCR.get_file(str_opt, required: true) + + # Command line check + format = formats.reduce(nil) do |matched, (format, selectors)| + used = selectors[:option].reduce(false) {|used, option| SCR.get_arg(option) || used} + next matched if matched + next format if used + end + + # 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.logger.error("Could not find any file with extension: #{ext} in folder '#{folder}'") + exit(1) + end + end + else + ext = File.extname(file) + end + + format ||= formats.reduce(nil) do |matched, (format, selectors)| + next matched if matched + next format if selectors[:extname].any? {|e| ext == e} + end + format ||= :csv + options.deep_merge!(input: {file: {name: file}}) - if SCR.get_arg("-xml") - options.deep_merge!(input: {file: {format: :xml}}) - session.config.files.validate(:xml, file) - input = session.entries(file: file, format: :xml) - elsif SCR.get_arg("-json") - options.deep_merge!(input: {file: {format: :json}}) - input = Eco::API::Organization::People.new(JSON.parse(File.read(file))) + options.deep_merge!(input: {file: {format: format}}) + + case format + when :xml + [file].flatten.each {|f| session.config.files.validate(:xml, f)} + input = session.entries(file: file, format: format) + when :xls + input = session.entries(file: file, format: format) + when :json + input = [file].flatten.reduce(Eco::API::Organization::People.new([])) do |people, file| + people.merge(JSON.parse(File.read(file))) + end else - options.deep_merge!(input: {file: {format: :csv}}) input = session.csv_entries(file) end end input end