client.rb 1.92 KB
Newer Older
1 2 3
require 'faraday'
require 'faraday_middleware'

4
module ContainerRegistry
5 6 7 8 9 10 11
  class Client
    attr_accessor :uri

    MANIFEST_VERSION = 'application/vnd.docker.distribution.manifest.v2+json'

    def initialize(base_uri, options = {})
      @base_uri = base_uri
Kamil Trzcinski's avatar
Kamil Trzcinski committed
12 13
      @faraday = Faraday.new(@base_uri) do |conn|
        initialize_connection(conn)
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
      end
    end

    def repository_tags(name)
      @faraday.get("/v2/#{name}/tags/list").body
    end

    def repository_manifest(name, reference)
      @faraday.get("/v2/#{name}/manifests/#{reference}").body
    end

    def put_repository_manifest(name, reference, manifest)
      @faraday.put("/v2/#{name}/manifests/#{reference}", manifest, { "Content-Type" => MANIFEST_VERSION }).success?
    end

    def repository_mount_blob(name, digest, from)
30
      @faraday.post("/v2/#{name}/blobs/uploads/?mount=#{digest}&from=#{from}").status == 201
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    end

    def repository_tag_digest(name, reference)
      response = @faraday.head("/v2/#{name}/manifests/#{reference}")
      response.headers['docker-content-digest'] if response.success?
    end

    def delete_repository_tag(name, reference)
      @faraday.delete("/v2/#{name}/manifests/#{reference}").success?
    end

    def blob(name, digest, type = nil)
      headers = {}
      headers['Accept'] = type if type
      @faraday.get("/v2/#{name}/blobs/#{digest}", nil, headers).body
    end

    def delete_blob(name, digest)
      @faraday.delete("/v2/#{name}/blobs/#{digest}").success?
    end
Kamil Trzcinski's avatar
Kamil Trzcinski committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    
    private
    
    def initialize_connection(conn)
      conn.request :json
      conn.headers['Accept'] = MANIFEST_VERSION

      conn.response :json, :content_type => /\bjson$/

      if options[:user] && options[:password]
        conn.request(:basic_auth, options[:user].to_s, options[:password].to_s)
      elsif options[:token]
        conn.request(:authorization, :bearer, options[:token].to_s)
      end

      conn.adapter :net_http
    end
68 69
  end
end