BigW Consortium Gitlab

client.rb 2.02 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
module Gitlab
  module GitlabImport
    class Client
      attr_reader :client, :api

      PER_PAGE = 100

      def initialize(access_token)
        @client = ::OAuth2::Client.new(
          config.app_id,
          config.app_secret,
Douwe Maan committed
12
          gitlab_options
13 14 15
        )

        if access_token
16
          @api = OAuth2::AccessToken.from_hash(@client, access_token: access_token)
17 18 19 20 21 22 23 24 25 26 27 28 29 30
        end
      end

      def authorize_url(redirect_uri)
        client.auth_code.authorize_url({
          redirect_uri: redirect_uri,
          scope: "api"
        })
      end

      def get_token(code, redirect_uri)
        client.auth_code.get_token(code, redirect_uri: redirect_uri).token
      end

31 32 33 34
      def user
        api.get("/api/v3/user").parsed
      end

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
      def issues(project_identifier)
        lazy_page_iterator(PER_PAGE) do |page|
          api.get("/api/v3/projects/#{project_identifier}/issues?per_page=#{PER_PAGE}&page=#{page}").parsed
        end
      end

      def issue_comments(project_identifier, issue_id)
        lazy_page_iterator(PER_PAGE) do |page|
          api.get("/api/v3/projects/#{project_identifier}/issues/#{issue_id}/notes?per_page=#{PER_PAGE}&page=#{page}").parsed
        end
      end

      def project(id)
        api.get("/api/v3/projects/#{id}").parsed
      end

      def projects
        lazy_page_iterator(PER_PAGE) do |page|
          api.get("/api/v3/projects?per_page=#{PER_PAGE}&page=#{page}").parsed
        end
      end

      private

      def lazy_page_iterator(per_page)
        Enumerator.new do |y|
          page = 1
          loop do
            items = yield(page)
            items.each do |item|
              y << item
            end
            break if items.empty? || items.size < per_page
            page += 1
          end
        end
      end

      def config
74
        Gitlab.config.omniauth.providers.find{|provider| provider.name == "gitlab"}
75 76
      end

Douwe Maan committed
77
      def gitlab_options
Valery Sizov committed
78
        OmniAuth::Strategies::GitLab.default_options[:client_options].to_h.symbolize_keys
79 80 81 82
      end
    end
  end
end