Sha256: 7e2230754dcee153fa13e8e4306a8a91b48383814da4e30118745ef053d13188

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

class Vars < BasicObject
  class Options
    attr_reader :opts

    DEFAULT_NAME   = "default".freeze
    DEFAULT_BRANCH = "master".freeze

    def initialize(opts = {})
      @opts = opts.transform_keys(&:to_sym)
    end

    def name
      opts.fetch(:name, ENV.fetch("APP_ENV", DEFAULT_NAME))
    end

    def repo_path
      return opts.fetch(:repo_path) if opts.key?(:repo_path)

      in_repository? ? `git rev-parse --show-toplevel`.chomp : nil
    end

    def branch
      return opts.fetch(:branch) if opts.key?(:branch)
      return ENV["TARGET_BRANCH"] if ENV.key?("TARGET_BRANCH")

      in_repository? ? `git symbolic-ref --short HEAD`.chomp : DEFAULT_BRANCH
    end

    def source_type
      opts.fetch(:source_type, :path)
    end

    def load_source(path)
      src = YAML.safe_load(ERB.new(raw_source(path), nil, "-").result(binding), [], [], true)
      src.fetch("default", {}).merge(src.fetch(name.to_s))
    end

    def in_repository?
      return @in_repository if instance_variable_defined?(:@in_repository)

      _, _, status = Open3.capture3("git rev-parse --git-dir")
      @in_repository = status.exitstatus.zero?
    end

    private

      def raw_source(path)
        case source_type
        when :path
          File.read(path)
        when :git
          raise "repo_path is nil" if repo_path.nil?
          Dir.chdir(repo_path) { `git show #{branch}:#{path}` }
        else
          raise "Unknown source_type: #{source_type}"
        end
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vars-0.0.1 lib/vars/options.rb