Module: GitHub

Defined in:
brew/Library/Homebrew/dev-cmd/pull.rb,
brew/Library/Homebrew/utils/github.rb

Defined Under Namespace

Classes: AuthenticationFailedError, Error, HTTPNotFoundError, RateLimitExceededError, ValidationFailedError

Constant Summary collapse

API_URL =
"https://api.github.com"
CREATE_GIST_SCOPES =
["gist"].freeze
CREATE_ISSUE_FORK_OR_PR_SCOPES =
["public_repo"].freeze
ALL_SCOPES =
(CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES).freeze
ALL_SCOPES_URL =
Formatter.url(
  "https://github.com/settings/tokens/new?scopes=#{ALL_SCOPES.join(",")}&description=Homebrew",
).freeze
PR_ENV_KEY =
"HOMEBREW_NEW_FORMULA_PULL_REQUEST_URL"
PR_ENV =
ENV[PR_ENV_KEY]

Class Method Summary collapse

Class Method Details

.api_credentialsObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'brew/Library/Homebrew/utils/github.rb', line 82

def api_credentials
  @api_credentials ||= begin
    if ENV["HOMEBREW_GITHUB_API_TOKEN"]
      ENV["HOMEBREW_GITHUB_API_TOKEN"]
    elsif ENV["HOMEBREW_GITHUB_API_USERNAME"] && ENV["HOMEBREW_GITHUB_API_PASSWORD"]
      [ENV["HOMEBREW_GITHUB_API_PASSWORD"], ENV["HOMEBREW_GITHUB_API_USERNAME"]]
    else
      github_credentials = api_credentials_from_keychain
      github_username = github_credentials[/username=(.+)/, 1]
      github_password = github_credentials[/password=(.+)/, 1]
      if github_username && github_password
        [github_password, github_username]
      else
        []
      end
    end
  end
end

.api_credentials_error_message(response_headers, needed_scopes) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'brew/Library/Homebrew/utils/github.rb', line 123

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

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

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

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

.api_credentials_from_keychainObject



101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'brew/Library/Homebrew/utils/github.rb', line 101

def api_credentials_from_keychain
  Utils.popen(["git", "credential-osxkeychain", "get"], "w+") do |pipe|
    pipe.write "protocol=https\nhost=github.com\n"
    pipe.close_write
    pipe.read
  end
rescue Errno::EPIPE
  # The above invocation via `Utils.popen` can fail, causing the pipe to be
  # prematurely closed (before we can write to it) and thus resulting in a
  # broken pipe error. The root cause is usually a missing or malfunctioning
  # `git-credential-osxkeychain` helper.
  ""
end

.api_credentials_typeObject



115
116
117
118
119
120
121
# File 'brew/Library/Homebrew/utils/github.rb', line 115

def api_credentials_type
  token, username = api_credentials
  return :none if !token || token.empty?
  return :environment if !username || username.empty?

  :keychain
end

.api_errorsObject



401
402
403
404
# File 'brew/Library/Homebrew/utils/github.rb', line 401

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

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



265
266
267
268
269
270
271
272
# File 'brew/Library/Homebrew/utils/github.rb', line 265

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

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

.create_fork(repo) ⇒ Object



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

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

.create_issue_comment(body) ⇒ Object



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

def create_issue_comment(body)
  return false unless PR_ENV

  _, user, repo, pr = *PR_ENV.match(HOMEBREW_PULL_OR_COMMIT_URL_REGEX)
  if !user || !repo || !pr
    opoo <<-EOS.undent
      #{PR_ENV_KEY} set but regex matched:
      user: #{user.inspect}, repo: #{repo.inspect}, pr: #{pr.inspect}
    EOS
    return false
  end

  url = "#{API_URL}/repos/#{user}/#{repo}/issues/#{pr}/comments"
  data = { "body" => body }
  if issue_comment_exists?(user, repo, pr, body)
    ohai "Skipping: identical comment exists on #{PR_ENV}"
    return true
  end

  scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
  open_api(url, data: data, scopes: scopes)
end

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



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

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

.issue_comment_exists?(user, repo, pr, body) ⇒ Boolean

Returns:

  • (Boolean)


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

def issue_comment_exists?(user, repo, pr, body)
  url = "#{API_URL}/repos/#{user}/#{repo}/issues/#{pr}/comments"
  comments = open_api(url)
  return unless comments

  comments.any? { |comment| comment["body"].eql?(body) }
end

.issues_for_formula(name, options = {}) ⇒ Object



286
287
288
289
# File 'brew/Library/Homebrew/utils/github.rb', line 286

def issues_for_formula(name, options = {})
  tap = options[:tap] || CoreTap.instance
  search_issues(name, state: "open", repo: tap.full_name, in: "title")
end

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



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

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

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



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'brew/Library/Homebrew/utils/github.rb', line 162

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

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

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

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

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

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

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

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

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

    return if http_code == "204" # No Content

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

.permission(repo, user) ⇒ Object



295
296
297
# File 'brew/Library/Homebrew/utils/github.rb', line 295

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


316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'brew/Library/Homebrew/utils/github.rb', line 316

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

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

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

.private_repo?(full_name) ⇒ Boolean

Returns:

  • (Boolean)


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

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

.pull_requests(repo, **options) ⇒ Object



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

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

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



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

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

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

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

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



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'brew/Library/Homebrew/utils/github.rb', line 228

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

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

    meta[key] = value.strip
  end

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

  GitHub.api_credentials_error_message(meta, scopes)

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

.repository(user, repo) ⇒ Object



278
279
280
# File 'brew/Library/Homebrew/utils/github.rb', line 278

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

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



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

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

.search_code(**qualifiers) ⇒ Object



282
283
284
# File 'brew/Library/Homebrew/utils/github.rb', line 282

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

.search_issues(query, **qualifiers) ⇒ Object



274
275
276
# File 'brew/Library/Homebrew/utils/github.rb', line 274

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

.test_bot_user(user, test_bot) ⇒ Object

Return the corresponding test-bot user name for the given GitHub organization.



18
19
20
21
22
23
# File 'brew/Library/Homebrew/dev-cmd/pull.rb', line 18

def test_bot_user(user, test_bot)
  return test_bot if test_bot
  return "BrewTestBot" if user.casecmp("homebrew").zero?

  "#{user.capitalize}TestBot"
end

.url_to(*subroutes) ⇒ Object



360
361
362
# File 'brew/Library/Homebrew/utils/github.rb', line 360

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

.userObject



291
292
293
# File 'brew/Library/Homebrew/utils/github.rb', line 291

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

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

Returns:

  • (Boolean)


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

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