Sha256: 083ee63e6b0dcb72a367cf452bbf5c47af1e89d460ae2fa3dcc241ddf7e8f97c

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

require_relative 'helper'
require_relative 'ext/hash'
module Dply
  class MetaConfig

    using HashExt

    include Helper

    def initialize(dir)
      @sources = []
      @dir = dir
      @output_path = "#{dir}/meta_generated.yml"
      @tmpfile = "#{dir}/meta.tmp"
    end

    def define(&block)
      instance_eval &block
    end

    def generate
      config = {}
      @sources.each do |i|
        path = i.fetch(:path)
        url = i.fetch(:url)
        auth = i.fetch(:auth)
        optional = i.fetch(:optional)
        deep_merge = i.fetch(:deep_merge)
        block = i.fetch(:block)

        if url
          download(url, path, optional: optional)
        end

        if block
          instance_exec path, optional, &block
        end
        
        h = load_yml(path, optional: optional)
        deep_merge ? config.deep_merge!(h) : config.merge!(h)
      end
      File.write @tmpfile, YAML.dump(config)
      FileUtils.mv @tmpfile, @output_path
    end

    private

    def config(path, url = nil, auth: nil, deep_merge: true, optional: false, &block)
      path = "#{@dir}/#{path}"
      @sources << { path: path, url: url, auth: auth, deep_merge: deep_merge,
                    optional: optional, block: block }
    end

    def load_yml(path, optional:)
      if not File.readable? path
        return {} if optional
        raise Error, "error reading file #{path}"
      end
      YAML.safe_load(File.read(path)) || {}
    end

    def download(url, path, optional:)
      logger.bullet "downloading #{url}"
      http_status = IO.popen(["curl", "-w", '%{http_code}', "-f", "-s", "-o", @tmpfile, url]) { |f| f.read }
      exit_status = $?.exitstatus
      if (http_status != "200" || exit_status != 0)
        message = "failed to download #{path}, http status #{http_status}, exit_status #{exit_status}"
        if optional
          logger.warn message
          return
        end
        error(message)
      end
      FileUtils.mv @tmpfile, path
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dply-0.3.2 lib/dply/meta_config.rb