require "uri" module Shipit module Cli # This class maintains all system-wide configuration for *shipit*. It properly # applies the correct source of configuration values based on the different contexts and # also makes sure that compulsory data are not missing. # class Configuration # List of all the configuration attributes stored for use within the gem ATTRIBUTES = [:endpoint, :private_token, :protected_branches] attr_accessor :endpoint, :private_token, :protected_branches # Apply a configuration hash to a configuration instance # # @example Override one of the configuration attributes # config = Shipit::Cli::Configuration.new # config.apply(private_token: 'supersecret') # config.private_token #=> "supersecret" # # @param attributes [Hash] list of key/values to apply to the configuration # @return [Object] the configuration object # def apply(attributes = {}) prepared_attributes = prepare_attributes attributes prepared_attributes.each_pair do |attribute, value| send("#{attribute}=", value) end self end # The configuration instance formatted as a stringified hash # # @example Override one of the configuration attributes # config = Shipit::Cli::Configuration.new # config.to_hash # #=> { "endpoint" => "https://gitlab.example.com/api/v3", "private_token" => "supersecret" } # # @return [Hash] the configuration object as a Hash # def to_hash config_hash = ATTRIBUTES.inject({}) do |hash, attr| hash["#{attr}"] = instance_variable_get("@#{attr}") hash end Shipit::Cli::Sanitizer.symbolize config_hash end # Write a configuration summary to STDOUT, useful for output in the CLI # def to_stdout to_hash.each_pair do |attribute, value| puts format("%-20s %-50s", "#{attribute}:", value) end nil end def motd_list File.readlines(File.expand_path('../../motd', __FILE__)).map(&:chomp) end private # Symbolize keys and remove nil or duplicate attributes # The attributes usually passed to our configuration class by the CLI # are usually full of duplicates and unconsistant keys, we make sure # to clean up that input, before doing any configuration work. # # @param attributes [Hash] list of key/values # @return [Hash] a clean list of key/values # def prepare_attributes(attributes) # Convert string keys to symbols symboled_attributes = Shipit::Cli::Sanitizer.symbolize attributes # Clean up user_attributes from unwanted, nil and duplicate options symboled_attributes.select { |key, _| ATTRIBUTES.include? key }.delete_if { |_, v| v.nil? } end end end end