summaryrefslogtreecommitdiff
path: root/lib/gitlab/github_import/clients/search_repos.rb
blob: bcd226087e7a740861d26e53811dc0928e3cf479 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
# frozen_string_literal: true

module Gitlab
  module GithubImport
    module Clients
      module SearchRepos
        def search_repos_by_name_graphql(name, options = {})
          with_retry do
            octokit.post(
              '/graphql',
              { query: graphql_search_repos_body(name, options) }.to_json
            ).to_h
          end
        end

        def search_repos_by_name(name, options = {})
          with_retry do
            octokit.search_repositories(
              search_repos_query(str: name, type: :name),
              options
            ).to_h
          end
        end

        private

        def graphql_search_repos_body(name, options)
          query = search_repos_query(str: name, type: :name)
          query = "query: \"#{query}\""
          first = options[:first].present? ? ", first: #{options[:first]}" : ''
          after = options[:after].present? ? ", after: \"#{options[:after]}\"" : ''
          <<-TEXT
          {
              search(type: REPOSITORY, #{query}#{first}#{after}) {
                  nodes {
                      __typename
                      ... on Repository {
                          id: databaseId
                          name
                          full_name: nameWithOwner
                          owner { login }
                      }
                  }
                  pageInfo {
                      startCursor
                      endCursor
                      hasNextPage
                      hasPreviousPage
                  }
              }
          }
          TEXT
        end

        def search_repos_query(str:, type:, include_collaborations: true, include_orgs: true)
          query = "#{str} in:#{type} is:public,private user:#{octokit.user.to_h[:login]}"

          query = [query, collaborations_subquery].join(' ') if include_collaborations
          query = [query, organizations_subquery].join(' ') if include_orgs

          query
        end
      end
    end
  end
end