Skip to content

Commit f4b234c

Browse files
authored
cli: try squash merge first, fall back to merge commit if not allowed (#25609)
1 parent ae3de6f commit f4b234c

1 file changed

Lines changed: 26 additions & 5 deletions

File tree

pkg/cli/add_interactive_git.go

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,34 @@ func (c *AddInteractiveConfig) checkCleanWorkingDirectory() error {
279279
return nil
280280
}
281281

282-
// mergePullRequest merges the specified PR
282+
// squashMergeNotAllowedErr is the lowercase substring of the GitHub GraphQL API error
283+
// returned when a repository does not permit squash merges. It is used to detect when
284+
// a squash merge should be retried with a merge-commit strategy.
285+
const squashMergeNotAllowedErr = "squash merges are not allowed"
286+
287+
// mergePullRequest merges the specified PR, attempting a squash merge first and
288+
// falling back to a merge commit if squash merges are not allowed on the repository.
283289
func (c *AddInteractiveConfig) mergePullRequest(prNumber int) error {
284-
output, err := workflow.RunGHCombined("Merging pull request...", "pr", "merge", strconv.Itoa(prNumber), "--repo", c.RepoOverride, "--merge")
285-
if err != nil {
286-
return fmt.Errorf("merge failed: %w (output: %s)", err, string(output))
290+
prArg := strconv.Itoa(prNumber)
291+
squashOutput, squashErr := workflow.RunGHCombined("Merging pull request (squash)...", "pr", "merge", prArg, "--repo", c.RepoOverride, "--squash")
292+
if squashErr == nil {
293+
return nil
287294
}
288-
return nil
295+
296+
// If squash merges are not allowed on this repository (e.g. only merge commits or rebase
297+
// merges are enabled), fall back to a merge commit. The error text comes from the GitHub
298+
// GraphQL API and is surfaced verbatim in the gh CLI output.
299+
combinedText := strings.ToLower(string(squashOutput) + squashErr.Error())
300+
if strings.Contains(combinedText, squashMergeNotAllowedErr) {
301+
fmt.Fprintln(os.Stderr, console.FormatInfoMessage("Squash merges are not allowed on this repository, retrying with merge commit"))
302+
mergeOutput, mergeErr := workflow.RunGHCombined("Merging pull request...", "pr", "merge", prArg, "--repo", c.RepoOverride, "--merge")
303+
if mergeErr != nil {
304+
return fmt.Errorf("merge failed: %w (output: %s)", mergeErr, string(mergeOutput))
305+
}
306+
return nil
307+
}
308+
309+
return fmt.Errorf("merge failed: %w (output: %s)", squashErr, string(squashOutput))
289310
}
290311

291312
// editPRTitle updates the title of the specified PR via the gh CLI.

0 commit comments

Comments
 (0)