require "singleton" require "json" module Brief class Configuration include Singleton DefaultSettings = { github_username: "", github_api_token: "" } def self.method_missing meth, *args, &block if instance.respond_to?(meth) return instance.send meth, *args, &block end nil end def initialize! FileUtils.mkdir_p home_config_path.dirname end def method_missing meth, *args, &block if current.has_key?(meth.to_s) return current.fetch(meth) end super end def current_github_repository value = current.github_repository return value if value if value.nil? if guess = Brief::Git.current_github_repository set "github_repository", guess return guess end end current.github_repository end def current @current ||= begin home_config.merge(cwd_config) end end def current_config cwd_config_path.exist? ? cwd_config : home_config end def set setting, value, persist=true current_config[setting] = value save! if persist == true value end def unset setting, persist=true current_config.delete(setting) save! if persist == true end def current Hashie::Mash.new(home_config.merge(cwd_config).merge(applied_config)) end def apply_config_from_path path path = Pathname(path) parsed = JSON.parse(path.read) rescue {} applied_config.merge!(parsed) nil end def save! save_home_config save_cwd_config end def save_cwd_config return nil unless cwd_config_path.exist? File.open(cwd_config_path,'w+') do |fh| fh.write JSON.generate(cwd_config.to_hash) end end def save_home_config File.open(home_config_path,'w+') do |fh| fh.write JSON.generate(home_config.to_hash) end end # Applied config is configuration values passed in context # usually from the cli, but also in the unit tests def applied_config @applied_config ||= {} end def cwd_config @cwd_config ||= begin (cwd_config_path.exist? rescue false) ? JSON.parse(cwd_config_path.read) : {} rescue {} end end def home_config @home_config ||= begin (home_config_path.exist? rescue false) ? JSON.parse(home_config_path.read) : {} rescue {} end end def home_folder Pathname(ENV['HOME']).join('.brief') end def home_config_path Pathname(ENV['HOME']).join('.brief','config.json') end def cwd_config_path Pathname(Dir.pwd).join('.briefrc') end end end