Sha256: 73520c3ff995c89ce760aeb333330a0fd5791b36abb351aabe47f6d6f1f2a4fa

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

require 'magic_reveal'
require 'net/https'
require 'archive/zip'
require 'pathname'
require 'fileutils'

module MagicReveal
  # Fetchs a github zip file and unpacks it for use.
  class Conductor
    attr_reader :url, :enable_warnings

    def initialize(url = nil)
      self.url = url unless url.nil?
    end

    def url=(url)
      @url = URI.parse url
    end

    def fetch(save_path, limit = 5) # rubocop:disable MethodLength
      fail TooManyRedirects if limit <= 0
      save_path = Pathname.new save_path

      request = Net::HTTP::Get.new url.path
      response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') { |http| http.request(request)  }

      case response
      when Net::HTTPSuccess then
        save_path.open('w') { |fp| fp.write response.body }
      when Net::HTTPRedirection then
        self.url = response['location']
        warn "redirected to #{url}" if enable_warnings
        fetch(save_path, limit - 1)
      else
        fail Error, "Huh? #{response.value}"
      end
    end

    def unpack(zip_file, directory)
      directory = Pathname.new directory
      fail Error, "Directory '#{directory}' already exists." if directory.exist?

      Archive::Zip.extract zip_file.to_s, directory.to_s

      # Unwrap the outer-most unzipped directory.
      wrapper_dir = directory.children.first
      wrapper_dir.children.each { |c| c.rename(directory + c.basename)  }
      wrapper_dir.rmdir
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
magic_reveal-2.6.1.4 lib/magic_reveal/conductor.rb