Module: GitHub Private

Extended by:
T::Sig
Defined in:
utils/github.rb,
utils/github/api.rb,
utils/github/actions.rb

Overview

This module is part of a private API. This module may only be used in the Homebrew/brew repository. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Wrapper functions for the GitHub API.

Defined Under Namespace

Modules: API, Actions

Constant Summary collapse

API_URL =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

"https://api.github.com"
API_MAX_PAGES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

50
API_MAX_ITEMS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

5000
CREATE_GIST_SCOPES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

["gist"].freeze
CREATE_ISSUE_FORK_OR_PR_SCOPES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

["public_repo"].freeze
CREATE_WORKFLOW_SCOPES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

["workflow"].freeze
ALL_SCOPES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

(CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES + CREATE_WORKFLOW_SCOPES).freeze
ALL_SCOPES_URL =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

Formatter.url(
  "https://github.com/settings/tokens/new?scopes=#{ALL_SCOPES.join(",")}&description=Homebrew",
).freeze
CREATE_GITHUB_PAT_MESSAGE =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

<<~EOS
  Create a GitHub personal access token:
      #{ALL_SCOPES_URL}
    #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")}
EOS
GITHUB_PERSONAL_ACCESS_TOKEN_REGEX =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

/^(?:[a-f0-9]{40}|ghp_\w{36,251})$/.freeze

Class Method Summary collapse

Class Method Details

.approved_reviews(user, repo, pr, commit: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'utils/github.rb', line 169

def approved_reviews(user, repo, pr, commit: nil)
  query = <<~EOS
    { repository(name: "#{repo}", owner: "#{user}") {
        pullRequest(number: #{pr}) {
          reviews(states: APPROVED, first: 100) {
            nodes {
              author {
                ... on User { email login name databaseId }
                ... on Organization { email login name databaseId }
              }
              authorAssociation
              commit { oid }
            }
          }
        }
      }
    }
  EOS

  result = API.open_graphql(query, scopes: ["user:email"])
  reviews = result["repository"]["pullRequest"]["reviews"]["nodes"]

  valid_associations = %w[MEMBER OWNER]
  reviews.map do |r|
    next if commit.present? && commit != r["commit"]["oid"]
    next unless valid_associations.include? r["authorAssociation"]

    email = r["author"]["email"].presence ||
            "#{r["author"]["databaseId"]}+#{r["author"]["login"]}@users.noreply.github.com"

    name = r["author"]["name"].presence ||
           r["author"]["login"]

    {
      "email" => email,
      "name"  => name,
      "login" => r["author"]["login"],
    }
  end.compact
end

.check_for_duplicate_pull_requests(name, tap_remote_repo, state:, file:, args:, version: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'utils/github.rb', line 430

def check_for_duplicate_pull_requests(name, tap_remote_repo, state:, file:, args:, version: nil)
  pull_requests = fetch_pull_requests(name, tap_remote_repo, state: state, version: version).select do |pr|
    pr_files = API.open_rest(url_to("repos", tap_remote_repo, "pulls", pr["number"], "files"))
    pr_files.any? { |f| f["filename"] == file }
  end
  return if pull_requests.blank?

  duplicates_message = <<~EOS
    These pull requests may be duplicates:
    #{pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n")}
  EOS
  error_message = "Duplicate PRs should not be opened. Use --force to override this error."
  if args.force? && !args.quiet?
    opoo duplicates_message
  elsif !args.force? && args.quiet?
    odie error_message
  elsif !args.force?
    odie <<~EOS
      #{duplicates_message.chomp}
      #{error_message}
    EOS
  end
end

.check_fork_exists(repo, org: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



126
127
128
129
130
131
132
133
134
135
# File 'utils/github.rb', line 126

def check_fork_exists(repo, org: nil)
  _, reponame = repo.split("/")

  username = org || API.open_rest(url_to("user")) { |json| json["login"] }
  json = API.open_rest(url_to("repos", username, reponame))

  return false if json["message"] == "Not Found"

  true
end

.check_runs(repo: nil, commit: nil, pr: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



22
23
24
25
26
27
28
29
# File 'utils/github.rb', line 22

def check_runs(repo: nil, commit: nil, pr: nil)
  if pr
    repo = pr.fetch("base").fetch("repo").fetch("full_name")
    commit = pr.fetch("head").fetch("sha")
  end

  API.open_rest(url_to("repos", repo, "commits", commit, "check-runs"))
end

.create_bump_pr(info, args:) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'utils/github.rb', line 471

def create_bump_pr(info, args:)
  tap = info[:tap]
  sourcefile_path = info[:sourcefile_path]
  old_contents = info[:old_contents]
  additional_files = info[:additional_files] || []
  remote = info[:remote] || "origin"
  remote_branch = info[:remote_branch] || tap.path.git_origin_branch
  branch = info[:branch_name]
  commit_message = info[:commit_message]
  previous_branch = info[:previous_branch] || "-"
  tap_remote_repo = info[:tap_remote_repo] || tap.full_name
  pr_message = info[:pr_message]

  sourcefile_path.parent.cd do
    git_dir = Utils.popen_read("git", "rev-parse", "--git-dir").chomp
    shallow = !git_dir.empty? && File.exist?("#{git_dir}/shallow")
    changed_files = [sourcefile_path]
    changed_files += additional_files if additional_files.present?

    if args.dry_run? || (args.write? && !args.commit?)
      unless args.no_fork?
        fork_message = "try to fork repository with GitHub API" \
                       "#{" into `#{args.fork_org}` organization" if args.fork_org}"
        ohai fork_message
      end
      ohai "git fetch --unshallow origin" if shallow
      ohai "git add #{changed_files.join(" ")}"
      ohai "git checkout --no-track -b #{branch} #{remote}/#{remote_branch}"
      ohai "git commit --no-edit --verbose --message='#{commit_message}'" \
           " -- #{changed_files.join(" ")}"
      ohai "git push --set-upstream $HUB_REMOTE #{branch}:#{branch}"
      ohai "git checkout --quiet #{previous_branch}"
      ohai "create pull request with GitHub API (base branch: #{remote_branch})"
    else

      unless args.commit?
        if args.no_fork?
          remote_url = Utils.popen_read("git", "remote", "get-url", "--push", "origin").chomp
          username = tap.user
        else
          begin
            remote_url, username = forked_repo_info!(tap_remote_repo, org: args.fork_org)
          rescue *API::ERRORS => e
            sourcefile_path.atomic_write(old_contents)
            odie "Unable to fork: #{e.message}!"
          end
        end

        safe_system "git", "fetch", "--unshallow", "origin" if shallow
      end

      safe_system "git", "add", *changed_files
      safe_system "git", "checkout", "--no-track", "-b", branch, "#{remote}/#{remote_branch}" unless args.commit?
      safe_system "git", "commit", "--no-edit", "--verbose",
                  "--message=#{commit_message}",
                  "--", *changed_files
      return if args.commit?

      safe_system "git", "push", "--set-upstream", remote_url, "#{branch}:#{branch}"
      safe_system "git", "checkout", "--quiet", previous_branch
      pr_message = <<~EOS
        #{pr_message}
      EOS
      user_message = args.message
      if user_message
        pr_message = <<~EOS
          #{user_message}

          ---

          #{pr_message}
        EOS
      end

      begin
        url = create_pull_request(tap_remote_repo, commit_message,
                                  "#{username}:#{branch}", remote_branch, pr_message)["html_url"]
        if args.no_browse?
          puts url
        else
          exec_browser url
        end
      rescue *API::ERRORS => e
        odie "Unable to open pull request: #{e.message}!"
      end
    end
  end
end

.create_check_run(repo:, data:) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



31
32
33
# File 'utils/github.rb', line 31

def create_check_run(repo:, data:)
  API.open_rest(url_to("repos", repo, "check-runs"), data: data)
end

.create_fork(repo, org: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



118
119
120
121
122
123
124
# File 'utils/github.rb', line 118

def create_fork(repo, org: nil)
  url = "#{API_URL}/repos/#{repo}/forks"
  data = {}
  data[:organization] = org if org
  scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
  API.open_rest(url, data: data, scopes: scopes)
end

.create_gist(files, description, private:) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



39
40
41
42
43
# File 'utils/github.rb', line 39

def create_gist(files, description, private:)
  url = "https://api.github.com/gists"
  data = { "public" => !private, "files" => files, "description" => description }
  API.open_rest(url, data: data, scopes: CREATE_GIST_SCOPES)["html_url"]
end

.create_issue(repo, title, body) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



45
46
47
48
49
# File 'utils/github.rb', line 45

def create_issue(repo, title, body)
  url = "https://api.github.com/repos/#{repo}/issues"
  data = { "title" => title, "body" => body }
  API.open_rest(url, data: data, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)["html_url"]
end

.create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'utils/github.rb', line 234

def create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false)
  url = "#{API_URL}/repos/#{user}/#{repo}/releases"
  method = if id
    url += "/#{id}"
    :PATCH
  else
    :POST
  end
  data = {
    tag_name: tag,
    name:     name || tag,
    draft:    draft,
  }
  data[:body] = body if body.present?
  API.open_rest(url, data: data, request_method: method, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end

.create_pull_request(repo, title, head, base, body) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



137
138
139
140
141
142
# File 'utils/github.rb', line 137

def create_pull_request(repo, title, head, base, body)
  url = "#{API_URL}/repos/#{repo}/pulls"
  data = { title: title, head: head, base: base, body: body }
  scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
  API.open_rest(url, data: data, scopes: scopes)
end

.dispatch_event(user, repo, event, **payload) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



210
211
212
213
214
215
# File 'utils/github.rb', line 210

def dispatch_event(user, repo, event, **payload)
  url = "#{API_URL}/repos/#{user}/#{repo}/dispatches"
  API.open_rest(url, data:           { event_type: event, client_payload: payload },
                     request_method: :POST,
                     scopes:         CREATE_ISSUE_FORK_OR_PR_SCOPES)
end

.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'utils/github.rb', line 414

def fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil)
  if version.present?
    query = "#{name} #{version}"
    regex = /(^|\s)#{Regexp.quote(name)}(:|,|\s)(.*\s)?#{Regexp.quote(version)}(:|,|\s|$)/i
  else
    query = name
    regex = /(^|\s)#{Regexp.quote(name)}(:|,|\s|$)/i
  end
  issues_for_formula(query, tap_remote_repo: tap_remote_repo, state: state).select do |pr|
    pr["html_url"].include?("/pull/") && regex.match?(pr["title"])
  end
rescue API::RateLimitExceededError => e
  opoo e.message
  []
end

.forked_repo_info!(tap_remote_repo, org: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'utils/github.rb', line 454

def forked_repo_info!(tap_remote_repo, org: nil)
  response = create_fork(tap_remote_repo, org: org)
  # GitHub API responds immediately but fork takes a few seconds to be ready.
  sleep 1 until check_fork_exists(tap_remote_repo, org: org)
  remote_url = if system("git", "config", "--local", "--get-regexp", "remote\..*\.url", "git@github.com:.*")
    response.fetch("ssh_url")
  else
    url = response.fetch("clone_url")
    if (api_token = Homebrew::EnvConfig.github_api_token)
      url.gsub!(%r{^https://github\.com/}, "https://#{api_token}@github.com/")
    end
    url
  end
  username = response.fetch("owner").fetch("login")
  [remote_url, username]
end

.get_artifact_url(workflow_array) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'utils/github.rb', line 273

def get_artifact_url(workflow_array)
  workflow_run, pr_sha, pr_branch, pr, workflow_id, scopes, artifact_name = *workflow_array
  if workflow_run.empty?
    raise API::Error, <<~EOS
      No matching workflow run found for these criteria!
        Commit SHA:   #{pr_sha}
        Branch ref:   #{pr_branch}
        Pull request: #{pr}
        Workflow:     #{workflow_id}
    EOS
  end

  status = workflow_run.first["status"].sub("_", " ")
  if status != "completed"
    raise API::Error, <<~EOS
      The newest workflow run for ##{pr} is still #{status}!
        #{Formatter.url workflow_run.first["html_url"]}
    EOS
  end

  artifacts = API.open_rest(workflow_run.first["artifacts_url"], scopes: scopes)

  artifact = artifacts["artifacts"].select do |art|
    art["name"] == artifact_name
  end

  if artifact.empty?
    raise API::Error, <<~EOS
      No artifact with the name `#{artifact_name}` was found!
        #{Formatter.url workflow_run.first["html_url"]}
    EOS
  end

  artifact.first["archive_download_url"]
end

.get_latest_release(user, repo) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



229
230
231
232
# File 'utils/github.rb', line 229

def get_latest_release(user, repo)
  url = "#{API_URL}/repos/#{user}/#{repo}/releases/latest"
  API.open_rest(url, request_method: :GET)
end

.get_release(user, repo, tag) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



224
225
226
227
# File 'utils/github.rb', line 224

def get_release(user, repo, tag)
  url = "#{API_URL}/repos/#{user}/#{repo}/releases/tags/#{tag}"
  API.open_rest(url, request_method: :GET)
end

.get_repo_license(user, repo) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



405
406
407
408
409
410
411
412
# File 'utils/github.rb', line 405

def get_repo_license(user, repo)
  response = API.open_rest("#{API_URL}/repos/#{user}/#{repo}/license")
  return unless response.key?("license")

  response["license"]["spdx_id"]
rescue API::HTTPNotFoundError
  nil
end

.get_workflow_run(user, repo, pr, workflow_id: "tests.yml", artifact_name: "bottles") ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'utils/github.rb', line 257

def get_workflow_run(user, repo, pr, workflow_id: "tests.yml", artifact_name: "bottles")
  scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
  base_url = "#{API_URL}/repos/#{user}/#{repo}"
  pr_payload = API.open_rest("#{base_url}/pulls/#{pr}", scopes: scopes)
  pr_sha = pr_payload["head"]["sha"]
  pr_branch = URI.encode_www_form_component(pr_payload["head"]["ref"])
  parameters = "event=pull_request&branch=#{pr_branch}"

  workflow = API.open_rest("#{base_url}/actions/workflows/#{workflow_id}/runs?#{parameters}", scopes: scopes)
  workflow_run = workflow["workflow_runs"].select do |run|
    run["head_sha"] == pr_sha
  end

  [workflow_run, pr_sha, pr_branch, pr, workflow_id, scopes, artifact_name]
end

.issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap.full_name, state: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



66
67
68
# File 'utils/github.rb', line 66

def issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap.full_name, state: nil)
  search_issues(name, repo: tap_remote_repo, state: state, in: "title")
end

.members_by_team(org, team) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Raises:



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'utils/github.rb', line 321

def members_by_team(org, team)
  query = <<~EOS
      { organization(login: "#{org}") {
        teams(first: 100) {
          nodes {
            ... on Team { name }
          }
        }
        team(slug: "#{team}") {
          members(first: 100) {
            nodes {
              ... on User { login name }
            }
          }
        }
      }
    }
  EOS
  result = API.open_graphql(query, scopes: ["read:org", "user"])

  if result["organization"]["teams"]["nodes"].blank?
    raise API::Error,
          "Your token needs the 'read:org' scope to access this API"
  end
  raise API::Error, "The team #{org}/#{team} does not exist" if result["organization"]["team"].blank?

  result["organization"]["team"]["members"]["nodes"].map { |member| [member["login"], member["name"]] }.to_h
end

.merge_pull_request(repo, number:, sha:, merge_method:, commit_message: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



88
89
90
91
92
93
# File 'utils/github.rb', line 88

def merge_pull_request(repo, number:, sha:, merge_method:, commit_message: nil)
  url = "#{API_URL}/repos/#{repo}/pulls/#{number}/merge"
  data = { sha: sha, merge_method: merge_method }
  data[:commit_message] = commit_message if commit_message
  API.open_rest(url, data: data, request_method: :PUT, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end

.open_api(url, data: nil, data_binary_path: nil, request_method: nil, scopes: [].freeze, parse_json: true) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



16
17
18
19
20
# File 'utils/github.rb', line 16

def open_api(url, data: nil, data_binary_path: nil, request_method: nil, scopes: [].freeze, parse_json: true)
  odisabled "GitHub.open_api", "GitHub::API.open_rest"
  API.open_rest(url, data: data, data_binary_path: data_binary_path, request_method: request_method,
                scopes: scopes, parse_json: parse_json)
end

.permission(repo, user) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



74
75
76
# File 'utils/github.rb', line 74

def permission(repo, user)
  API.open_rest("#{API_URL}/repos/#{repo}/collaborators/#{user}/permission")
end

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'utils/github.rb', line 95

def print_pull_requests_matching(query, only = nil)
  open_or_closed_prs = search_issues(query, is: only, type: "pr", user: "Homebrew")

  open_prs, closed_prs = open_or_closed_prs.partition { |pr| pr["state"] == "open" }
                                           .map { |prs| prs.map { |pr| "#{pr["title"]} (#{pr["html_url"]})" } }

  if open_prs.present?
    ohai "Open pull requests"
    open_prs.each { |pr| puts pr }
  end

  if closed_prs.present?
    puts if open_prs.present?

    ohai "Closed pull requests"
    closed_prs.take(20).each { |pr| puts pr }

    puts "..." if closed_prs.count > 20
  end

  puts "No pull requests found for #{query.inspect}" if open_prs.blank? && closed_prs.blank?
end

.private_repo?(full_name) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


144
145
146
147
# File 'utils/github.rb', line 144

def private_repo?(full_name)
  uri = url_to "repos", full_name
  API.open_rest(uri) { |json| json["private"] }
end

.public_member_usernames(org, per_page: 100) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



309
310
311
312
313
314
315
316
317
318
319
# File 'utils/github.rb', line 309

def public_member_usernames(org, per_page: 100)
  url = "#{API_URL}/orgs/#{org}/public_members"
  members = []

  API.paginate_rest(url, per_page: per_page) do |result|
    result = result.map { |member| member["login"] }
    members.concat(result)

    return members if result.length < per_page
  end
end

.pull_request_commits(user, repo, pr, per_page: 100) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'utils/github.rb', line 560

def pull_request_commits(user, repo, pr, per_page: 100)
  pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pr))
  commits_api = pr_data["commits_url"]
  commit_count = pr_data["commits"]
  commits = []

  if commit_count > API_MAX_ITEMS
    raise API::Error, "Getting #{commit_count} commits would exceed limit of #{API_MAX_ITEMS} API items!"
  end

  API.paginate_rest(commits_api, per_page: per_page) do |result, page|
    commits.concat(result.map { |c| c["sha"] })

    return commits if commits.length == commit_count

    if result.empty? || page * per_page >= commit_count
      raise API::Error, "Expected #{commit_count} commits but actually got #{commits.length}!"
    end
  end
end

.pull_request_labels(user, repo, pr) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



581
582
583
584
# File 'utils/github.rb', line 581

def pull_request_labels(user, repo, pr)
  pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pr))
  pr_data["labels"].map { |label| label["name"] }
end

.pull_requests(repo, **options) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



83
84
85
86
# File 'utils/github.rb', line 83

def pull_requests(repo, **options)
  url = "#{API_URL}/repos/#{repo}/pulls?#{URI.encode_www_form(options)}"
  API.open_rest(url)
end

.query_string(*main_params, **qualifiers) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



149
150
151
152
153
154
155
156
157
# File 'utils/github.rb', line 149

def query_string(*main_params, **qualifiers)
  params = main_params

  params += qualifiers.flat_map do |key, value|
    Array(value).map { |v| "#{key}:#{v}" }
  end

  "q=#{URI.encode_www_form_component(params.join(" "))}&per_page=100"
end

.repository(user, repo) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



51
52
53
# File 'utils/github.rb', line 51

def repository(user, repo)
  API.open_rest(url_to("repos", user, repo))
end

.search(entity, *queries, **qualifiers) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



163
164
165
166
167
# File 'utils/github.rb', line 163

def search(entity, *queries, **qualifiers)
  uri = url_to "search", entity
  uri.query = query_string(*queries, **qualifiers)
  API.open_rest(uri) { |json| json.fetch("items", []) }
end

.search_code(repo: nil, user: "Homebrew", path: ["Formula", "Casks", "."], filename: nil, extension: "rb") ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



55
56
57
58
59
60
61
62
63
64
# File 'utils/github.rb', line 55

def search_code(repo: nil, user: "Homebrew", path: ["Formula", "Casks", "."], filename: nil, extension: "rb")
  matches = search("code", user: user, path: path, filename: filename, extension: extension, repo: repo)
  return matches if matches.blank?

  matches.map do |match|
    # .sub workaround for GitHub returning preceding /
    match["path"] = match["path"].delete_prefix("/")
    match
  end
end

.search_issues(query, **qualifiers) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



35
36
37
# File 'utils/github.rb', line 35

def search_issues(query, **qualifiers)
  search("issues", query, **qualifiers)
end

.sponsors_by_tier(user) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'utils/github.rb', line 350

def sponsors_by_tier(user)
  query = <<~EOS
      { organization(login: "#{user}") {
        sponsorsListing {
          tiers(first: 10, orderBy: {field: MONTHLY_PRICE_IN_CENTS, direction: DESC}) {
            nodes {
              monthlyPriceInDollars
              adminInfo {
                sponsorships(first: 100, includePrivate: true) {
                  totalCount
                  nodes {
                    privacyLevel
                    sponsorEntity {
                      __typename
                      ... on Organization { login name }
                      ... on User { login name }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  EOS
  result = API.open_graphql(query, scopes: ["admin:org", "user"])

  tiers = result["organization"]["sponsorsListing"]["tiers"]["nodes"]

  tiers.map do |t|
    tier = t["monthlyPriceInDollars"]
    raise API::Error, "Your token needs the 'admin:org' scope to access this API" if t["adminInfo"].nil?

    sponsorships = t["adminInfo"]["sponsorships"]
    count = sponsorships["totalCount"]
    sponsors = sponsorships["nodes"].map do |sponsor|
      next unless sponsor["privacyLevel"] == "PUBLIC"

      se = sponsor["sponsorEntity"]
      {
        "name"  => se["name"].presence || sponsor["login"],
        "login" => se["login"],
        "type"  => se["__typename"].downcase,
      }
    end.compact

    {
      "tier"     => tier,
      "count"    => count,
      "sponsors" => sponsors,
    }
  end.compact
end

.upload_release_asset(user, repo, id, local_file: nil, remote_file: nil) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



251
252
253
254
255
# File 'utils/github.rb', line 251

def upload_release_asset(user, repo, id, local_file: nil, remote_file: nil)
  url = "https://uploads.github.com/repos/#{user}/#{repo}/releases/#{id}/assets"
  url += "?name=#{remote_file}" if remote_file
  API.open_rest(url, data_binary_path: local_file, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end

.url_to(*subroutes) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



159
160
161
# File 'utils/github.rb', line 159

def url_to(*subroutes)
  URI.parse([API_URL, *subroutes].join("/"))
end

.userObject

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



70
71
72
# File 'utils/github.rb', line 70

def user
  @user ||= API.open_rest("#{API_URL}/user")
end

.workflow_dispatch_event(user, repo, workflow, ref, **inputs) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



217
218
219
220
221
222
# File 'utils/github.rb', line 217

def workflow_dispatch_event(user, repo, workflow, ref, **inputs)
  url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow}/dispatches"
  API.open_rest(url, data:           { ref: ref, inputs: inputs },
                     request_method: :POST,
                     scopes:         CREATE_ISSUE_FORK_OR_PR_SCOPES)
end

.write_access?(repo, user = nil) ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


78
79
80
81
# File 'utils/github.rb', line 78

def write_access?(repo, user = nil)
  user ||= self.user["login"]
  ["admin", "write"].include?(permission(repo, user)["permission"])
end