Module: GitHub
- Includes:
- SystemCommand::Mixin
- Defined in:
- utils/github.rb,
utils/github/api.rb,
utils/github/actions.rb,
utils/github/artifacts.rb
Overview
A module that interfaces with GitHub, code like PAT scopes, credential handling and API errors.
Defined Under Namespace
Constant Summary collapse
- API_URL =
"https://api.github.com"
- API_MAX_PAGES =
50
- API_MAX_ITEMS =
5000
- PAGINATE_RETRY_COUNT =
3
- CREATE_GIST_SCOPES =
["gist"].freeze
- CREATE_ISSUE_FORK_OR_PR_SCOPES =
["repo"].freeze
- CREATE_WORKFLOW_SCOPES =
["workflow"].freeze
- ALL_SCOPES =
(CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES + CREATE_WORKFLOW_SCOPES).freeze
- GITHUB_PERSONAL_ACCESS_TOKEN_REGEX =
/^(?:[a-f0-9]{40}|gh[po]_\w{36,251})$/.freeze
Class Method Summary collapse
-
.approved_reviews(user, repo, pull_request, commit: nil) ⇒ Object
private
-
.branch_exists?(user, repo, branch) ⇒ Boolean
private
-
.check_for_duplicate_pull_requests(name, tap_remote_repo, state:, file:, args:, version: nil) ⇒ Object
private
-
.check_runs(repo: nil, commit: nil, pull_request: nil) ⇒ Object
private
-
.count_issues(query, **qualifiers) ⇒ Object
private
-
.count_repo_commits(nwo, user, args, max: nil) ⇒ Object
private
-
.create_bump_pr(info, args:) ⇒ Object
private
-
.create_check_run(repo:, data:) ⇒ Object
private
-
.create_fork(repo, org: nil) ⇒ Object
private
-
.create_gist(files, description, private:) ⇒ Object
private
-
.create_issue(repo, title, body) ⇒ Object
private
-
.create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false) ⇒ Object
private
-
.create_pull_request(repo, title, head, base, body) ⇒ Object
private
-
.dispatch_event(user, repo, event, **payload) ⇒ Object
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) ⇒ Object
private
WARNING: The GitHub API returns results in a slightly different form here compared to
fetch_pull_requests
. -
.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil) ⇒ Object
private
-
.fork_exists?(repo, org: nil) ⇒ Boolean
private
-
.forked_repo_info!(tap_remote_repo, org: nil) ⇒ Object
private
-
.generate_release_notes(user, repo, tag, previous_tag: nil) ⇒ Object
private
-
.get_artifact_url(workflow_array) ⇒ Object
private
-
.get_latest_release(user, repo) ⇒ Object
private
-
.get_pull_request_changed_files(tap_remote_repo, pull_request) ⇒ Object
private
-
.get_release(user, repo, tag) ⇒ Object
private
-
.get_repo_license(user, repo) ⇒ Object
private
-
.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_name: "bottles") ⇒ Object
private
-
.issues(repo:, **filters) ⇒ Object
private
-
.issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap&.full_name, state: nil, type: nil) ⇒ Object
private
-
.last_commit(user, repo, ref, version) ⇒ Object
private
-
.members_by_team(org, team) ⇒ Object
private
-
.merge_pull_request(repo, number:, sha:, merge_method:, commit_message: nil) ⇒ Object
private
-
.multiple_short_commits_exist?(user, repo, commit) ⇒ Boolean
private
-
.pat_blurb(scopes = ALL_SCOPES) ⇒ Object
-
.permission(repo, user) ⇒ Object
private
-
.print_pull_requests_matching(query, only = nil) ⇒ Object
private
-
.private_repo?(full_name) ⇒ Boolean
private
-
.public_member_usernames(org, per_page: 100) ⇒ Object
private
-
.pull_request_commits(user, repo, pull_request, per_page: 100) ⇒ Object
private
-
.pull_request_labels(user, repo, pull_request) ⇒ Object
private
-
.pull_request_title_regex(name, version = nil) ⇒ Object
private
-
.pull_requests(repo, **options) ⇒ Object
private
-
.repo_commits_for_user(nwo, user, filter, args, max) ⇒ Object
private
-
.repository(user, repo) ⇒ Object
private
-
.search(entity, *queries, **qualifiers) ⇒ Object
private
-
.search_issues(query, **qualifiers) ⇒ Object
private
-
.search_query_string(*main_params, **qualifiers) ⇒ Object
private
-
.search_results_count(entity, *queries, **qualifiers) ⇒ Object
private
-
.search_results_items(entity, *queries, **qualifiers) ⇒ Object
private
-
.sponsorships(user) ⇒ Array<Hash>
private
-
.upload_release_asset(user, repo, id, local_file: nil, remote_file: nil) ⇒ Object
private
-
.url_to(*subroutes) ⇒ Object
private
-
.user ⇒ Object
private
-
.workflow_dispatch_event(user, repo, workflow, ref, **inputs) ⇒ Object
private
-
.write_access?(repo, user = nil) ⇒ Boolean
private
Methods included from SystemCommand::Mixin
#system_command, #system_command!
Class Method Details
.approved_reviews(user, repo, pull_request, commit: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'utils/github.rb', line 191 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.map do |r| next if commit.present? && commit != r["commit"]["oid"] next unless valid_associations.include? r["authorAssociation"] email = r["author"]["email"].presence || "#{r["author"]["databaseId"]}+#{r["author"]["login"]}@users.noreply.github.com" name = r["author"]["name"].presence || r["author"]["login"] { "email" => email, "name" => name, "login" => r["author"]["login"], } end.compact end |
.branch_exists?(user, repo, branch) ⇒ 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.
78 79 80 81 82 83 |
# File 'utils/github.rb', line 78 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, state:, file:, args:, version: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
# File 'utils/github.rb', line 556 def self.check_for_duplicate_pull_requests(name, tap_remote_repo, state:, file:, args:, version: nil) # `fetch_open_pull_requests` is more reliable but *really* slow, so let's use it only in CI. pull_requests = if state == "open" && ENV["CI"].present? fetch_open_pull_requests(name, tap_remote_repo, version: version) else fetch_pull_requests(name, tap_remote_repo, state: state, version: version) end 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? = <<~EOS These #{state} pull requests may be duplicates: #{pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n")} EOS = "Duplicate PRs should not be opened. Use --force to override this error." if args.force? && !args.quiet? opoo elsif !args.force? && args.quiet? odie elsif !args.force? odie <<~EOS #{.chomp} #{} EOS end end |
.check_runs(repo: nil, commit: nil, pull_request: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
16 17 18 19 20 21 22 23 |
# File 'utils/github.rb', line 16 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 a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
39 40 41 |
# File 'utils/github.rb', line 39 def self.count_issues(query, **qualifiers) search_results_count("issues", query, **qualifiers) end |
.count_repo_commits(nwo, user, args, max: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
779 780 781 782 783 784 785 786 787 788 789 790 791 |
# File 'utils/github.rb', line 779 def self.count_repo_commits(nwo, user, args, max: nil) odie "Cannot count commits, HOMEBREW_NO_GITHUB_API set!" if Homebrew::EnvConfig.no_github_api? = repo_commits_for_user(nwo, user, "author", args, max) committer_shas = repo_commits_for_user(nwo, user, "committer", args, max) return [0, 0] if .blank? && committer_shas.blank? = .count # Only count commits where the author and committer are different. committer_count = committer_shas.difference().count [, committer_count] end |
.create_bump_pr(info, args:) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 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 688 689 690 691 692 693 694 695 696 697 698 699 700 |
# File 'utils/github.rb', line 609 def self.create_bump_pr(info, args:) tap = info[:tap] sourcefile_path = info[:sourcefile_path] old_contents = info[:old_contents] additional_files = info[:additional_files] || [] remote = info[:remote] || "origin" remote_branch = info[:remote_branch] || tap.git_repo.origin_branch_name branch = info[:branch_name] = info[:commit_message] previous_branch = info[:previous_branch] || "-" tap_remote_repo = info[:tap_remote_repo] || tap.full_name = info[:pr_message] sourcefile_path.parent.cd do git_dir = Utils.popen_read("git", "rev-parse", "--git-dir").chomp shallow = !git_dir.empty? && File.exist?("#{git_dir}/shallow") changed_files = [sourcefile_path] changed_files += additional_files if additional_files.present? if args.dry_run? || (args.write_only? && !args.commit?) remote_url = if args.no_fork? Utils.popen_read("git", "remote", "get-url", "--push", "origin").chomp else = "try to fork repository with GitHub API" \ "#{" into `#{args.fork_org}` organization" if args.fork_org}" ohai "FORK_URL" end ohai "git fetch --unshallow origin" if shallow ohai "git add #{changed_files.join(" ")}" ohai "git checkout --no-track -b #{branch} #{remote}/#{remote_branch}" ohai "git commit --no-edit --verbose --message='#{}' " \ "-- #{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 unless args.commit? if args.no_fork? remote_url = Utils.popen_read("git", "remote", "get-url", "--push", "origin").chomp username = tap.user else begin remote_url, username = forked_repo_info!(tap_remote_repo, org: args.fork_org) rescue *API::ERRORS => e sourcefile_path.atomic_write(old_contents) odie "Unable to fork: #{e.}!" end end safe_system "git", "fetch", "--unshallow", "origin" if shallow end safe_system "git", "add", *changed_files safe_system "git", "checkout", "--no-track", "-b", branch, "#{remote}/#{remote_branch}" unless args.commit? safe_system "git", "commit", "--no-edit", "--verbose", "--message=#{}", "--", *changed_files return if args.commit? system_command!("git", args: ["push", "--set-upstream", remote_url, "#{branch}:#{branch}"], print_stdout: true) safe_system "git", "checkout", "--quiet", previous_branch = <<~EOS #{} EOS = args. if = <<~EOS #{} --- #{} EOS end begin url = create_pull_request(tap_remote_repo, , "#{username}:#{branch}", remote_branch, )["html_url"] if args.no_browse? puts url else exec_browser url end rescue *API::ERRORS => e odie "Unable to open pull request: #{e.}!" end end end end |
.create_check_run(repo:, data:) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
25 26 27 |
# File 'utils/github.rb', line 25 def self.create_check_run(repo:, data:) API.open_rest(url_to("repos", repo, "check-runs"), data: data) end |
.create_fork(repo, org: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
120 121 122 123 124 125 126 |
# File 'utils/github.rb', line 120 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: data, scopes: scopes) end |
.create_gist(files, description, private:) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
43 44 45 46 47 |
# File 'utils/github.rb', line 43 def self.create_gist(files, description, private:) url = "#{API_URL}/gists" data = { "public" => !private, "files" => files, "description" => description } API.open_rest(url, data: data, scopes: CREATE_GIST_SCOPES)["html_url"] end |
.create_issue(repo, title, body) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
49 50 51 52 53 |
# File 'utils/github.rb', line 49 def self.create_issue(repo, title, body) url = "#{API_URL}/repos/#{repo}/issues" data = { "title" => title, "body" => body } API.open_rest(url, data: data, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)["html_url"] end |
.create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'utils/github.rb', line 263 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: draft, } data[:body] = body if body.present? API.open_rest(url, data: data, request_method: method, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES) end |
.create_pull_request(repo, title, head, base, body) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
139 140 141 142 143 144 |
# File 'utils/github.rb', line 139 def self.create_pull_request(repo, title, head, base, body) url = "#{API_URL}/repos/#{repo}/pulls" data = { title: title, head: head, base: base, body: body, maintainer_can_modify: true } scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES API.open_rest(url, data: data, scopes: scopes) end |
.dispatch_event(user, repo, event, **payload) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
232 233 234 235 236 237 |
# File 'utils/github.rb', line 232 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.
15 16 17 18 19 20 21 22 23 24 |
# File 'utils/github/artifacts.rb', line 15 def self.download_artifact(url, artifact_id) raise API::MissingAuthenticationError if API.credentials == :none # We use a download strategy here to leverage the Homebrew cache # to avoid repeated downloads of (possibly large) bottles. token = API.credentials downloader = GitHubArtifactDownloadStrategy.new(url, artifact_id, token: token) downloader.fetch downloader.stage end |
.fetch_open_pull_requests(name, tap_remote_repo, version: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
WARNING: The GitHub API returns results in a slightly different form here compared to fetch_pull_requests
.
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 |
# File 'utils/github.rb', line 530 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 owner, repo = tap_remote_repo.split("/") endpoint = "repos/#{owner}/#{repo}/pulls" query_parameters = ["state=open", "direction=desc"] pull_requests = [] API.paginate_rest("#{API_URL}/#{endpoint}", additional_query_params: query_parameters.join("&")) do |page| pull_requests.concat(page) end pull_requests end regex = pull_request_title_regex(name, version) @open_pull_requests[cache_key].select { |pr| regex.match?(pr["title"]) } end |
.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
517 518 519 520 521 522 523 524 525 526 527 |
# File 'utils/github.rb', line 517 def self.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil) regex = pull_request_title_regex(name, version) query = "is:pr #{name} #{version}".strip issues_for_formula(query, tap_remote_repo: tap_remote_repo, state: state).select do |pr| pr["html_url"].include?("/pull/") && regex.match?(pr["title"]) end rescue API::RateLimitExceededError => e opoo e. [] 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.
128 129 130 131 132 133 134 135 136 137 |
# File 'utils/github.rb', line 128 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 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.
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 |
# File 'utils/github.rb', line 592 def self.forked_repo_info!(tap_remote_repo, org: nil) response = create_fork(tap_remote_repo, org: org) # GitHub API responds immediately but fork takes a few seconds to be ready. sleep 1 until fork_exists?(tap_remote_repo, org: org) remote_url = if system("git", "config", "--local", "--get-regexp", "remote..*.url", "git@github.com:.*") response.fetch("ssh_url") else url = response.fetch("clone_url") if (api_token = Homebrew::EnvConfig.github_api_token) url.gsub!(%r{^https://github\.com/}, "https://#{api_token}@github.com/") end url end username = response.fetch("owner").fetch("login") [remote_url, username] end |
.generate_release_notes(user, repo, tag, previous_tag: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
256 257 258 259 260 261 |
# File 'utils/github.rb', line 256 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: data, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES) end |
.get_artifact_url(workflow_array) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
339 340 341 342 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 |
# File 'utils/github.rb', line 339 def self.get_artifact_url(workflow_array) check_suite, user, repo, pr, workflow_id, scopes, artifact_name = *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 = API.open_rest("#{API_URL}/repos/#{user}/#{repo}/actions/runs/#{run_id}/artifacts", scopes: scopes) artifact = artifacts["artifacts"].select do |art| art["name"] == artifact_name end if artifact.empty? raise API::Error, <<~EOS No artifact with the name `#{artifact_name}` was found! #{Formatter.url check_suite.last["workflowRun"]["url"]} EOS end artifact.last["archive_download_url"] end |
.get_latest_release(user, repo) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
251 252 253 254 |
# File 'utils/github.rb', line 251 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 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.
588 589 590 |
# File 'utils/github.rb', line 588 def self.get_pull_request_changed_files(tap_remote_repo, pull_request) API.open_rest(url_to("repos", tap_remote_repo, "pulls", pull_request, "files")) end |
.get_release(user, repo, tag) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
246 247 248 249 |
# File 'utils/github.rb', line 246 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) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
500 501 502 503 504 505 506 507 508 509 |
# File 'utils/github.rb', line 500 def self.get_repo_license(user, repo) response = API.open_rest("#{API_URL}/repos/#{user}/#{repo}/license") return unless response.key?("license") response["license"]["spdx_id"] rescue API::HTTPNotFoundError nil rescue API::AuthenticationFailedError => e raise unless e..match?(API::GITHUB_IP_ALLOWLIST_ERROR) end |
.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_name: "bottles") ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
286 287 288 289 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 |
# File 'utils/github.rb', line 286 def self.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_name: "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: 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: user, repo: repo, pr: pull_request.to_i, } result = API.open_graphql(query, variables: variables, scopes: 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_name] end |
.issues(repo:, **filters) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
29 30 31 32 33 |
# File 'utils/github.rb', line 29 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 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.
59 60 61 62 63 |
# File 'utils/github.rb', line 59 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: state, type: type, in: "title") end |
.last_commit(user, repo, ref, version) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 |
# File 'utils/github.rb', line 728 def self.last_commit(user, repo, ref, version) return if Homebrew::EnvConfig.no_github_api? output, _, status = Utils::Curl.curl_output( "--silent", "--head", "--location", "--header", "Accept: application/vnd.github.sha", url_to("repos", user, repo, "commits", ref).to_s ) return unless status.success? commit = output[/^ETag: "(\h+)"/, 1] return if commit.blank? version.update_commit(commit) commit end |
.members_by_team(org, team) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
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 |
# File 'utils/github.rb', line 386 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 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.
90 91 92 93 94 95 |
# File 'utils/github.rb', line 90 def self.merge_pull_request(repo, number:, sha:, merge_method:, commit_message: nil) url = "#{API_URL}/repos/#{repo}/pulls/#{number}/merge" data = { sha: sha, merge_method: merge_method } data[:commit_message] = if API.open_rest(url, data: 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 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.
746 747 748 749 750 751 752 753 754 755 756 757 758 759 |
# File 'utils/github.rb', line 746 def self.multiple_short_commits_exist?(user, repo, commit) return if Homebrew::EnvConfig.no_github_api? output, _, status = 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 status.success? return true if output.blank? output[/^Status: (200)/, 1] != "200" end |
.pat_blurb(scopes = ALL_SCOPES) ⇒ Object
10 11 12 13 14 15 16 17 18 |
# File 'utils/github/api.rb', line 10 def self.pat_blurb(scopes = ALL_SCOPES) <<~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 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.
69 70 71 |
# File 'utils/github.rb', line 69 def self.(repo, user) API.open_rest("#{API_URL}/repos/#{repo}/collaborators/#{user}/permission") end |
.print_pull_requests_matching(query, only = nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'utils/github.rb', line 97 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.
146 147 148 149 |
# File 'utils/github.rb', line 146 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 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.
374 375 376 377 378 379 380 381 382 383 384 |
# File 'utils/github.rb', line 374 def self.public_member_usernames(org, per_page: 100) url = "#{API_URL}/orgs/#{org}/public_members" members = [] API.paginate_rest(url, per_page: per_page) do |result| result = result.map { |member| member["login"] } members.concat(result) return members if result.length < per_page end end |
.pull_request_commits(user, repo, pull_request, per_page: 100) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 |
# File 'utils/github.rb', line 702 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: 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 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.
723 724 725 726 |
# File 'utils/github.rb', line 723 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 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.
511 512 513 514 515 |
# File 'utils/github.rb', line 511 def self.pull_request_title_regex(name, version = nil) return /(^|\s)#{Regexp.quote(name)}(:|,|\s|$)/i.freeze if version.blank? /(^|\s)#{Regexp.quote(name)}(:|,|\s)(.*\s)?#{Regexp.quote(version)}(:|,|\s|$)/i.freeze end |
.pull_requests(repo, **options) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
85 86 87 88 |
# File 'utils/github.rb', line 85 def self.pull_requests(repo, **) url = "#{API_URL}/repos/#{repo}/pulls?#{URI.encode_www_form()}" API.open_rest(url) end |
.repo_commits_for_user(nwo, user, filter, args, max) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 |
# File 'utils/github.rb', line 761 def self.repo_commits_for_user(nwo, user, filter, args, max) return if Homebrew::EnvConfig.no_github_api? params = ["#{filter}=#{user}"] params << "since=#{DateTime.parse(args.from).iso8601}" if args.from params << "until=#{DateTime.parse(args.to).iso8601}" if args.to 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 a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
55 56 57 |
# File 'utils/github.rb', line 55 def self.repository(user, repo) API.open_rest(url_to("repos", user, repo)) end |
.search(entity, *queries, **qualifiers) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
175 176 177 178 179 |
# File 'utils/github.rb', line 175 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 a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
35 36 37 |
# File 'utils/github.rb', line 35 def self.search_issues(query, **qualifiers) search_results_items("issues", query, **qualifiers) end |
.search_query_string(*main_params, **qualifiers) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'utils/github.rb', line 151 def self.search_query_string(*main_params, **qualifiers) params = main_params if (args = qualifiers.fetch(:args, nil)) params << if args.from && args.to "created:#{args.from}..#{args.to}" elsif args.from "created:>=#{args.from}" elsif args.to "created:<=#{args.to}" end end params += qualifiers.except(:args).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 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.
186 187 188 189 |
# File 'utils/github.rb', line 186 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 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.
181 182 183 184 |
# File 'utils/github.rb', line 181 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.
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 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 |
# File 'utils/github.rb', line 426 def self.sponsorships(user) has_next_page = T.let(true, T::Boolean) after = "" sponsorships = T.let([], T::Array[Hash]) errors = T.let([], T::Array[Hash]) while has_next_page query = <<~EOS { organization(login: "#{user}") { sponsorshipsAsMaintainer(first: 100 #{after}) { pageInfo { startCursor hasNextPage endCursor } totalCount nodes { tier { monthlyPriceInDollars closestLesserValueTier { monthlyPriceInDollars } } sponsorEntity { __typename ... on Organization { login name } ... on User { login name } } } } } } EOS # 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. result = API.open_graphql(query, scopes: ["user"], raise_errors: false) errors += result["errors"] if result["errors"].present? current_sponsorships = result["data"]["organization"]["sponsorshipsAsMaintainer"] # The organisations mentioned above will show up as nil nodes. if (nodes = current_sponsorships["nodes"].compact.presence) sponsorships += nodes end if (page_info = current_sponsorships["pageInfo"].presence) && page_info["hasNextPage"].presence after = %Q(, after: "#{page_info["endCursor"]}") else has_next_page = false end end # Only raise errors if we didn't get any sponsorships. if sponsorships.blank? && errors.present? raise API::Error, errors.map { |e| "#{e["type"]}: #{e["message"]}" }.join("\n") end 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: monthly_amount, closest_tier_monthly_amount: closest_tier_monthly_amount, } end end |
.upload_release_asset(user, repo, id, local_file: nil, remote_file: nil) ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
280 281 282 283 284 |
# File 'utils/github.rb', line 280 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 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.
171 172 173 |
# File 'utils/github.rb', line 171 def self.url_to(*subroutes) URI.parse([API_URL, *subroutes].join("/")) end |
.user ⇒ Object
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
65 66 67 |
# File 'utils/github.rb', line 65 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 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.
239 240 241 242 243 244 |
# File 'utils/github.rb', line 239 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: ref, inputs: inputs }, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES) end |
.write_access?(repo, user = nil) ⇒ Boolean
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
73 74 75 76 |
# File 'utils/github.rb', line 73 def self.write_access?(repo, user = nil) user ||= self.user["login"] ["admin", "write"].include?((repo, user)["permission"]) end |