Module: GitHub Private

Defined in:
brew/Library/Homebrew/utils/github.rb,
brew/Library/Homebrew/utils/github/actions.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Helper functions for interacting with the GitHub API.

Defined Under Namespace

Modules: Actions Classes: AuthenticationFailedError, Error, HTTPNotFoundError, RateLimitExceededError, ValidationFailedError

Constant Summary collapse

API_URL =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

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

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

["gist"].freeze
CREATE_ISSUE_FORK_OR_PR_SCOPES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

["public_repo"].freeze
ALL_SCOPES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES).freeze
ALL_SCOPES_URL =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

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

Class Method Summary collapse

Class Method Details

.api_credentialsObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



121
122
123
124
125
# File 'brew/Library/Homebrew/utils/github.rb', line 121

def api_credentials
  @api_credentials ||= begin
    Homebrew::EnvConfig.github_api_token || env_username_password || keychain_username_password
  end
end

.api_credentials_error_message(response_headers, needed_scopes) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'brew/Library/Homebrew/utils/github.rb', line 139

def api_credentials_error_message(response_headers, needed_scopes)
  return if response_headers.empty?

  @api_credentials_error_message ||= begin
    unauthorized = (response_headers["http/1.1"] == "401 Unauthorized")
    scopes = response_headers["x-accepted-oauth-scopes"].to_s.split(", ")
    if unauthorized && scopes.blank?
      needed_human_scopes = needed_scopes.join(", ")
      credentials_scopes = response_headers["x-oauth-scopes"]
      return if needed_human_scopes.blank? && credentials_scopes.blank?

      needed_human_scopes = "none" if needed_human_scopes.blank?
      credentials_scopes = "none" if credentials_scopes.blank?

      case GitHub.api_credentials_type
      when :keychain_username_password
        onoe <<~EOS
          Your macOS keychain GitHub credentials do not have sufficient scope!
          Scopes they need: #{needed_human_scopes}
          Scopes they have: #{credentials_scopes}
          Create a personal access token:
            #{ALL_SCOPES_URL}
          #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")}
        EOS
      when :env_token
        onoe <<~EOS
          Your HOMEBREW_GITHUB_API_TOKEN does not have sufficient scope!
          Scopes it needs: #{needed_human_scopes}
            Scopes it has: #{credentials_scopes}
          Create a new personal access token:
            #{ALL_SCOPES_URL}
          #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")}
        EOS
      end
    end
    true
  end
end

.api_credentials_typeObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



127
128
129
130
131
132
133
134
135
136
137
# File 'brew/Library/Homebrew/utils/github.rb', line 127

def api_credentials_type
  if Homebrew::EnvConfig.github_api_token
    :env_token
  elsif env_username_password
    :env_username_password
  elsif keychain_username_password
    :keychain_username_password
  else
    :none
  end
end

.api_errorsObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



614
615
616
617
# File 'brew/Library/Homebrew/utils/github.rb', line 614

def api_errors
  [GitHub::AuthenticationFailedError, GitHub::HTTPNotFoundError,
   GitHub::RateLimitExceededError, GitHub::Error, JSON::ParserError].freeze
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'brew/Library/Homebrew/utils/github.rb', line 419

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 = 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 = if r["author"]["email"].blank?
      "#{r["author"]["databaseId"]}+#{r["author"]["login"]}@users.noreply.github.com"
    else
      r["author"]["email"]
    end

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

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

.check_for_duplicate_pull_requests(query, tap_full_name, state:, args:) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'brew/Library/Homebrew/utils/github.rb', line 629

def check_for_duplicate_pull_requests(query, tap_full_name, state:, args:)
  pull_requests = fetch_pull_requests(query, tap_full_name, state: state)
  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) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'brew/Library/Homebrew/utils/github.rb', line 371

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

  case api_credentials_type
  when :env_username_password, :keychain_username_password
    _, username = api_credentials
  when :env_token
    username = open_api(url_to("user")) { |json| json["login"] }
  end
  json = open_api(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. You should avoid using this method if possible, as it may be removed or be changed in the future.



295
296
297
298
299
300
301
302
# File 'brew/Library/Homebrew/utils/github.rb', line 295

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

  open_api(url_to("repos", repo, "commits", commit, "check-runs"))
end

.create_bump_pr(info, args:) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'brew/Library/Homebrew/utils/github.rb', line 667

def create_bump_pr(info, args:)
  sourcefile_path = info[:sourcefile_path]
  old_contents = info[:old_contents]
  additional_files = info[:additional_files] || []
  origin_branch = info[:origin_branch]
  branch = info[:branch_name]
  commit_message = info[:commit_message]
  previous_branch = info[:previous_branch]
  tap = info[:tap]
  tap_full_name = info[:tap_full_name]
  pr_message = info[:pr_message]

  sourcefile_path.parent.cd do
    _, base_branch = origin_branch.split("/")
    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?)
      ohai "try to fork repository with GitHub API" unless args.no_fork?
      ohai "git fetch --unshallow origin" if shallow
      ohai "git add #{changed_files.join(" ")}"
      ohai "git checkout --no-track -b #{branch} #{origin_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: #{base_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 = GitHub.forked_repo_info!(tap_full_name)
          rescue *GitHub.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, origin_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}
        EOS
      end

      begin
        url = GitHub.create_pull_request(tap_full_name, commit_message,
                                         "#{username}:#{branch}", base_branch, pr_message)["html_url"]
        if args.no_browse?
          puts url
        else
          exec_browser url
        end
      rescue *GitHub.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. You should avoid using this method if possible, as it may be removed or be changed in the future.



304
305
306
# File 'brew/Library/Homebrew/utils/github.rb', line 304

def create_check_run(repo:, data:)
  open_api(url_to("repos", repo, "check-runs"), data: data)
end

.create_fork(repo) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



364
365
366
367
368
369
# File 'brew/Library/Homebrew/utils/github.rb', line 364

def create_fork(repo)
  url = "#{API_URL}/repos/#{repo}/forks"
  data = {}
  scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
  open_api(url, data: data, scopes: scopes)
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'brew/Library/Homebrew/utils/github.rb', line 481

def create_or_update_release(user, repo, tag, id: nil, name: 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,
  }
  open_api(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. You should avoid using this method if possible, as it may be removed or be changed in the future.



387
388
389
390
391
392
# File 'brew/Library/Homebrew/utils/github.rb', line 387

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
  open_api(url, data: data, scopes: scopes)
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



462
463
464
465
466
467
# File 'brew/Library/Homebrew/utils/github.rb', line 462

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

.env_username_passwordObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



90
91
92
93
94
95
# File 'brew/Library/Homebrew/utils/github.rb', line 90

def env_username_password
  return unless Homebrew::EnvConfig.github_api_username
  return unless Homebrew::EnvConfig.github_api_password

  [Homebrew::EnvConfig.github_api_password, Homebrew::EnvConfig.github_api_username]
end

.fetch_pull_requests(query, tap_full_name, state: nil) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



619
620
621
622
623
624
625
626
627
# File 'brew/Library/Homebrew/utils/github.rb', line 619

def fetch_pull_requests(query, tap_full_name, state: nil)
  GitHub.issues_for_formula(query, tap_full_name: tap_full_name, state: state).select do |pr|
    pr["html_url"].include?("/pull/") &&
      /(^|\s)#{Regexp.quote(query)}(:|\s|$)/i =~ pr["title"]
  end
rescue GitHub::RateLimitExceededError => e
  opoo e.message
  []
end

.forked_repo_info!(tap_full_name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'brew/Library/Homebrew/utils/github.rb', line 650

def forked_repo_info!(tap_full_name)
  response = GitHub.create_fork(tap_full_name)
  # GitHub API responds immediately but fork takes a few seconds to be ready.
  sleep 1 until GitHub.check_fork_exists(tap_full_name)
  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(user, repo, pr, workflow_id: "tests.yml", artifact_name: "bottles") ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



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
# File 'brew/Library/Homebrew/utils/github.rb', line 503

def get_artifact_url(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 = open_api("#{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 = open_api("#{base_url}/actions/workflows/#{workflow_id}/runs?#{parameters}", scopes: scopes)
  workflow_run = workflow["workflow_runs"].select do |run|
    run["head_sha"] == pr_sha
  end

  if workflow_run.empty?
    raise 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 Error, <<~EOS
      The newest workflow run for ##{pr} is still #{status}!
        #{Formatter.url workflow_run.first["html_url"]}
    EOS
  end

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

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

  if artifact.empty?
    raise 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_release(user, repo, tag) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



476
477
478
479
# File 'brew/Library/Homebrew/utils/github.rb', line 476

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

.get_repo_license(user, repo) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



605
606
607
608
609
610
611
612
# File 'brew/Library/Homebrew/utils/github.rb', line 605

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

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

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



320
321
322
# File 'brew/Library/Homebrew/utils/github.rb', line 320

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

.keychain_username_passwordObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'brew/Library/Homebrew/utils/github.rb', line 97

def keychain_username_password
  github_credentials = Utils.popen(["git", "credential-osxkeychain", "get"], "w+") do |pipe|
    pipe.write "protocol=https\nhost=github.com\n"
    pipe.close_write
    pipe.read
  end
  github_username = github_credentials[/username=(.+)/, 1]
  github_password = github_credentials[/password=(.+)/, 1]
  return unless github_username

  # Don't use passwords from the keychain unless they look like
  # GitHub Personal Access Tokens:
  #   https://github.com/Homebrew/brew/issues/6862#issuecomment-572610344
  return unless /^[a-f0-9]{40}$/i.match?(github_password)

  [github_password, github_username]
rescue Errno::EPIPE
  # The above invocation via `Utils.popen` can fail, causing the pipe to be
  # prematurely closed (before we can write to it) and thus resulting in a
  # broken pipe error. The root cause is usually a missing or malfunctioning
  # `git-credential-osxkeychain` helper.
  nil
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



342
343
344
345
346
347
# File 'brew/Library/Homebrew/utils/github.rb', line 342

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
  open_api(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. You should avoid using this method if possible, as it may be removed or be changed in the future.



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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'brew/Library/Homebrew/utils/github.rb', line 178

def open_api(url, data: nil, data_binary_path: nil, request_method: nil, scopes: [].freeze, parse_json: true)
  # This is a no-op if the user is opting out of using the GitHub API.
  return block_given? ? yield({}) : {} if Homebrew::EnvConfig.no_github_api?

  args = ["--header", "Accept: application/vnd.github.v3+json", "--write-out", "\n%\{http_code}"]
  args += ["--header", "Accept: application/vnd.github.antiope-preview+json"]

  token, username = api_credentials
  case api_credentials_type
  when :env_username_password, :keychain_username_password
    args += ["--user", "#{username}:#{token}"]
  when :env_token
    args += ["--header", "Authorization: token #{token}"]
  end

  data_tmpfile = nil
  if data
    begin
      data = JSON.generate data
      data_tmpfile = Tempfile.new("github_api_post", HOMEBREW_TEMP)
    rescue JSON::ParserError => e
      raise Error, "Failed to parse JSON request:\n#{e.message}\n#{data}", e.backtrace
    end
  end

  if data_binary_path.present?
    args += ["--data-binary", "@#{data_binary_path}"]
    args += ["--header", "Content-Type: application/gzip"]
  end

  headers_tmpfile = Tempfile.new("github_api_headers", HOMEBREW_TEMP)
  begin
    if data
      data_tmpfile.write data
      data_tmpfile.close
      args += ["--data", "@#{data_tmpfile.path}"]

      args += ["--request", request_method.to_s] if request_method
    end

    args += ["--dump-header", headers_tmpfile.path]

    output, errors, status = curl_output("--location", url.to_s, *args, secrets: [token])
    output, _, http_code = output.rpartition("\n")
    output, _, http_code = output.rpartition("\n") if http_code == "000"
    headers = headers_tmpfile.read
  ensure
    if data_tmpfile
      data_tmpfile.close
      data_tmpfile.unlink
    end
    headers_tmpfile.close
    headers_tmpfile.unlink
  end

  begin
    raise_api_error(output, errors, http_code, headers, scopes) if !http_code.start_with?("2") || !status.success?

    return if http_code == "204" # No Content

    output = JSON.parse output if parse_json
    if block_given?
      yield output
    else
      output
    end
  rescue JSON::ParserError => e
    raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
  end
end

.open_graphql(query, scopes: [].freeze) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Raises:



249
250
251
252
253
254
255
256
# File 'brew/Library/Homebrew/utils/github.rb', line 249

def open_graphql(query, scopes: [].freeze)
  data = { query: query }
  result = open_api("https://api.github.com/graphql", scopes: scopes, data: data, request_method: "POST")

  raise Error, result["errors"].map { |e| "#{e["type"]}: #{e["message"]}" }.join("\n") if result["errors"].present?

  result["data"]
end

.permission(repo, user) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



328
329
330
# File 'brew/Library/Homebrew/utils/github.rb', line 328

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'brew/Library/Homebrew/utils/github.rb', line 349

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

  open_prs = open_or_closed_prs.select { |i| i["state"] == "open" }
  prs = if !open_prs.empty?
    puts "Open pull requests:"
    open_prs
  else
    puts "Closed pull requests:" unless open_or_closed_prs.empty?
    open_or_closed_prs.take(20)
  end

  prs.each { |i| puts "#{i["title"]} (#{i["html_url"]})" }
end

.private_repo?(full_name) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)


394
395
396
397
# File 'brew/Library/Homebrew/utils/github.rb', line 394

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

.pull_request_commits(user, repo, pr) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



751
752
753
# File 'brew/Library/Homebrew/utils/github.rb', line 751

def pull_request_commits(user, repo, pr)
  open_api(url_to("repos", user, repo, "pulls", pr, "commits?per_page=100")).map { |c| c["sha"] }
end

.pull_requests(repo, **options) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



337
338
339
340
# File 'brew/Library/Homebrew/utils/github.rb', line 337

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

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



399
400
401
402
403
404
405
406
407
# File 'brew/Library/Homebrew/utils/github.rb', line 399

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

.raise_api_error(output, errors, http_code, headers, scopes) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'brew/Library/Homebrew/utils/github.rb', line 258

def raise_api_error(output, errors, http_code, headers, scopes)
  json = begin
    JSON.parse(output)
  rescue
    nil
  end
  message = json&.[]("message") || "curl failed! #{errors}"

  meta = {}
  headers.lines.each do |l|
    key, _, value = l.delete(":").partition(" ")
    key = key.downcase.strip
    next if key.empty?

    meta[key] = value.strip
  end

  if meta.fetch("x-ratelimit-remaining", 1).to_i <= 0
    reset = meta.fetch("x-ratelimit-reset").to_i
    raise RateLimitExceededError.new(reset, message)
  end

  GitHub.api_credentials_error_message(meta, scopes)

  case http_code
  when "401", "403"
    raise AuthenticationFailedError, message
  when "404"
    raise HTTPNotFoundError, message
  when "422"
    errors = json&.[]("errors") || []
    raise ValidationFailedError.new(message, errors)
  else
    raise Error, message
  end
end

.repository(user, repo) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



312
313
314
# File 'brew/Library/Homebrew/utils/github.rb', line 312

def repository(user, repo)
  open_api(url_to("repos", user, repo))
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



413
414
415
416
417
# File 'brew/Library/Homebrew/utils/github.rb', line 413

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

.search_code(**qualifiers) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



316
317
318
# File 'brew/Library/Homebrew/utils/github.rb', line 316

def search_code(**qualifiers)
  search("code", **qualifiers)
end

.search_issues(query, **qualifiers) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



308
309
310
# File 'brew/Library/Homebrew/utils/github.rb', line 308

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

.sponsors_by_tier(user) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'brew/Library/Homebrew/utils/github.rb', line 550

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 = open_graphql(query, scopes: ["admin:org", "user"])

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

  tiers.map do |t|
    tier = t["monthlyPriceInDollars"]
    raise 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. You should avoid using this method if possible, as it may be removed or be changed in the future.



497
498
499
500
501
# File 'brew/Library/Homebrew/utils/github.rb', line 497

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
  open_api(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. You should avoid using this method if possible, as it may be removed or be changed in the future.



409
410
411
# File 'brew/Library/Homebrew/utils/github.rb', line 409

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

.userObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



324
325
326
# File 'brew/Library/Homebrew/utils/github.rb', line 324

def user
  @user ||= open_api("#{API_URL}/user")
end

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

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



469
470
471
472
473
474
# File 'brew/Library/Homebrew/utils/github.rb', line 469

def workflow_dispatch_event(user, repo, workflow, ref, **inputs)
  url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow}/dispatches"
  open_api(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. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)


332
333
334
335
# File 'brew/Library/Homebrew/utils/github.rb', line 332

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