require 'yaml' class Fanforce::AppFactory::CLI::Env include Fanforce::AppFactory::CLI::Utils attr_reader :app def initialize(app) @app = app end def setup(environment) environment = environment.to_sym bind_path = "#{app.dir}/../.env/_bind.yml" error 'You must setup .env/_bind.yml before updating env variables.' if !File.exists?(bind_path) vars = vars(environment) has_workers = File.directory?("#{app.dir}/workers") ? true : false return log "#{'Skipped'.format(:bold)} #{environment.to_s.titleize} has 0 env variables" if vars.blank? or vars.size == 0 push_to(environment, vars) log "#{'Updated'.format(:green,:bold)} #{environment.to_s.titleize}#{has_workers ? '... and workers have' : ' has'} #{vars.size} env variables" end def push_to(environment, vars, create_worker_env=true) environment = environment.to_sym vars.each {|k,v| puts " - #{k}" } workers_dir = "#{app.dir}/workers" workers_env_dir = "#{workers_dir}/.env" if create_worker_env and File.directory?(workers_dir) and vars['IRON_PROJECT_ID'] FileUtils.mkdir_p(workers_env_dir) unless File.directory?(workers_env_dir) File.open("#{workers_env_dir}/#{environment}.rb", 'w') {|f| f.write convert_hash_to_ruby_env(vars) } end if environment == :development update_powenv File.open("#{app.dir}/.appenv", 'w') {|f| f.write convert_hash_to_shell_env(vars) } else error 'could not find heroku in .fanforce-app-factory' if config[:heroku][environment].blank? Fanforce::AppFactory::CLI::Heroku.new(app).update_config(environment, vars) end end def convert_hash_to_shell_env(hash) hash.inject('') {|script, (k,v)| script += "export #{k}=#{v.to_s.to_json}\n" } end def convert_hash_to_ruby_env(hash) hash.inject('') {|script, (k,v)| script += "ENV['#{k}']=#{v.to_s.to_json}\n" } end def load_vars(environment) environment = environment.to_sym vars = {'FANFORCE_APP_ID' => app._id} raw_yaml = File.read("#{app.dir}/../.env/_bind.yml") bindings = (raw_yaml.present?) ? YAML.load(raw_yaml) : {} bindings.each do |filename, dir_names| file = YAML.load_file("#{app.dir}/../.env/#{filename}.yml").symbolize_keys next if file[environment].blank? dir_names = [app.dir_name] if dir_names.is_a?(String) and dir_names.upcase == 'ALL' file[environment].each do |k,v| dir_names.each {|dir_name| vars["#{filename}_#{k}".upcase] = v if dir_name == app.dir_name } end end return vars end def vars(environment) @vars ||= {} @vars[environment] ||= load_vars(environment) end # .POWENV ####################################################################### def create_powenv file = powenv_lines.join("\n") + "\n" File.open("#{app.dir}/.powenv", 'w') {|f| f.write file } end def update_powenv return create_powenv if !File.exists?("#{app.dir}/.powenv") lines = File.open("#{app.dir}/.powenv", 'r') {|f| f.readlines}.map {|l| l.strip } powenv_lines.each do |line| lines << line if !lines.include?(line) end File.open("#{app.dir}/.powenv", 'w') {|f| f.write(lines.join "\n") } end def powenv_lines ['source .appenv'] end end