Module: GitHub Private
- Extended by:
- Workflows, SystemCommand::Mixin, Utils::Output::Mixin
- Defined in:
- utils/github.rb,
utils/github/api.rb,
utils/github/actions.rb,
utils/github/artifacts.rb,
utils/github/workflows.rb,
utils/github/patch_inclusion.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, Workflows Classes: PatchInclusion
Constant Summary collapse
- MAX_PER_PAGE =
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.
100- WorkflowArray =
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.type_alias { [T::Array[T::Hash[String, T.untyped]], String, String, String, String, T::Array[String], String] }
- 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.
"https://api.github.com"- 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.
["gist"].freeze
- 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.
["repo"].freeze
- 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.
["workflow"].freeze
Class Method Summary collapse
-
.check_for_duplicate_pull_requests(name, tap_remote_repo, file:, quiet: false, state: nil, version: nil, official_tap: true, strict: false) ⇒ void
internal
Check for duplicate pull requests that modify the same file.
- .create_fork(repo, org: nil) ⇒ Hash{String => T.untyped} private
- .create_gist(files, description, private:) ⇒ String private
- .create_issue(repo, title, body) ⇒ String private
- .create_issue_comment(repo, issue, body) ⇒ Hash{String => T.untyped} private
- .create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false) ⇒ Hash{String => T.untyped} private
- .create_pull_request(repo, title, head, base, body) ⇒ Hash{String => T.untyped} private
-
.download_artifact(url, artifact_id) ⇒ void
private
Download an artifact from GitHub Actions and unpack it into the current working directory.
- .fetch_open_pull_requests(name, tap_remote_repo, version: nil) ⇒ Array<Hash{String => String}> private
- .fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil) ⇒ Array<Hash{String => T.untyped}> private
- .fork_exists?(repo, org: nil) ⇒ Boolean private
- .generate_release_notes(user, repo, tag, previous_tag: nil) ⇒ Hash{String => T.untyped} private
- .get_draft_release(user, repo, tag) ⇒ Hash{String => T.untyped}? private
- .get_latest_release(user, repo) ⇒ Hash{String => T.untyped} private
- .get_pull_request_changed_files(tap_remote_repo, pull_request) ⇒ Array<T.untyped> private
- .get_release(user, repo, tag) ⇒ Hash{String => T.untyped} private
- .get_repo_license(user, repo, ref: nil) ⇒ String? private
- .issues(repo:, state:, labels:) ⇒ Array<Hash{String => T.untyped}> private
- .issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap&.full_name, state: nil, type: nil) ⇒ Array<Hash{String => T.untyped}> private
- .last_commit(user, repo, ref, version, length: nil) ⇒ String? private
- .members_by_team(org, team) ⇒ Hash{String => String} private
- .multiple_short_commits_exist?(user, repo, commit) ⇒ Boolean private
- .organisation_repositories(organisation, from, to, verbose) ⇒ Array<String> private
- .pat_blurb(scopes = ALL_SCOPES) ⇒ String private
- .print_pull_requests_matching(query, only = nil) ⇒ void private
-
.private_repo?(full_name) ⇒ Boolean
private
We default to private if we aren't sure or if the GitHub API is disabled.
- .pull_request_commits(user, repo, pull_request, per_page: MAX_PER_PAGE) ⇒ Array<String> private
- .pull_request_labels(user, repo, pull_request) ⇒ Array<String> private
- .pull_request_title_regex(name, version = nil) ⇒ Regexp private
- .repository(user, repo) ⇒ Hash{String => T.untyped} private
- .repository_approved_reviews(user, repo, pull_request, commit: nil) ⇒ Array<Hash{String => T.untyped}> private
- .search(entity, *queries, **qualifiers) ⇒ Hash{String => T.untyped} private
- .search_approved_pull_requests_in_user_or_organisation(user, reviewed_by, from:, to:) ⇒ Array<Hash{String => T.untyped}> private
- .search_issues(query, **qualifiers) ⇒ Array<Hash{String => T.untyped}> private
- .search_query_string(*main_params, **qualifiers) ⇒ String private
-
.sponsorship_tiers(user) ⇒ Array<Hash>
private
Return published tiers with one-time prices expressed as monthly amounts.
- .sponsorships(user) ⇒ Array<Hash> private
- .too_many_open_prs?(tap) ⇒ Boolean private
- .upload_release_asset(user, repo, id, local_file:, remote_file: nil) ⇒ void private
- .url_to(*subroutes) ⇒ URI::Generic private
- .user ⇒ Hash{String => T.untyped} private
- .workflow_dispatch_event(user, repo, workflow, ref, **inputs) ⇒ void private
Methods included from Workflows
get_artifact_urls, get_workflow_run
Methods included from SystemCommand::Mixin
command_sandbox, system_command, system_command!
Methods included from Utils::Output::Mixin
issue_reporting_message, odebug, odeprecated, odie, odisabled, ofail, oh1, oh1_title, ohai, ohai_title, onoe, opoo, opoo_once, opoo_outside_github_actions, opoo_without_github_actions_annotation, pretty_cannot_install, pretty_deprecated, pretty_disabled, pretty_duration, pretty_incompatible, pretty_install_status, pretty_installed, pretty_removed, pretty_uninstalled, pretty_unmarked, pretty_upgradable, pretty_warning
Class Method Details
.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.
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 |
# File 'utils/github.rb', line 586 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" state_prefix = state ? "#{state} " : "" pr_list = pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n") = <<~EOS These #{state_prefix}pull requests #{confidence} duplicates: #{pr_list} EOS = <<~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 #{.chomp} #{} EOS elsif !official_tap opoo elsif quiet opoo else opoo <<~EOS #{.chomp} #{} EOS end end |
.create_fork(repo, org: nil) ⇒ 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.
107 108 109 110 111 112 113 |
# File 'utils/github.rb', line 107 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:) ⇒ 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.
38 39 40 41 42 |
# File 'utils/github.rb', line 38 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) ⇒ 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.
45 46 47 48 49 |
# File 'utils/github.rb', line 45 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_issue_comment(repo, issue, body) ⇒ 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.
52 53 54 55 |
# File 'utils/github.rb', line 52 def self.create_issue_comment(repo, issue, body) url = "#{API_URL}/repos/#{repo}/issues/#{issue}/comments" API.open_rest(url, data: { body: }, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES) end |
.create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false) ⇒ 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.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
# File 'utils/github.rb', line 269 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) ⇒ 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.
128 129 130 131 132 133 |
# File 'utils/github.rb', line 128 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 |
.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.
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) ⇒ Array<Hash{String => 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.
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 559 560 561 562 563 564 565 566 |
# File 'utils/github.rb', line 521 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 ||= T.let({}, T.nilable(T::Hash[String, T.untyped])) @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. 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.
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 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'utils/github.rb', line 458 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. pull_requests || [] end |
.fork_exists?(repo, org: 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.
116 117 118 119 120 121 122 123 124 125 |
# File 'utils/github.rb', line 116 def self.fork_exists?(repo, org: nil) reponame = repo.split("/").fetch(1) 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 |
.generate_release_notes(user, repo, tag, previous_tag: nil) ⇒ 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.
258 259 260 261 262 263 |
# File 'utils/github.rb', line 258 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_draft_release(user, repo, tag) ⇒ 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.
242 243 244 245 246 247 248 249 |
# File 'utils/github.rb', line 242 def self.get_draft_release(user, repo, tag) url = "#{API_URL}/repos/#{user}/#{repo}/releases" API.paginate_rest(url) do |releases| draft_release = releases.find { |release| release["draft"] && release["tag_name"] == tag } return draft_release if draft_release end nil end |
.get_latest_release(user, repo) ⇒ 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.
252 253 254 255 |
# File 'utils/github.rb', line 252 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) ⇒ Array<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.
627 628 629 630 631 632 633 |
# File 'utils/github.rb', line 627 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) ⇒ 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.
234 235 236 237 |
# File 'utils/github.rb', line 234 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) ⇒ 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.
434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'utils/github.rb', line 434 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..match?(API::GITHUB_IP_ALLOWLIST_ERROR) end |
.issues(repo:, state:, labels:) ⇒ 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.
25 26 27 28 29 |
# File 'utils/github.rb', line 25 def self.issues(repo:, state:, labels:) uri = url_to("repos", repo, "issues") uri.query = URI.encode_www_form(state:, labels:) API.open_rest(uri) end |
.issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap&.full_name, state: nil, type: 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.
71 72 73 74 75 |
# File 'utils/github.rb', line 71 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, length: nil) ⇒ 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.
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 |
# File 'utils/github.rb', line 672 def self.last_commit(user, repo, ref, version, length: nil) return if Homebrew::EnvConfig.no_github_api? require "utils/curl" result = Utils::Curl.curl_output( "--silent", "--head", "--location", "--header", "Accept: application/vnd.github.sha", *API.credentials_curl_args, url_to("repos", user, repo, "commits", ref).to_s, secrets: [API.credentials].compact ) return unless result.status.success? commit = result.stdout[/^ETag: "(\h+)"/i, 1] return if commit.blank? if length return if commit.length < length commit = commit[0, length] odie "commit does not exist" unless commit # We return nil if the following fails as we currently don't have a way to # determine the reason for the failure. This means we can't distinguish a # GitHub API rate limit from a non-unique short commit where the latter # needs (n+1) or more characters to match `git rev-parse --short=n`. return if multiple_short_commits_exist?(user, repo, commit) end version.update_commit(commit) commit end |
.members_by_team(org, team) ⇒ Hash{String => 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.
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 |
# File 'utils/github.rb', line 296 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.dig("organization", "teams", "nodes").blank? || result.dig("organization", "team").blank? raise API::Error, "Could not access the team #{org}/#{team}. " \ "Please check that your GitHub account has access to the team and that your token has the " \ "required permissions." end result["organization"]["team"]["members"]["nodes"].to_h { |member| [member["login"], member["name"]] } end |
.multiple_short_commits_exist?(user, repo, commit) ⇒ 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.
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
# File 'utils/github.rb', line 707 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", *API.credentials_curl_args, "--output", File::NULL, *Utils::Curl.curl_http_code_write_out_args, url_to("repos", user, repo, "commits", commit).to_s, secrets: [API.credentials].compact ) return true unless result.status.success? return true if (output = result.stdout).blank? output != "200" end |
.organisation_repositories(organisation, from, to, verbose) ⇒ Array<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.
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 824 825 826 827 828 829 |
# File 'utils/github.rb', line 795 def self.organisation_repositories(organisation, from, to, verbose) from_date = Date.parse(from) to_date = Date.parse(to) rest_api_url = "#{GitHub::API_URL}/orgs/#{organisation}/repos" params = "type=sources" repositories = [] GitHub::API.paginate_rest(rest_api_url, per_page: MAX_PER_PAGE, additional_query_params: params) do |result| repositories.concat(result) end repositories.filter_map do |repository| pushed_at = Date.parse(repository.fetch("pushed_at")) created_at = Date.parse(repository.fetch("created_at")) archived_at = Date.parse(repository.fetch("archived_at", from)) full_name = repository.fetch("full_name") not_pushed = pushed_at < from_date not_created = created_at > to_date archived = archived_at < from_date if not_pushed || not_created || archived if verbose reasons = [] reasons << "not pushed" if not_pushed reasons << "not created" if not_created reasons << "archived" if archived opoo "Repository #{full_name} #{reasons.join(", ")} from #{from_date} to #{to_date}. Skipping." end next end full_name end 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.
11 12 13 14 15 16 17 18 19 20 |
# File 'utils/github/api.rb', line 11 def self.pat_blurb(scopes = ALL_SCOPES) require "utils/formatter" require "utils/shell" token_url = "https://github.com/settings/tokens/new?scopes=#{scopes.join(",")}&description=Homebrew" <<~EOS Create a GitHub personal access token: #{Formatter.url(token_url)} #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} EOS end |
.print_pull_requests_matching(query, only = nil) ⇒ 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.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'utils/github.rb', line 83 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 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.
We default to private if we aren't sure or if the GitHub API is disabled.
137 138 139 140 |
# File 'utils/github.rb', line 137 def self.private_repo?(full_name) uri = url_to "repos", full_name API.open_rest(uri) { |json| json.fetch("private", true) } end |
.pull_request_commits(user, repo, pull_request, per_page: MAX_PER_PAGE) ⇒ Array<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.
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 |
# File 'utils/github.rb', line 639 def self.pull_request_commits(user, repo, pull_request, per_page: MAX_PER_PAGE) 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 commits end |
.pull_request_labels(user, repo, pull_request) ⇒ Array<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.
663 664 665 666 |
# File 'utils/github.rb', line 663 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) ⇒ Regexp
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.
448 449 450 451 452 |
# File 'utils/github.rb', line 448 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 |
.repository(user, repo) ⇒ 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.
58 59 60 |
# File 'utils/github.rb', line 58 def self.repository(user, repo) API.open_rest(url_to("repos", user, repo)) end |
.repository_approved_reviews(user, repo, pull_request, commit: 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.
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 |
# File 'utils/github.rb', line 182 def self.repository_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 { databaseId } ... on Organization { databaseId } } authorAssociation commit { oid } } } } } } EOS result = API.open_graphql(query) reviews = result["repository"]["pullRequest"]["reviews"]["nodes"] valid_associations = %w[MEMBER OWNER] profiles = {} reviews.filter_map do |r| next if commit.present? && commit != r["commit"]["oid"] next unless valid_associations.include? r["authorAssociation"] id = r.dig("author", "databaseId") next unless id # The public profile exposes the email without a GraphQL user:email scope. = profiles[id] ||= API.open_rest(url_to("user", id)) login = .fetch("login") { "email" => ["email"].presence || "#{id}+#{login}@users.noreply.github.com", "name" => ["name"].presence || login, "login" => login, } end end |
.search(entity, *queries, **qualifiers) ⇒ 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.
172 173 174 175 176 |
# File 'utils/github.rb', line 172 def self.search(entity, *queries, **qualifiers) uri = url_to "search", entity uri.query = search_query_string(*queries, **qualifiers) API.open_rest(uri) end |
.search_approved_pull_requests_in_user_or_organisation(user, reviewed_by, from:, to:) ⇒ 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.
835 836 837 838 839 840 |
# File 'utils/github.rb', line 835 def self.search_approved_pull_requests_in_user_or_organisation(user, reviewed_by, from:, to:) search_issues("", is: "pr", review: "approved", user:, reviewed_by:, from:, to:) rescue GitHub::API::ValidationFailedError opoo "Couldn't search GitHub for PRs reviewed by #{reviewed_by}. Their profile might be private. Defaulting to 0." [] end |
.search_issues(query, **qualifiers) ⇒ 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.
32 33 34 35 |
# File 'utils/github.rb', line 32 def self.search_issues(query, **qualifiers) json = search("issues", query, **qualifiers) json.fetch("items", []) end |
.search_query_string(*main_params, **qualifiers) ⇒ 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.
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'utils/github.rb', line 143 def self.search_query_string(*main_params, **qualifiers) params = T.let(main_params.to_a, T::Array[T.nilable(String)]) 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| qualifier = key.to_s.tr("_", "-") Array(value).map { |v| "#{qualifier}:#{v}" } end search_terms = URI.encode_www_form_component(params.compact.join(" ")) "q=#{search_terms}&per_page=#{MAX_PER_PAGE}" end |
.sponsorship_tiers(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.
Return published tiers with one-time prices expressed as monthly amounts.
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
# File 'utils/github.rb', line 327 def self.sponsorship_tiers(user) query = <<~EOS query($user: String!) { organization(login: $user) { sponsorsListing { tiers(first: 100, includeUnpublished: false) { nodes { description monthlyPriceInDollars isOneTime } } } } } EOS result = API.open_graphql(query, variables: { user: }, scopes: ["user"]) Array(result.dig("organization", "sponsorsListing", "tiers", "nodes")).filter_map do |tier| next if tier.nil? months = tier["isOneTime"] ? 12 : 1 { description: tier.fetch("description"), monthly_amount: tier.fetch("monthlyPriceInDollars") / months } end 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.
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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 |
# File 'utils/github.rb', line 365 def self.sponsorships(user) query = <<~EOS query($user: String!, $after: String) { organization(login: $user) { sponsorshipsAsMaintainer(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { isOneTimePayment tierSelectedAt createdAt tier { monthlyPriceInDollars description } sponsorEntity { __typename ... on Organization { login name } ... on User { login name } } } } } } EOS sponsorships = T.let([], T::Array[T::Hash[String, T.untyped]]) errors = T.let([], T::Array[T::Hash[String, T.untyped]]) 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.filter_map do |sponsorship| next if sponsorship["isOneTimePayment"] sponsor = sponsorship["sponsorEntity"] tier = sponsorship["tier"].presence || {} { name: sponsor["name"].presence || sponsor["login"], login: sponsor["login"], type: sponsor["__typename"], monthly_amount: tier.fetch("monthlyPriceInDollars", 0), tier_description: tier.fetch("description", ""), started_at: (sponsorship["tierSelectedAt"] || sponsorship["createdAt"]).to_s, } 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.
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 |
# File 'utils/github.rb', line 730 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..include?("Resource protected by organization SAML enforcement") || e..include?("your IP address is not permitted to access this resource") raise end false end |
.upload_release_asset(user, repo, id, local_file:, remote_file: nil) ⇒ 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.
289 290 291 292 293 |
# File 'utils/github.rb', line 289 def self.upload_release_asset(user, repo, id, local_file:, 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) ⇒ URI::Generic
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.
167 168 169 |
# File 'utils/github.rb', line 167 def self.url_to(*subroutes) URI.parse([API_URL, *subroutes].join("/")) end |
.user ⇒ 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.
78 79 80 |
# File 'utils/github.rb', line 78 def self.user @user ||= T.let(API.open_rest("#{API_URL}/user"), T.nilable(T::Hash[String, T.untyped])) end |
.workflow_dispatch_event(user, repo, workflow, ref, **inputs) ⇒ 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.
226 227 228 229 230 231 |
# File 'utils/github.rb', line 226 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 |