Class: Homebrew::DevCmd::PrPull Private

Inherits:
AbstractCommand show all
Includes:
FileUtils
Defined in:
sorbet/rbi/dsl/homebrew/dev_cmd/pr_pull.rbi,
dev-cmd/pr-pull.rb

Overview

This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

DO NOT EDIT MANUALLY This is an autogenerated file for dynamic methods in Homebrew::DevCmd::PrPull. Please instead update this file by running bin/tapioca dsl Homebrew::DevCmd::PrPull.

Defined Under Namespace

Classes: Args

Instance Method Summary collapse

Methods inherited from AbstractCommand

command, command_name, dev_cmd?, #initialize, parser

Constructor Details

This class inherits a constructor from Homebrew::AbstractCommand

Instance Method Details

#argsHomebrew::DevCmd::PrPull::Args

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.



9
# File 'sorbet/rbi/dsl/homebrew/dev_cmd/pr_pull.rbi', line 9

def args; end

#autosquash!(original_commit, tap:, reason: "", verbose: false, resolve: false, cherry_picked: true) ⇒ 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.

TODO:

fix test in test/dev-cmd/pr-pull_spec.rb and assume cherry_picked: false.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
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
# File 'dev-cmd/pr-pull.rb', line 348

def autosquash!(original_commit, tap:, reason: "", verbose: false, resolve: false, cherry_picked: true)
  git_repo = tap.git_repo
  original_head = git_repo.head_ref

  commits = Utils.safe_popen_read("git", "-C", tap.path, "rev-list",
                                  "--reverse", "#{original_commit}..HEAD").lines.map(&:strip)

  # Generate a bidirectional mapping of commits <=> formula/cask files.
  files_to_commits = {}
  commits_to_files = commits.to_h do |commit|
    files = Utils.safe_popen_read("git", "-C", tap.path, "diff-tree", "--diff-filter=AMD",
                                  "-r", "--name-only", "#{commit}^", commit).lines.map(&:strip)
    files.each do |file|
      files_to_commits[file] ||= []
      files_to_commits[file] << commit
      tap_file = (tap.path/file).to_s
      if (tap_file.start_with?("#{tap.formula_dir}/") || tap_file.start_with?("#{tap.cask_dir}/")) &&
         File.extname(file) == ".rb"
        next
      end

      odie <<~EOS
        Autosquash can only squash commits that modify formula or cask files.
          File:   #{file}
          Commit: #{commit}
      EOS
    end
    [commit, files]
  end

  # Reset to state before cherry-picking.
  safe_system "git", "-C", tap.path, "reset", "--hard", original_commit

  # Iterate over every commit in the pull request series, but if we have to squash
  # multiple commits into one, ensure that we skip over commits we've already squashed.
  processed_commits = T.let([], T::Array[String])
  commits.each do |commit|
    next if processed_commits.include? commit

    files = commits_to_files[commit]
    if files.length == 1 && files_to_commits[files.first].length == 1
      # If there's a 1:1 mapping of commits to files, just cherry pick and (maybe) reword.
      reword_package_commit(
        commit, files.first, git_repo:, reason:, verbose:, resolve:
      )
      processed_commits << commit
    elsif files.length == 1 && files_to_commits[files.first].length > 1
      # If multiple commits modify a single file, squash them down into a single commit.
      file = files.first
      commits = files_to_commits[file]
      squash_package_commits(commits, file, git_repo:, reason:, verbose:, resolve:)
      processed_commits += commits
    else
      # We can't split commits (yet) so just raise an error.
      odie <<~EOS
        Autosquash can't split commits that modify multiple files.
          Commit: #{commit}
          Files:  #{files.join " "}
      EOS
    end
  end
rescue
  opoo "Autosquash encountered an error; resetting to original state at #{original_head}"
  system "git", "-C", tap.path, "reset", "--hard", original_head
  system "git", "-C", tap.path, "cherry-pick", "--abort" if cherry_picked
  raise
end

#determine_bump_subject(old_contents, new_contents, subject_path, reason: 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.



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'dev-cmd/pr-pull.rb', line 248

def determine_bump_subject(old_contents, new_contents, subject_path, reason: nil)
  subject_path = Pathname(subject_path)
  tap          = Tap.from_path(subject_path)
  subject_name = subject_path.basename.to_s.chomp(".rb")
  is_cask      = subject_path.to_s.start_with?("#{tap.cask_dir}/")
  name         = is_cask ? "cask" : "formula"

  new_package = get_package(tap, subject_name, subject_path, new_contents)

  return "#{subject_name}: delete #{reason}".strip if new_package.blank?

  old_package = get_package(tap, subject_name, subject_path, old_contents)

  if old_package.blank?
    "#{subject_name} #{new_package.version} (new #{name})"
  elsif old_package.version != new_package.version
    "#{subject_name} #{new_package.version}"
  elsif !is_cask && old_package.revision != new_package.revision
    "#{subject_name}: revision #{reason}".strip
  elsif is_cask && old_package.sha256 != new_package.sha256
    "#{subject_name}: checksum update #{reason}".strip
  else
    "#{subject_name}: #{reason || "rebuild"}".strip
  end
end

#get_package(tap, subject_name, subject_path, content) ⇒ 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.



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'dev-cmd/pr-pull.rb', line 231

def get_package(tap, subject_name, subject_path, content)
  if subject_path.to_s.start_with?("#{tap.cask_dir}/")
    cask = begin
      Cask::CaskLoader.load(content.dup)
    rescue Cask::CaskUnavailableError
      nil
    end
    return cask
  end

  begin
    Formulary.from_contents(subject_name, subject_path, content, :stable)
  rescue FormulaUnavailableError
    nil
  end
end

#reword_package_commit(commit, file, git_repo:, reason: "", verbose: false, resolve: 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.

Cherry picks a single commit that modifies a single file. Potentially rewords this commit using #determine_bump_subject.



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'dev-cmd/pr-pull.rb', line 276

def reword_package_commit(commit, file, git_repo:, reason: "", verbose: false, resolve: false)
  package_file = git_repo.pathname / file
  package_name = package_file.basename.to_s.chomp(".rb")

  odebug "Cherry-picking #{package_file}: #{commit}"
  Utils::Git.cherry_pick!(git_repo.to_s, commit, verbose:, resolve:)

  old_package = Utils::Git.file_at_commit(git_repo.to_s, file, "HEAD^")
  new_package = Utils::Git.file_at_commit(git_repo.to_s, file, "HEAD")

  bump_subject = determine_bump_subject(old_package, new_package, package_file, reason:).strip
  subject, body, trailers = separate_commit_message(git_repo.commit_message)

  if subject != bump_subject && !subject.start_with?("#{package_name}:")
    safe_system("git", "-C", git_repo.pathname, "commit", "--amend", "-q",
                "-m", bump_subject, "-m", subject, "-m", body, "-m", trailers)
    ohai bump_subject
  else
    ohai subject
  end
end

#runvoid

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.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
161
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
# File 'dev-cmd/pr-pull.rb', line 79

def run
  # Needed when extracting the CI artifact.
  ensure_executable!("unzip", reason: "extracting CI artifacts")

  workflows = args.workflows.presence || ["tests.yml"]
  artifact_pattern = args.artifact_pattern || "bottles{,_*}"
  tap = Tap.fetch(args.tap || CoreTap.instance.name)
  raise TapUnavailableError, tap.name unless tap.installed?

  Utils::Git.set_name_email!(committer: args.committer.blank?)
  Utils::Git.setup_gpg!

  if (committer = args.committer)
    committer = Utils.parse_author!(committer)
    ENV["GIT_COMMITTER_NAME"] = committer[:name]
    ENV["GIT_COMMITTER_EMAIL"] = committer[:email]
  end

  args.named.uniq.each do |arg|
    arg = "#{tap.default_remote}/pull/#{arg}" if arg.to_i.positive?
    url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX
    _, user, repo, pr = *url_match
    odie "Not a GitHub pull request: #{arg}" unless pr

    git_repo = tap.git_repo
    if !git_repo.default_origin_branch? && !args.branch_okay? && !args.no_commit? && !args.no_cherry_pick?
      origin_branch_name = git_repo.origin_branch_name
      opoo "Current branch is #{git_repo.branch_name}: do you need to pull inside #{origin_branch_name}?"
    end

    pr_labels = GitHub.pull_request_labels(user, repo, pr)
    if pr_labels.include?("autosquash") && !args.autosquash?
      opoo "Pull request is labelled `autosquash`: do you need to pass `--autosquash`?"
    end

    pr_check_conflicts("#{user}/#{repo}", pr)

    ohai "Fetching #{tap} pull request ##{pr}"
    dir = Dir.mktmpdir("pr-pull-#{pr}-", HOMEBREW_TEMP)
    begin
      cd dir do
        current_branch_head = ENV["GITHUB_SHA"] || tap.git_head
        original_commit = if args.no_cherry_pick?
          # TODO: Handle the case where `merge-base` returns multiple commits.
          Utils.safe_popen_read("git", "-C", tap.path, "merge-base", "origin/HEAD",
                                current_branch_head).strip
        else
          current_branch_head
        end
        odebug "Pull request merge-base: #{original_commit}"

        unless args.no_commit?
          cherry_pick_pr!(user, repo, pr, path: tap.path) unless args.no_cherry_pick?
          if args.autosquash? && !args.dry_run?
            autosquash!(original_commit, tap:, cherry_picked: !args.no_cherry_pick?,
                        verbose: args.verbose?, resolve: args.resolve?, reason: args.message)
          end
          signoff!(git_repo, pull_request: pr, dry_run: args.dry_run?) unless args.clean?
        end

        unless formulae_need_bottles?(tap, original_commit, pr_labels)
          ohai "Skipping artifacts for ##{pr} as the formulae don't need bottles"
          next
        end

        workflows.each do |workflow|
          workflow_run = GitHub.get_workflow_run(
            user, repo, pr, workflow_id: workflow, artifact_pattern:
          )
          if args.ignore_missing_artifacts.present? &&
             T.must(args.ignore_missing_artifacts).include?(workflow) &&
             workflow_run.first.blank?
            # Ignore that workflow as it was not executed and we specified
            # that we could skip it.
            ohai "Ignoring workflow #{workflow} as requested by `--ignore-missing-artifacts`"
            next
          end

          ohai "Downloading bottles for workflow: #{workflow}"

          urls = GitHub.get_artifact_urls(workflow_run)
          urls.each { |url| GitHub.download_artifact(url, pr) }
        end

        next if args.no_upload?

        upload_args = ["pr-upload"]
        upload_args << "--debug" if args.debug?
        upload_args << "--verbose" if args.verbose?
        upload_args << "--no-commit" if args.no_commit?
        upload_args << "--dry-run" if args.dry_run?
        upload_args << "--keep-old" if args.keep_old?
        upload_args << "--warn-on-upload-failure" if args.warn_on_upload_failure?
        upload_args << "--committer=#{args.committer}" if args.committer
        upload_args << "--root-url=#{args.root_url}" if args.root_url
        upload_args << "--root-url-using=#{args.root_url_using}" if args.root_url_using
        safe_system HOMEBREW_BREW_FILE, *upload_args
      end
    ensure
      if args.retain_bottle_dir? && ENV["GITHUB_ACTIONS"]
        ohai "Bottle files retained at:", dir
        File.open(ENV.fetch("GITHUB_OUTPUT"), "a") do |f|
          f.puts "bottle_path=#{dir}"
        end
      else
        FileUtils.remove_entry dir
      end
    end
  end
end

#separate_commit_message(message) ⇒ 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.

Separates a commit message into subject, body and trailers.



191
192
193
194
195
196
197
198
199
200
201
202
# File 'dev-cmd/pr-pull.rb', line 191

def separate_commit_message(message)
  subject = message.lines.first.strip

  # Skip the subject and separate lines that look like trailers (e.g. "Co-authored-by")
  # from lines that look like regular body text.
  trailers, body = message.lines.drop(1).partition { |s| s.match?(/^[a-z-]+-by:/i) }

  trailers = trailers.uniq.join.strip
  body = body.join.strip.gsub(/\n{3,}/, "\n\n")

  [subject, body, trailers]
end

#signoff!(git_repo, pull_request: nil, dry_run: 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.



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
# File 'dev-cmd/pr-pull.rb', line 204

def signoff!(git_repo, pull_request: nil, dry_run: false)
  subject, body, trailers = separate_commit_message(git_repo.commit_message)

  if pull_request
    # This is a tap pull request and approving reviewers should also sign-off.
    tap = Tap.from_path(git_repo.pathname)
    review_trailers = GitHub.approved_reviews(tap.user, tap.full_name.split("/").last,
                                              pull_request).map do |r|
      "Signed-off-by: #{r["name"]} <#{r["email"]}>"
    end
    trailers = trailers.lines.concat(review_trailers).map(&:strip).uniq.join("\n")

    # Append the close message as well, unless the commit body already includes it.
    close_message = "Closes ##{pull_request}."
    body += "\n\n#{close_message}" unless body.include? close_message
  end

  git_args = Utils::Git.git, "-C", git_repo.pathname, "commit", "--amend", "--signoff", "--allow-empty",
             "--quiet", "--message", subject, "--message", body, "--message", trailers

  if dry_run
    puts(*git_args)
  else
    safe_system(*git_args)
  end
end

#squash_package_commits(commits, file, git_repo:, reason: "", verbose: false, resolve: 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.

Cherry picks multiple commits that each modify a single file. Words the commit according to #determine_bump_subject with the body corresponding to all the original commit messages combined.



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'dev-cmd/pr-pull.rb', line 301

def squash_package_commits(commits, file, git_repo:, reason: "", verbose: false, resolve: false)
  odebug "Squashing #{file}: #{commits.join " "}"

  # Format commit messages into something similar to `git fmt-merge-message`.
  # * subject 1
  # * subject 2
  #   optional body
  # * subject 3
  messages = []
  trailers = []
  commits.each do |commit|
    subject, body, trailer = separate_commit_message(git_repo.commit_message(commit))
    body = body.lines.map { |line| "  #{line.strip}" }.join("\n")
    messages << "* #{subject}\n#{body}".strip
    trailers << trailer
  end

  # Get the set of authors in this series.
  authors = Utils.safe_popen_read("git", "-C", git_repo.pathname, "show",
                                  "--no-patch", "--pretty=%an <%ae>", *commits).lines.map(&:strip).uniq.compact

  # Get the author and date of the first commit of this series, which we use for the squashed commit.
  original_author = authors.shift
  original_date = Utils.safe_popen_read "git", "-C", git_repo.pathname, "show", "--no-patch", "--pretty=%ad",
                                        commits.first

  # Generate trailers for coauthors and combine them with the existing trailers.
  co_author_trailers = authors.map { |au| "Co-authored-by: #{au}" }
  trailers = [trailers + co_author_trailers].flatten.uniq.compact

  # Apply the patch series but don't commit anything yet.
  Utils::Git.cherry_pick!(git_repo.pathname, "--no-commit", *commits, verbose:, resolve:)

  # Determine the bump subject by comparing the original state of the tree to its current state.
  package_file = git_repo.pathname / file
  old_package = Utils::Git.file_at_commit(git_repo.pathname, file, "#{commits.first}^")
  new_package = package_file.read
  bump_subject = determine_bump_subject(old_package, new_package, package_file, reason:)

  # Commit with the new subject, body and trailers.
  safe_system("git", "-C", git_repo.pathname, "commit", "--quiet",
              "-m", bump_subject, "-m", messages.join("\n"), "-m", trailers.join("\n"),
              "--author", original_author, "--date", original_date, "--", file)
  ohai bump_subject
end