Module: GitHub Private

Extended by:
SystemCommand::Mixin, Utils::Output::Mixin
Defined in:
utils/github.rb,
utils/github/api.rb,
utils/github/actions.rb,
utils/github/artifacts.rb

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.

Defined Under Namespace

Modules: API, Actions

Constant Summary collapse

MAXIMUM_OPEN_PRS =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

15
API_URL =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let("https://api.github.com", String)
CREATE_GIST_SCOPES =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let(["gist"].freeze, T::Array[String])
CREATE_ISSUE_FORK_OR_PR_SCOPES =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let(["repo"].freeze, T::Array[String])
CREATE_WORKFLOW_SCOPES =

This constant is part of an internal API. This constant may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let(["workflow"].freeze, T::Array[String])

Class Method Summary collapse

Methods included from SystemCommand::Mixin

system_command, system_command!

Methods included from Utils::Output::Mixin

odebug, odeprecated, odie, odisabled, ofail, oh1, oh1_title, ohai, ohai_title, onoe, opoo, opoo_outside_github_actions, pretty_duration, pretty_installed, pretty_outdated, pretty_uninstalled

Class Method Details

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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
# File 'utils/github.rb', line 195

def self.approved_reviews(user, repo, pull_request, commit: nil)
  query = <<~EOS
    { repository(name: "#{repo}", owner: "#{user}") {
        pullRequest(number: #{pull_request}) {
          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.filter_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
end

.branch_exists?(user, repo, branch) ⇒ Boolean

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


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

def self.branch_exists?(user, repo, branch)
  API.open_rest("#{API_URL}/repos/#{user}/#{repo}/branches/#{branch}")
  true
rescue API::HTTPNotFoundError
  false
end

.check_for_duplicate_pull_requests(name, tap_remote_repo, file:, quiet: false, state: nil, version: nil, official_tap: true, strict: false) ⇒ void

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Check for duplicate pull requests that modify the same file.

Exits the process on duplicates if strict or both version and official_tap, otherwise warns.

Parameters:

  • name (String)
  • tap_remote_repo (String)
  • file (String)
  • quiet (Boolean) (defaults to: false)
  • state (String, nil) (defaults to: nil)
  • version (String, nil) (defaults to: nil)
  • official_tap (Boolean) (defaults to: true)
  • strict (Boolean) (defaults to: false)


651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'utils/github.rb', line 651

def self.check_for_duplicate_pull_requests(name, tap_remote_repo, file:, quiet: false, state: nil,
                                           version: nil, official_tap: true, strict: false)
  pull_requests = fetch_pull_requests(name, tap_remote_repo, state:, version:)

  pull_requests.select! do |pr|
    get_pull_request_changed_files(
      tap_remote_repo, pr["number"]
    ).any? { |f| f["filename"] == file }
  end
  return if pull_requests.blank?

  confidence = version ? "are" : "might be"
  duplicates_message = <<~EOS
    These #{state} pull requests #{confidence} duplicates:
    #{pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n")}
  EOS
  error_message = <<~EOS
    Duplicate PRs must not be opened.
    Manually open these PRs if you are sure that they are not duplicates (and tell us that in the PR).
  EOS

  if strict || (version && official_tap)
    odie <<~EOS
      #{duplicates_message.chomp}
      #{error_message}
    EOS
  elsif !official_tap
    opoo duplicates_message
  elsif quiet
    opoo error_message
  else
    opoo <<~EOS
      #{duplicates_message.chomp}
      #{error_message}
    EOS
  end
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



19
20
21
22
23
24
25
26
# File 'utils/github.rb', line 19

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

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

.count_issues(query, **qualifiers) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



42
43
44
# File 'utils/github.rb', line 42

def self.count_issues(query, **qualifiers)
  search_results_count("issues", query, **qualifiers)
end

.count_repo_commits(nwo, user, from: nil, to: nil, max: nil) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



904
905
906
907
908
909
910
911
912
913
914
915
916
# File 'utils/github.rb', line 904

def self.count_repo_commits(nwo, user, from: nil, to: nil, max: nil)
  odie "Cannot count commits as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?

  author_shas = repo_commits_for_user(nwo, user, "author", from, to, max)
  committer_shas = repo_commits_for_user(nwo, user, "committer", from, to, max)
  return [0, 0] if author_shas.blank? && committer_shas.blank?

  author_count = author_shas.count
  # Only count commits where the author and committer are different.
  committer_count = committer_shas.difference(author_shas).count

  [author_count, committer_count]
end

.create_bump_pr(info, args:) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# File 'utils/github.rb', line 717

def self.create_bump_pr(info, args:)
  tap = info[:tap]
  remote = info[:remote] || "origin"
  remote_branch = info[:remote_branch] || tap.git_repository.origin_branch_name
  branch = info[:branch_name]
  previous_branch = info[:previous_branch] || "-"
  tap_remote_repo = info[:tap_remote_repo] || tap.full_name
  pr_message = info[:pr_message]
  pr_title = info[:pr_title]
  commits = info[:commits]

  remote_url = Utils.popen_read("git", "remote", "get-url", "--push", "origin").chomp
  username = tap.user

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

    next if args.dry_run?

    require "utils/popen"
    git_dir = Utils.popen_read("git", "rev-parse", "--git-dir").chomp
    shallow = !git_dir.empty? && File.exist?("#{git_dir}/shallow")
    safe_system "git", "fetch", "--unshallow", "origin" if !args.commit? && shallow
    safe_system "git", "checkout", "--no-track", "-b", branch, "#{remote}/#{remote_branch}" unless args.commit?
    Utils::Git.set_name_email!
  end

  commits.each do |commit|
    sourcefile_path = commit[:sourcefile_path]
    commit_message = commit[:commit_message]
    additional_files = commit[:additional_files] || []

    sourcefile_path.parent.cd do
      require "utils/popen"
      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_only? && !args.commit?)
        ohai "git checkout --no-track -b #{branch} #{remote}/#{remote_branch}"
        ohai "git fetch --unshallow origin" if shallow
        ohai "git add #{changed_files.join(" ")}"
        ohai "git commit --no-edit --verbose --message='#{commit_message}' " \
             "-- #{changed_files.join(" ")}"
        ohai "git push --set-upstream #{remote_url} #{branch}:#{branch}"
        ohai "git checkout --quiet #{previous_branch}"
        ohai "create pull request with GitHub API (base branch: #{remote_branch})"
      else
        safe_system "git", "add", *changed_files
        Utils::Git.set_name_email!
        safe_system "git", "commit", "--no-edit", "--verbose",
                    "--message=#{commit_message}",
                    "--", *changed_files
      end
    end
  end

  return if args.commit? || args.dry_run?

  tap.path.cd do
    system_command!("git", args:         ["push", "--set-upstream", remote_url, "#{branch}:#{branch}"],
                           print_stdout: true)
    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, pr_title,
                                "#{username}:#{branch}", remote_branch, pr_message)["html_url"]
      if args.no_browse?
        puts url
      else
        exec_browser url
      end
    rescue *API::ERRORS => e
      commits.each do |commit|
        commit[:sourcefile_path].atomic_write(commit[:old_contents])
      end
      odie "Unable to open pull request for #{tap_remote_repo}: #{e.message}!"
    end
  end
end

.create_check_run(repo:, data:) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



28
29
30
# File 'utils/github.rb', line 28

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

.create_fork(repo, org: nil) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



123
124
125
126
127
128
129
# File 'utils/github.rb', line 123

def self.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:, scopes:)
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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

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

.create_issue(repo, title, body) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



52
53
54
55
56
# File 'utils/github.rb', line 52

def self.create_issue(repo, title, body)
  url = "#{API_URL}/repos/#{repo}/issues"
  data = { "title" => title, "body" => body }
  API.open_rest(url, 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 an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'utils/github.rb', line 267

def self.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:,
  }
  data[:body] = body if body.present?
  API.open_rest(url, 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 an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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

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

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



236
237
238
239
240
241
# File 'utils/github.rb', line 236

def self.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

.download_artifact(url, artifact_id) ⇒ void

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.

This method returns an undefined value.

Download an artifact from GitHub Actions and unpack it into the current working directory.

Parameters:

  • url (String)

    URL to download from

  • artifact_id (String)

    a value that uniquely identifies the downloaded artifact

Raises:



13
14
15
16
17
18
19
20
21
22
# File 'utils/github/artifacts.rb', line 13

def self.download_artifact(url, artifact_id)
  token = API.credentials
  raise API::MissingAuthenticationError if token.blank?

  # We use a download strategy here to leverage the Homebrew cache
  # to avoid repeated downloads of (possibly large) bottles.
  downloader = GitHubArtifactDownloadStrategy.new(url, artifact_id, token:)
  downloader.fetch
  downloader.stage
end

.fetch_open_pull_requests(name, tap_remote_repo, version: nil) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# File 'utils/github.rb', line 586

def self.fetch_open_pull_requests(name, tap_remote_repo, version: nil)
  return [] if tap_remote_repo.blank?

  # Bust the cache every three minutes.
  cache_expiry = 3 * 60
  cache_epoch = Time.now - (Time.now.to_i % cache_expiry)
  cache_key = "#{tap_remote_repo}_#{cache_epoch.to_i}"

  @open_pull_requests ||= {}
  @open_pull_requests[cache_key] ||= begin
    query = <<~EOS
      query($owner: String!, $repo: String!, $states: [PullRequestState!], $after: String) {
        repository(owner: $owner, name: $repo) {
          pullRequests(states: $states, first: 100, after: $after) {
            nodes {
              number
              title
              url
            }
            pageInfo {
              hasNextPage
              endCursor
            }
          }
        }
      }
    EOS
    owner, repo = tap_remote_repo.split("/")
    variables = { owner:, repo:, states: ["OPEN"] }

    pull_requests = []
    API.paginate_graphql(query, variables:) do |result|
      data = result.dig("repository", "pullRequests")
      pull_requests.concat(data["nodes"])
      data["pageInfo"]
    end
    pull_requests
  end

  regex = pull_request_title_regex(name, version)
  @open_pull_requests[cache_key].select { |pr| regex.match?(pr["title"]) }
                                .map { |pr| pr.merge("html_url" => pr.delete("url")) }
rescue API::RateLimitExceededError => e
  opoo e.message
  pull_requests || []
end

.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil) ⇒ Array<Hash{String => T.untyped}>

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.

Parameters:

  • name (String)
  • tap_remote_repo (String)
  • state (String, nil) (defaults to: nil)
  • version (String, nil) (defaults to: nil)

Returns:



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
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
# File 'utils/github.rb', line 527

def self.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil)
  return [] if Homebrew::EnvConfig.no_github_api?

  regex = pull_request_title_regex(name, version)
  query = "is:pr #{name} #{version}".strip

  # Unauthenticated users cannot use GraphQL so use search REST API instead.
  # Limit for this is 30/minute so is usually OK unless you're spamming bump PRs (e.g. CI).
  if API.credentials_type == :none
    return issues_for_formula(query, tap_remote_repo:, state:).select do |pr|
      pr["html_url"].include?("/pull/") && regex.match?(pr["title"])
    end
  elsif state == "open" && ENV["GITHUB_REPOSITORY_OWNER"] == "Homebrew"
    # Try use PR API, which might be cheaper on rate limits in some cases.
    # The rate limit of the search API under GraphQL is unclear as it
    # costs the same as any other query according to /rate_limit.
    # The PR API is also not very scalable so limit to Homebrew CI.
    return fetch_open_pull_requests(name, tap_remote_repo, version:)
  end

  query += " repo:#{tap_remote_repo} in:title"
  query += " state:#{state}" if state.present?
  graphql_query = <<~EOS
    query($query: String!, $after: String) {
      search(query: $query, type: ISSUE, first: 100, after: $after) {
        nodes {
          ... on PullRequest {
            number
            title
            url
            state
          }
        }
        pageInfo {
          hasNextPage
          endCursor
        }
      }
    }
  EOS
  variables = { query: }

  pull_requests = []
  API.paginate_graphql(graphql_query, variables:) do |result|
    data = result["search"]
    pull_requests.concat(data["nodes"].select { |pr| regex.match?(pr["title"]) })
    data["pageInfo"]
  end
  pull_requests.map! do |pr|
    pr.merge({
      "html_url" => pr.delete("url"),
      "state"    => pr.fetch("state").downcase,
    })
  end
rescue API::RateLimitExceededError => e
  opoo e.message
  pull_requests || []
end

.fork_exists?(repo, org: nil) ⇒ Boolean

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


131
132
133
134
135
136
137
138
139
140
# File 'utils/github.rb', line 131

def self.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

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



704
705
706
707
708
709
710
711
712
713
714
715
# File 'utils/github.rb', line 704

def self.forked_repo_info!(tap_remote_repo, org: nil)
  response = create_fork(tap_remote_repo, org:)
  # GitHub API responds immediately but fork takes a few seconds to be ready.
  sleep 1 until fork_exists?(tap_remote_repo, org:)
  remote_url = if system("git", "config", "--local", "--get-regexp", "remote..*.url", "git@github.com:.*")
    response.fetch("ssh_url")
  else
    add_auth_token_to_url!(response.fetch("clone_url"))
  end
  username = response.fetch("owner").fetch("login")
  [remote_url, username]
end

.generate_release_notes(user, repo, tag, previous_tag: nil) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



260
261
262
263
264
265
# File 'utils/github.rb', line 260

def self.generate_release_notes(user, repo, tag, previous_tag: nil)
  url = "#{API_URL}/repos/#{user}/#{repo}/releases/generate-notes"
  data = { tag_name: tag }
  data[:previous_tag_name] = previous_tag if previous_tag.present?
  API.open_rest(url, data:, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end

.get_artifact_urls(workflow_array) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



343
344
345
346
347
348
349
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
# File 'utils/github.rb', line 343

def self.get_artifact_urls(workflow_array)
  check_suite, user, repo, pr, workflow_id, scopes, artifact_pattern = *workflow_array
  if check_suite.empty?
    raise API::Error, <<~EOS
      No matching check suite found for these criteria!
        Pull request: #{pr}
        Workflow:     #{workflow_id}
    EOS
  end

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

  run_id = check_suite.last["workflowRun"]["databaseId"]
  artifacts = []
  per_page = 50
  API.paginate_rest("#{API_URL}/repos/#{user}/#{repo}/actions/runs/#{run_id}/artifacts",
                    per_page:, scopes:) do |result|
    result = result["artifacts"]
    artifacts.concat(result)
    break if result.length < per_page
  end

  matching_artifacts =
    artifacts
    .group_by { |art| art["name"] }
    .select { |name| File.fnmatch?(artifact_pattern, name, File::FNM_EXTGLOB) }
    .map { |_, arts| arts.last }

  if matching_artifacts.empty?
    raise API::Error, <<~EOS
      No artifacts with the pattern `#{artifact_pattern}` were found!
        #{Formatter.url check_suite.last["workflowRun"]["url"]}
    EOS
  end

  matching_artifacts.map { |art| art["archive_download_url"] }
end

.get_latest_release(user, repo) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



255
256
257
258
# File 'utils/github.rb', line 255

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

.get_pull_request_changed_files(tap_remote_repo, pull_request) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



689
690
691
692
693
694
695
# File 'utils/github.rb', line 689

def self.get_pull_request_changed_files(tap_remote_repo, pull_request)
  files = []
  API.paginate_rest(url_to("repos", tap_remote_repo, "pulls", pull_request, "files")) do |result|
    files.concat(result)
  end
  files
end

.get_release(user, repo, tag) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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

def self.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, ref: nil) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



504
505
506
507
508
509
510
511
512
513
514
515
# File 'utils/github.rb', line 504

def self.get_repo_license(user, repo, ref: nil)
  url = "#{API_URL}/repos/#{user}/#{repo}/license"
  url += "?ref=#{ref}" if ref.present?
  response = API.open_rest(url)
  return unless response.key?("license")

  response["license"]["spdx_id"]
rescue API::HTTPNotFoundError
  nil
rescue API::AuthenticationFailedError => e
  raise unless e.message.match?(API::GITHUB_IP_ALLOWLIST_ERROR)
end

.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_pattern: "bottles{,_*}") ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'utils/github.rb', line 290

def self.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_pattern: "bottles{,_*}")
  scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES

  # GraphQL unfortunately has no way to get the workflow yml name, so we need an extra REST call.
  workflow_api_url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow_id}"
  workflow_payload = API.open_rest(workflow_api_url, scopes:)
  workflow_id_num = workflow_payload["id"]

  query = <<~EOS
    query ($user: String!, $repo: String!, $pr: Int!) {
      repository(owner: $user, name: $repo) {
        pullRequest(number: $pr) {
          commits(last: 1) {
            nodes {
              commit {
                checkSuites(first: 100) {
                  nodes {
                    status,
                    workflowRun {
                      databaseId,
                      url,
                      workflow {
                        databaseId
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  EOS
  variables = {
    user:,
    repo:,
    pr:   pull_request.to_i,
  }
  result = API.open_graphql(query, variables:, scopes:)

  commit_node = result["repository"]["pullRequest"]["commits"]["nodes"].first
  check_suite = if commit_node.present?
    commit_node["commit"]["checkSuites"]["nodes"].select do |suite|
      suite.dig("workflowRun", "workflow", "databaseId") == workflow_id_num
    end
  else
    []
  end

  [check_suite, user, repo, pull_request, workflow_id, scopes, artifact_pattern]
end

.issues(repo:, **filters) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



32
33
34
35
36
# File 'utils/github.rb', line 32

def self.issues(repo:, **filters)
  uri = url_to("repos", repo, "issues")
  uri.query = URI.encode_www_form(filters)
  API.open_rest(uri)
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



62
63
64
65
66
# File 'utils/github.rb', line 62

def self.issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap&.full_name, state: nil, type: nil)
  return [] unless tap_remote_repo

  search_issues(name, repo: tap_remote_repo, state:, type:, in: "title")
end

.last_commit(user, repo, ref, version) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
# File 'utils/github.rb', line 851

def self.last_commit(user, repo, ref, version)
  return if Homebrew::EnvConfig.no_github_api?

  require "utils/curl"
  result = Utils::Curl.curl_output(
    "--silent", "--head", "--location",
    "--header", "Accept: application/vnd.github.sha",
    url_to("repos", user, repo, "commits", ref).to_s
  )

  return unless result.status.success?

  commit = result.stdout[/^ETag: "(\h+)"/, 1]
  return if commit.blank?

  version.update_commit(commit)
  commit
end

.members_by_team(org, team) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Raises:



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'utils/github.rb', line 399

def self.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"].to_h { |member| [member["login"], member["name"]] }
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



93
94
95
96
97
98
# File 'utils/github.rb', line 93

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

.multiple_short_commits_exist?(user, repo, commit) ⇒ Boolean

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'utils/github.rb', line 870

def self.multiple_short_commits_exist?(user, repo, commit)
  return false if Homebrew::EnvConfig.no_github_api?

  require "utils/curl"
  result = Utils::Curl.curl_output(
    "--silent", "--head", "--location",
    "--header", "Accept: application/vnd.github.sha",
    url_to("repos", user, repo, "commits", commit).to_s
  )

  return true unless result.status.success?
  return true if (output = result.stdout).blank?

  output[/^Status: (200)/, 1] != "200"
end

.pat_blurb(scopes = ALL_SCOPES) ⇒ String

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.

Parameters:

Returns:



9
10
11
12
13
14
15
16
17
18
19
# File 'utils/github/api.rb', line 9

def self.pat_blurb(scopes = ALL_SCOPES)
  require "utils/formatter"
  require "utils/shell"
  <<~EOS
    Create a GitHub personal access token:
      #{Formatter.url(
        "https://github.com/settings/tokens/new?scopes=#{scopes.join(",")}&description=Homebrew",
      )}
    #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")}
  EOS
end

.permission(repo, user) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



72
73
74
# File 'utils/github.rb', line 72

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'utils/github.rb', line 100

def self.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 an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


149
150
151
152
# File 'utils/github.rb', line 149

def self.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 an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



387
388
389
390
391
392
393
394
395
396
397
# File 'utils/github.rb', line 387

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

  API.paginate_rest(url, 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, pull_request, per_page: 100) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'utils/github.rb', line 825

def self.pull_request_commits(user, repo, pull_request, per_page: 100)
  pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pull_request))
  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:) 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, pull_request) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



846
847
848
849
# File 'utils/github.rb', line 846

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

.pull_request_title_regex(name, version = nil) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



517
518
519
520
521
# File 'utils/github.rb', line 517

def self.pull_request_title_regex(name, version = nil)
  return /(^|\s)#{Regexp.quote(name)}(:|,|\s|$)/i if version.blank?

  /(^|\s)#{Regexp.quote(name)}(:|,|\s)(.*\s)?#{Regexp.quote(version)}(:|,|\s|$)/i
end

.pull_requests(repo, **options) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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

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

.repo_commits_for_user(nwo, user, filter, from, to, max) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# File 'utils/github.rb', line 886

def self.repo_commits_for_user(nwo, user, filter, from, to, max)
  return if Homebrew::EnvConfig.no_github_api?

  params = ["#{filter}=#{user}"]
  params << "since=#{DateTime.parse(from).iso8601}" if from.present?
  params << "until=#{DateTime.parse(to).iso8601}" if to.present?

  commits = []
  API.paginate_rest("#{API_URL}/repos/#{nwo}/commits", additional_query_params: params.join("&")) do |result|
    commits.concat(result.map { |c| c["sha"] })
    if max.present? && commits.length >= max
      opoo "#{user} exceeded #{max} #{nwo} commits as #{filter}, stopped counting!"
      break
    end
  end
  commits
end

.repository(user, repo) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



58
59
60
# File 'utils/github.rb', line 58

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

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



179
180
181
182
183
# File 'utils/github.rb', line 179

def self.search(entity, *queries, **qualifiers)
  uri = url_to "search", entity
  uri.query = search_query_string(*queries, **qualifiers)
  API.open_rest(uri)
end

.search_issues(query, **qualifiers) ⇒ Object

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



38
39
40
# File 'utils/github.rb', line 38

def self.search_issues(query, **qualifiers)
  search_results_items("issues", query, **qualifiers)
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'utils/github.rb', line 154

def self.search_query_string(*main_params, **qualifiers)
  params = main_params

  from = qualifiers.fetch(:from, nil)
  to = qualifiers.fetch(:to, nil)

  params << if from && to
    "created:#{from}..#{to}"
  elsif from
    "created:>=#{from}"
  elsif to
    "created:<=#{to}"
  end

  params += qualifiers.except(:args, :from, :to).flat_map do |key, value|
    Array(value).map { |v| "#{key.to_s.tr("_", "-")}:#{v}" }
  end

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

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



190
191
192
193
# File 'utils/github.rb', line 190

def self.search_results_count(entity, *queries, **qualifiers)
  json = search(entity, *queries, **qualifiers)
  json.fetch("total_count", 0)
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



185
186
187
188
# File 'utils/github.rb', line 185

def self.search_results_items(entity, *queries, **qualifiers)
  json = search(entity, *queries, **qualifiers)
  json.fetch("items", [])
end

.sponsorships(user) ⇒ Array<Hash>

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.

Parameters:

Returns:

Raises:



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
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
# File 'utils/github.rb', line 439

def self.sponsorships(user)
  query = <<~EOS
      query($user: String!, $after: String) { organization(login: $user) {
        sponsorshipsAsMaintainer(first: 100, after: $after) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            tier {
              monthlyPriceInDollars
              closestLesserValueTier {
                monthlyPriceInDollars
              }
            }
            sponsorEntity {
              ... on Organization { login name }
              ... on User { login name }
            }
          }
        }
      }
    }
  EOS

  sponsorships = T.let([], T::Array[Hash])
  errors = T.let([], T::Array[Hash])

  API.paginate_graphql(query, variables: { user: }, scopes: ["user"], raise_errors: false) do |result|
    # Some organisations do not permit themselves to be queried through the
    # API like this and raise an error so handle these errors later.
    # This has been reported to GitHub.
    errors += result["errors"] if result["errors"].present?

    current_sponsorships = result.dig("data", "organization", "sponsorshipsAsMaintainer")
    # if `current_sponsorships` is blank, then there should be errors to report.
    next { "hasNextPage" => false } if current_sponsorships.blank?

    # The organisations mentioned above will show up as nil nodes.
    if (nodes = current_sponsorships["nodes"].compact.presence)
      sponsorships += nodes
    end

    current_sponsorships.fetch("pageInfo")
  end

  # Only raise errors if we didn't get any sponsorships.
  raise API::Error, errors.map { |e| e["message"] }.join("\n") if sponsorships.blank? && errors.present?

  sponsorships.map do |sponsorship|
    sponsor = sponsorship["sponsorEntity"]
    tier = sponsorship["tier"].presence || {}
    monthly_amount = tier["monthlyPriceInDollars"].presence || 0
    closest_tier = tier["closestLesserValueTier"].presence || {}
    closest_tier_monthly_amount = closest_tier["monthlyPriceInDollars"].presence || 0

    {
      name:                        sponsor["name"].presence || sponsor["login"],
      login:                       sponsor["login"],
      monthly_amount:,
      closest_tier_monthly_amount:,
    }
  end
end

.too_many_open_prs?(tap) ⇒ 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.

Parameters:

  • tap (Tap, nil)

Returns:

  • (Boolean)


921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
# File 'utils/github.rb', line 921

def self.too_many_open_prs?(tap)
  # We don't enforce unofficial taps.
  return false if tap.nil? || !tap.official?

  # BrewTestBot can open as many PRs as it wants.
  return false if ENV["HOMEBREW_TEST_BOT_AUTOBUMP"].present?

  odie "Cannot count PRs as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?

  query = <<~EOS
    query($after: String) {
      viewer {
        login
        pullRequests(first: 100, states: OPEN, after: $after) {
          totalCount
          nodes {
            baseRepository {
              owner {
                login
              }
            }
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    }
  EOS
  puts

  homebrew_prs_count = 0

  begin
    API.paginate_graphql(query) do |result|
      data = result.fetch("viewer")
      github_user = data.fetch("login")

      # BrewTestBot can open as many PRs as it wants.
      return false if github_user.casecmp?("brewtestbot")

      pull_requests = data.fetch("pullRequests")
      return false if pull_requests.fetch("totalCount") < MAXIMUM_OPEN_PRS

      homebrew_prs_count += pull_requests.fetch("nodes").count do |node|
        node.dig("baseRepository", "owner", "login").casecmp?("homebrew")
      end
      return true if homebrew_prs_count >= MAXIMUM_OPEN_PRS

      pull_requests.fetch("pageInfo")
    end
  rescue => e
    # Ignore SAML access errors (https://github.com/Homebrew/brew/issues/18610) and related
    # IP allow list errors (https://github.com/orgs/Homebrew/discussions/6263)
    return false if e.message.include?("Resource protected by organization SAML enforcement") ||
                    e.message.include?("your IP address is not permitted to access this resource")

    raise
  end

  false
end

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



284
285
286
287
288
# File 'utils/github.rb', line 284

def self.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 an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



175
176
177
# File 'utils/github.rb', line 175

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

.userObject

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



68
69
70
# File 'utils/github.rb', line 68

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

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



243
244
245
246
247
248
# File 'utils/github.rb', line 243

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

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

This method is part of an internal API. This method may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (Boolean)


76
77
78
79
# File 'utils/github.rb', line 76

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