module Eco module API class Session class Config class Apis module OneOff private def one_off? @is_one_off ||= SCR.get_arg('-api-key') || SCR.get_arg('-one-off') end def one_off_key return @one_off_key if instance_variable_defined?(:@one_off_key) return unless one_off? Dotenv.load('./.env_one_off') SCR.get_arg('-api-key', with_param: true).then do |key| one_off_key_env(key) end end def one_off_key_env(key) return unless one_off? if key env_file_set_var('./.env_one_off', one_off_key_env_var, key) key else Dotenv.load('./.env_one_off') ENV[one_off_key_env_var].tap do |k| msg = "At least the first time, " msg << "you should provide the -api-key" raise msg unless k end end end def one_off_key_env_var @one_off_key_env_var ||= "#{one_off_org}_KEY" end def one_off_org return @one_off_org if instance_variable_defined?(:@one_off_org) msg = "You should specify -org NAME when using -api-key or -one-off" raise msg unless org = SCR.get_arg('-org', with_param: true) str_org = "#{org.downcase.split(/[^a-z]+/).join('_')}_#{one_off_enviro.gsub('.', '_')}" @one_off_org ||= str_org.to_sym end def one_off_enviro return @one_off_enviro if instance_variable_defined?(:@one_off_enviro) enviro = 'live' enviro = SCR.get_arg('-enviro', with_param: true) if SCR.get_arg('-enviro') @one_off_enviro ||= enviro.downcase end def env_file_set_var(file, var, value) pattern = /"#{var}=(?[^ \r\n]+)"/ File.open(file, "w+") do |fd| found = false fd.each_line do |line| next unless (match = line.match(pattern)) found = true # IO::SEEK_CUR => Seeks to _amount_ plus current position fd.seek(-(line.length + 1), IO::SEEK_CUR) fd.write line.gsub(match[:value], value) end fd << "#{var}=#{value}" unless found end true rescue StandardError => err puts "#{err}" false end end end end end end end