feat: add --admin, --match-head-commit, --disable-auto, --required and --fill-first/--fill-verbose to the pr commands (#97)

`gh pr merge`, `checks` and `create` have options that `gt pr` lacked:

- `gt pr merge --admin` merges past the branch protection (Gitea's `force_merge`, for those who administer the repository). `--match-head-commit SHA` merges only while the head is still that commit and fails with the `head_mismatch` exit status otherwise, so a push after the review is not merged unseen. `--disable-auto` cancels the merge that `--auto` scheduled and merges nothing; with none scheduled it says so.
- `gt pr checks --required` shows and awaits only the checks that the protection rule of the base branch requires (`effective_branch_protection_name`, then its `status_check_contexts`, where `*` and `?` match). A flaky optional check no longer holds `--watch` back, and a branch that requires none has nothing to show.
- `gt pr create --fill-first` takes the title and body from the first commit of the branch whatever their number; `--fill-verbose` takes the body from the full message of every commit, oldest first. `--fill` is unchanged. `--fill`, `--fill-first` and `--fill-verbose` cannot be combined, like gh.

`gh pr checks --fail-fast` is not added: `gt pr checks --watch` already stops at the first failure.

Tested against fake servers, and on the disposable Gitea 28 instance by three integration tests: a merge with a moved head, an administrator merging past a protection that wants an approval, a scheduled merge that is canceled and then does not happen, required against optional checks with `--watch`, and `--fill-first` and `--fill-verbose` from a real clone. The test of the cancel showed that Gitea answers a cancel with nothing scheduled with the same bare 404 as for a missing pull request, which the code now reads as "nothing scheduled".

---------

Co-authored-by: bircni <[email protected]>
Reviewed-on: https://gitea.com/gitea/cli/pulls/97
Reviewed-by: bircni <[email protected]>
Co-authored-by: Lunny Xiao <[email protected]>
This commit is contained in:
Lunny Xiao
2026-11-09 22:17:44 +00:00
committed by bircni
co-authored by bircni
parent 4dec73db35
commit 44a4491137
17 changed files with 860 additions and 39 deletions
+1
View File
@@ -17,6 +17,7 @@ require (
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/x/ansi v0.11.9
github.com/davidmz/go-pageant v1.0.2
github.com/gobwas/glob v1.1.0
github.com/itchyny/gojq v0.12.20
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/mattn/go-runewidth v0.0.31
+2
View File
@@ -78,6 +78,8 @@ github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxK
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gobwas/glob v1.1.0 h1:CS8tIr7+5fu50N+tKsQy3osOU5jmhjHv0/ildcKAn2Q=
github.com/gobwas/glob v1.1.0/go.mod h1:5OYLTTNYHcww+D/XwWAjGpmIE8sD41kWneKyzWkK7/k=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+14 -4
View File
@@ -18,19 +18,25 @@ import (
)
func (a *application) pullChecksCommand() *cobra.Command {
var watch, web bool
var watch, web, required bool
var interval, timeout time.Duration
cmd := &cobra.Command{Use: "checks [<number> | <url> | <branch>]", Short: "Show the status checks of a pull request", Long: `Show the latest status of each check of a pull request's head commit.
gt exits with 8 while checks are pending and with 1 when a check failed, like gh. With
--watch, it waits until every check finished, or one failed, and polls on through an outage of
the instance of up to 5 minutes.`, Annotations: pullArgumentsAnnotation(nil), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) error {
the instance of up to 5 minutes. With --required, only the checks that the branch protection of the
base branch requires are shown and awaited, so that a flaky optional check does not hold a merge
back. A required check that has not reported yet is pending under the name of its pattern, a rule
without patterns requires every check, and gt fails when the base branch requires none.`, Annotations: pullArgumentsAnnotation(nil), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) error {
if interval <= 0 || timeout <= 0 {
return clierr.Wrap(clierr.Usage, errors.New("--interval and --timeout must be positive"))
}
if web && watch {
return clierr.Wrap(clierr.Usage, errors.New("--watch cannot be combined with --web"))
}
if web && required {
return clierr.Wrap(clierr.Usage, errors.New("--required cannot be combined with --web"))
}
for _, name := range []string{"interval", "timeout"} {
if !watch && cmd.Flags().Changed(name) {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--%s requires --watch", name))
@@ -55,7 +61,7 @@ the instance of up to 5 minutes.`, Annotations: pullArgumentsAnnotation(nil), Ar
redraw, leave := a.checksRedraw(cmd, interval)
defer leave()
var latest []services.Check
items, err = service.WatchChecks(ctx, n, interval, func(current []services.Check) error {
items, err = service.WatchChecks(ctx, n, interval, required, func(current []services.Check) error {
latest = current
return redraw(current)
})
@@ -73,7 +79,7 @@ the instance of up to 5 minutes.`, Annotations: pullArgumentsAnnotation(nil), Ar
}
return timeoutError(err, timeout, "waiting for %s", waiting)
}
} else if items, err = service.Checks(cmd.Context(), n); err != nil {
} else if items, err = service.Checks(cmd.Context(), n, required); err != nil {
return err
}
if a.options.json != "" {
@@ -106,10 +112,14 @@ the instance of up to 5 minutes.`, Annotations: pullArgumentsAnnotation(nil), Ar
cmd.Flags().DurationVar(&interval, "interval", 5*time.Second, "Time between refreshes with --watch")
cmd.Flags().DurationVar(&timeout, "timeout", time.Hour, "Longest time to wait with --watch")
cmd.Flags().BoolVarP(&web, "web", "w", false, "Open the pull request in the browser")
cmd.Flags().BoolVar(&required, "required", false, "Only the checks that the branch protection requires")
cmd.ValidArgsFunction = firstArg(a.completePulls("open"))
cmd.Example = `# Show the checks of the current branch's pull request
$ gt pr checks
# Only the checks that must pass to merge
$ gt pr checks 13 --required --watch
# Wait until the checks of #13 finish, then merge it
$ gt pr checks 13 --watch && gt pr merge 13`
return jsonOutput[services.Check](cmd)
+18
View File
@@ -410,3 +410,21 @@ func TestDryRunPreviewsDependencyChanges(t *testing.T) {
require.Contains(t, out, "Dry run: would send "+tc.want, "%v", tc.args)
}
}
// TestDryRunPreviewsTheMergeOptions covers the flags of pr merge that the one case of the command in
// dryRunWriteCases does not send.
func TestDryRunPreviewsTheMergeOptions(t *testing.T) {
server := dryRunServer(t)
repo := server.URL + "/api/v1/repos/alice/project"
for _, tc := range []struct {
args []string
want string
}{
{[]string{"pr", "merge", "7", "--disable-auto"}, "DELETE " + repo + "/pulls/7/merge"},
{[]string{"pr", "merge", "7", "--squash", "--admin"}, "POST " + repo + "/pulls/7/merge"},
} {
out, _, err := dryRun(t, server, tc.args...)
require.NoError(t, err, "%v", tc.args)
require.Contains(t, out, "Dry run: would send "+tc.want, "%v", tc.args)
}
}
+2 -1
View File
@@ -393,7 +393,8 @@ Preferences in config.yml are described in gt config --help.`},
or a browser authorization of gt auth login not completed within 2 minutes
4 authentication is missing or was rejected
5 gt run watch and gt workflow run --follow: the run completed without success
6 gt run watch --expect-head: the run is for another commit
6 gt run watch --expect-head: the run is for another commit; gt pr merge: the head of
the pull request is not the commit to merge, such as the one --match-head-commit names
8 gt pr checks: some checks are still pending
130 interrupted with Ctrl-C, also at a prompt
+86 -13
View File
@@ -4,6 +4,7 @@
package app
import (
"cmp"
"context"
"errors"
"fmt"
@@ -26,6 +27,7 @@ type pullCreateFlags struct {
bodyFile, deadline, milestone, topic string
labelNames, reviewers, reviewerTeams, attachments, projects []string
useEditor, draft, agit, allowMaintainerEdits, fill, web bool
fillFirst, fillVerbose bool
}
func (a *application) pullCreateCommand() *cobra.Command {
@@ -36,7 +38,9 @@ On a terminal without flags, gt asks for the title and body, then what to do nex
submit as a draft, add metadata or change the branches. Any flag of this command, such as
--fill, --head or --base (but not global flags such as --repo), skips the questions: the
title is then --title, else the commit message of a single-commit branch, else the branch
name.
name. --fill-first takes the title and body from the first commit of the branch even when there
are several. --fill-verbose takes the body from the full message of every commit, oldest first, or
just the body of a single commit. --fill, --fill-first and --fill-verbose cannot be combined.
A branch that is not on the remote yet is pushed first, with its upstream set, after a
confirmation; without a terminal, pass --yes to push it. A branch that
@@ -64,6 +68,8 @@ else's, such as from gt pr checkout, pass --topic to open your own.`, Annotation
create.Flags().StringVarP(&f.options.Base, "base", "B", "", "Base branch (default: the repository's default branch)")
create.Flags().BoolVarP(&f.draft, "draft", "d", false, "Create a draft pull request")
create.Flags().BoolVarP(&f.fill, "fill", "f", false, "Skip the questions and take the title and body from the commits")
create.Flags().BoolVar(&f.fillFirst, "fill-first", false, "Take the title and body from the first commit of the branch, whatever their number")
create.Flags().BoolVar(&f.fillVerbose, "fill-verbose", false, "Take the body from the full message of every commit of the branch")
create.Flags().BoolVarP(&f.web, "web", "w", false, "Open the comparison of --head and --base in the browser to create the pull request there")
create.Flags().BoolVar(&f.allowMaintainerEdits, "allow-maintainer-edits", true, "Allow maintainers to push to the head branch")
create.Flags().BoolVar(&f.agit, "agit", false, "Create the pull request through AGit push (refs/for)")
@@ -97,6 +103,14 @@ func (a *application) runPullCreate(cmd *cobra.Command, f *pullCreateFlags) (run
if err := validateBodySources(cmd); err != nil {
return err
}
switch {
case f.fill && f.fillFirst:
return clierr.Wrap(clierr.Usage, errors.New("--fill cannot be combined with --fill-first"))
case f.fill && f.fillVerbose:
return clierr.Wrap(clierr.Usage, errors.New("--fill cannot be combined with --fill-verbose"))
case f.fillFirst && f.fillVerbose:
return clierr.Wrap(clierr.Usage, errors.New("--fill-first cannot be combined with --fill-verbose"))
}
if f.agit {
if a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--json, --jq or --csv cannot be combined with --agit; AGit creates the pull request through git push"))
@@ -104,7 +118,7 @@ func (a *application) runPullCreate(cmd *cobra.Command, f *pullCreateFlags) (run
if f.web {
return clierr.Wrap(clierr.Usage, errors.New("--web cannot be combined with --agit; AGit creates the pull request through git push, without a branch to compare"))
}
if err := onlyFlagsWith(cmd, "agit", "AGit pushes carry only a title and body", "title", "body", "body-file", "editor", "head", "base", "draft", "fill", "topic"); err != nil {
if err := onlyFlagsWith(cmd, "agit", "AGit pushes carry only a title and body", "title", "body", "body-file", "editor", "head", "base", "draft", "fill", "fill-first", "fill-verbose", "topic"); err != nil {
return err
}
if f.topic != "" && f.topic == f.options.Base {
@@ -212,13 +226,28 @@ func (a *application) runPullCreate(cmd *cobra.Command, f *pullCreateFlags) (run
return a.openBrowser(cmd, repositoryURL(t)+"/compare/"+compareRef(f.options.Base)+"..."+compareRef(f.options.Head))
}
var commitBody string
if f.options.Title == "" {
var messages []commitMessage
if f.fillFirst || f.fillVerbose {
if messages = a.commitMessages(cmd.Context(), f.options.Base, a.localHead(cmd.Context(), t, f.options.Head)); len(messages) == 0 {
flag := "--fill-verbose"
if f.fillFirst {
flag = "--fill-first"
}
return fmt.Errorf("%s needs the commits of %s that %s lacks in the local clone", flag, f.options.Head, f.options.Base)
}
}
if f.fillFirst {
f.options.Title, commitBody = cmp.Or(f.options.Title, messages[0].Subject), messages[0].Body
} else if f.options.Title == "" {
if subject, body, ok := a.singleCommitMessage(cmd.Context(), f.options.Base, a.localHead(cmd.Context(), t, f.options.Head)); ok {
f.options.Title, commitBody = subject, body
} else if f.options.Title = terminal.DefaultPullTitle(f.options.Head); f.options.Title == "" {
return clierr.Wrap(clierr.Usage, errors.New("pr create requires --title"))
}
}
if f.fillVerbose {
commitBody = verboseCommitBody(messages)
}
service := services.Pulls{Client: t.client, Repository: t.Repo}
if f.useEditor {
var seed string
@@ -414,31 +443,36 @@ func (a *application) defaultPullHead(ctx context.Context) (owner, branch string
return owner, branch
}
// singleCommitMessage returns the subject and body of the only commit the local branch head has
// ahead of base.
// Any Git failure, or a head with zero or several commits, reports ok=false.
func (a *application) singleCommitMessage(ctx context.Context, base, head string) (subject, body string, ok bool) {
// gitAheadOfBase runs Git with args and the commits head has ahead of base, trying base on the
// remotes before the local branch. It reports false for an unsafe ref or when every attempt fails.
func (a *application) gitAheadOfBase(ctx context.Context, base, head string, args ...string) (string, bool) {
if base == "" || head == "" || strings.HasPrefix(base, "-") || strings.HasPrefix(head, "-") {
return "", "", false
return "", false
}
probe := a.gitProbe()
remotes := []string{"upstream", "origin"}
if a.options.remote != "" {
remotes = []string{a.options.remote}
}
count, err := "", errors.New("no base reference")
for _, ref := range append(remotes, "") {
if ref != "" {
ref += "/"
}
if count, err = probe.Output(ctx, a.options.cwd, false, "rev-list", "--count", ref+base+".."+head); err == nil {
break
if out, err := probe.Output(ctx, a.options.cwd, false, append(args, ref+base+".."+head)...); err == nil {
return out, true
}
}
if err != nil || count != "1" {
return "", false
}
// singleCommitMessage returns the subject and body of the only commit the local branch head has
// ahead of base.
// Any Git failure, or a head with zero or several commits, reports ok=false.
func (a *application) singleCommitMessage(ctx context.Context, base, head string) (subject, body string, ok bool) {
if count, found := a.gitAheadOfBase(ctx, base, head, "rev-list", "--count"); !found || count != "1" {
return "", "", false
}
message, err := probe.Output(ctx, a.options.cwd, false, "log", "-1", "--format=%s%n%n%b", head)
message, err := a.gitProbe().Output(ctx, a.options.cwd, false, "log", "-1", "--format=%s%n%n%b", head)
if err != nil {
return "", "", false
}
@@ -447,6 +481,45 @@ func (a *application) singleCommitMessage(ctx context.Context, base, head string
return subject, body, subject != ""
}
// commitMessage is the message of one commit.
type commitMessage struct{ Subject, Body string }
// maxFilledBody keeps a body filled from the commits within what Gitea takes.
const maxFilledBody = 60000
// commitMessages returns the messages of the commits that the local head has ahead of base, oldest
// first, or none when Git cannot tell.
func (a *application) commitMessages(ctx context.Context, base, head string) []commitMessage {
out, found := a.gitAheadOfBase(ctx, base, head, "log", "--reverse", "--format=%s%x1f%b%x1e")
if !found {
return nil
}
var messages []commitMessage
for entry := range strings.SplitSeq(out, "\x1e") {
if subject, body, _ := strings.Cut(strings.TrimSpace(entry), "\x1f"); subject != "" {
messages = append(messages, commitMessage{Subject: subject, Body: strings.TrimSpace(body)})
}
}
return messages
}
// verboseCommitBody joins the full messages of commits, oldest first, with a blank line between.
// The subject of a single commit is the title already, so only its body remains.
func verboseCommitBody(messages []commitMessage) string {
body := messages[0].Body
if len(messages) > 1 {
parts := make([]string, 0, len(messages))
for _, message := range messages {
parts = append(parts, strings.TrimSpace(message.Subject+"\n\n"+message.Body))
}
body = strings.Join(parts, "\n\n---\n\n")
}
if len(body) > maxFilledBody {
body = strings.ToValidUTF8(body[:maxFilledBody], "") + "\n\n…"
}
return body
}
// refuseSameBranch rejects a head that is the base branch of the same repository, before anything
// is pushed: such a pull request has no commits, and pushing would publish the base branch itself.
func refuseSameBranch(head, base string, explicit bool) error {
+62 -5
View File
@@ -594,8 +594,8 @@ const manualMerge = "manually-merged"
var mergeMethods = []string{"merge", "rebase", "rebase-merge", "squash", "fast-forward-only", manualMerge}
func (a *application) pullMergeCommand() *cobra.Command {
var method, title, message, messageFile, commit string
var deleteBranch, useEditor, auto bool
var method, title, message, messageFile, commit, matchHead string
var deleteBranch, useEditor, auto, admin, disableAuto bool
var style struct{ merge, squash, rebase bool }
cmd := &cobra.Command{Use: "merge [<number> | <url> | <branch>]", Short: "Merge a pull request", Long: `Merge a pull request on Gitea.
@@ -610,7 +610,13 @@ to that fork: your own, or any as a site administrator. A fork you cannot push t
For a pull request merged outside Gitea, such as with git merge and git push, --method
manually-merged --commit SHA marks it as merged by that commit of the base branch. The
repository must allow it (gt repo edit --allow-manual-merge). Gitea does not check that the
commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotation(map[string]string{"gt.confirm": "true"}), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) (runErr error) {
commit contains the pull request's changes.
--admin merges although the branch protection is not met, if Gitea lets you bypass the branch
protection. --match-head-commit SHA merges only while the head of the pull request is still that
commit, so a push after you reviewed it is not merged unseen; otherwise gt exits with 6. Neither
can be combined with --auto, as a scheduled merge does not keep them. --disable-auto cancels the
merge that --auto scheduled, and merges nothing.`, Annotations: pullArgumentsAnnotation(map[string]string{"gt.confirm": "true"}), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) (runErr error) {
var editorDraft terminal.Draft
defer finishDraft(&editorDraft, &runErr)
for name, set := range map[string]bool{"merge": style.merge, "squash": style.squash, "rebase": style.rebase} {
@@ -621,6 +627,22 @@ commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotati
method = name
}
}
if disableAuto {
if err := onlyFlagsWith(cmd, "disable-auto", "it only cancels the scheduled merge", "dry-run"); err != nil {
return err
}
}
if auto {
for _, name := range []string{"admin", "match-head-commit"} {
if cmd.Flags().Changed(name) {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--%s cannot be combined with --auto", name))
}
}
}
matchHead = strings.ToLower(matchHead)
if cmd.Flags().Changed("match-head-commit") && !commitSHA.MatchString(matchHead) {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--match-head-commit requires a commit SHA of 7 to 64 hexadecimal digits, got %q", matchHead))
}
manual := method == manualMerge
switch {
case manual && commit == "":
@@ -631,7 +653,7 @@ commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotati
return clierr.Wrap(clierr.Usage, fmt.Errorf("--commit requires a commit SHA of 7 to 64 hexadecimal digits, got %q", commit))
}
if manual {
for _, name := range []string{"auto", "title", "message", "message-file", "editor"} {
for _, name := range []string{"auto", "title", "message", "message-file", "editor", "admin", "match-head-commit"} {
if cmd.Flags().Changed(name) {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--method manually-merged cannot be combined with --%s", name))
}
@@ -656,6 +678,18 @@ commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotati
return err
}
ref := refLabel(t.Repo, n, item.Title)
if disableAuto {
canceled, err := service.CancelAutoMerge(cmd.Context(), n)
if err != nil {
return err
}
if canceled {
a.done(cmd, "Canceled the merge of pull request %s that was scheduled for when its checks succeed", ref)
} else {
a.warn(cmd, "No merge is scheduled for pull request %s", ref)
}
return a.pullResult(cmd, t, item)
}
switch {
case item.Merged:
a.warn(cmd, "Pull request %s is already merged", ref)
@@ -670,6 +704,9 @@ commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotati
case item.HeadRemoteDeleted && item.Head != "" && !manual:
return fmt.Errorf("pull request %s cannot be merged: its head branch %s was deleted; push it again to merge", ref, item.Head)
}
if matchHead != "" && !strings.HasPrefix(item.HeadSHA, matchHead) {
return pullHeadMismatch(ref, item.HeadSHA, matchHead)
}
repoSettings, err := service.MergeSettings(cmd.Context())
if err != nil {
return err
@@ -717,12 +754,15 @@ commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotati
message = editorDraft.Body
}
// Gitea ignores delete_branch_after_merge for manual merges; gt deletes the branch itself.
if err := service.Merge(cmd.Context(), n, services.MergeOptions{Method: method, Title: title, Message: message, DeleteBranch: deleteBranch && !manual, Auto: auto, HeadSHA: item.HeadSHA, Commit: commit}); err != nil {
if err := service.Merge(cmd.Context(), n, services.MergeOptions{Method: method, Title: title, Message: message, DeleteBranch: deleteBranch && !manual, Auto: auto, Force: admin, HeadSHA: item.HeadSHA, Commit: commit}); err != nil {
if apiErr, ok := errors.AsType[*transport.APIError](err); ok {
switch {
case auto && apiErr.Status == http.StatusConflict && strings.Contains(apiErr.Message, "already scheduled to auto merge"):
a.warn(cmd, "Pull request %s is already scheduled to merge when its checks succeed", ref)
return a.pullResult(cmd, t, item)
case apiErr.Status == http.StatusConflict && strings.Contains(apiErr.Message, "head out of date"):
current, _ := service.View(cmd.Context(), n) // only to name the new head
return pullHeadMismatch(ref, current.HeadSHA, item.HeadSHA)
case manual && strings.Contains(apiErr.Message, "merge strategy is not allowed"):
return explain(err, "manual merges are disabled in %s; allow them with: gt repo edit --allow-manual-merge -R %s", t.Repo, t.Repo)
case manual && strings.Contains(apiErr.Message, "commit not found in base"):
@@ -766,6 +806,9 @@ commit contains the pull request's changes.`, Annotations: pullArgumentsAnnotati
cmd.Flags().StringVarP(&messageFile, "message-file", "F", "", "Read the merge commit message from `file`, or - for stdin")
cmd.Flags().BoolVarP(&useEditor, "editor", "e", false, "Write the merge commit message in your editor")
cmd.Flags().StringVar(&commit, "commit", "", "Commit `sha` on the base branch that merged the pull request outside Gitea (with --method manually-merged)")
cmd.Flags().BoolVar(&admin, "admin", false, "Merge although the branch protection is not met, if Gitea lets you bypass the branch protection")
cmd.Flags().StringVar(&matchHead, "match-head-commit", "", "Merge only if the head of the pull request is this commit `sha`")
cmd.Flags().BoolVar(&disableAuto, "disable-auto", false, "Cancel the merge that --auto scheduled, and merge nothing")
cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {
if strings.Contains(err.Error(), "flag needs an argument: 's' in -s") {
return clierr.Wrap(clierr.Usage, errors.New("-s takes a method (merge, rebase, rebase-merge, squash, fast-forward-only or manually-merged); for gh-style use --squash"))
@@ -782,11 +825,25 @@ $ gt pr merge 13 --squash --delete-branch
# Merge once the checks pass, without prompts
$ gt pr merge 13 --auto --yes
# Merge only the commit that was reviewed, and cancel a scheduled merge
$ gt pr merge 13 --squash --match-head-commit 4b825dc
$ gt pr merge 13 --disable-auto
# Mark #13 as merged by a commit pushed to the base branch outside Gitea
$ gt pr merge 13 --method manually-merged --commit 4b825dc --delete-branch`
return a.dryRunnable(cmd)
}
// pullHeadMismatch reports a pull request whose head is not the expected commit. An empty or unchanged
// head is one that could not be read after Gitea refused the expected one.
func pullHeadMismatch(ref, head, expected string) error {
state := "is no longer " + shortSHA(expected)
if head != "" && head != expected {
state = "is " + shortSHA(head) + ", not " + shortSHA(expected)
}
return clierr.Wrap(clierr.HeadMismatch, fmt.Errorf("the head of pull request %s %s; look at what was pushed and merge again", ref, state))
}
// mergeTarget selects the pull request to merge: the argument, else the current branch's pull
// request, else, on a terminal, one that the user picks among those for the current branch.
func (a *application) mergeTarget(cmd *cobra.Command, args []string) (target, int64, error) {
@@ -0,0 +1,235 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package app
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/git"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
// optionsRepo is a disposable repository for the pull request option tests.
type optionsRepo struct {
services.Repository
deps *Dependencies
execute func(args ...string) []byte
}
func newOptionsRepo(t *testing.T, prefix string) optionsRepo {
t.Helper()
_, deps, out, diagnostics := giteaDeps(t)
execute := outputExecutor(t, &deps, out, diagnostics)
var repo services.Repository
require.NoError(t, json.Unmarshal(execute("repo", "create", fmt.Sprintf("%s-%d", prefix, time.Now().UnixNano()), "--auto-init", "--private", "--json"), &repo))
t.Cleanup(func() {
if err := Execute(context.Background(), deps, []string{"repo", "delete", "-R", repo.FullName, "--yes"}); err != nil {
t.Errorf("repository cleanup: %v", err)
}
})
return optionsRepo{Repository: repo, deps: &deps, execute: execute}
}
func (r optionsRepo) scoped(args ...string) []byte {
return r.execute(append(args, "-R", r.FullName)...)
}
func (r optionsRepo) api(path, jq string) string {
return strings.TrimSpace(string(r.execute("api", "repos/"+r.FullName+"/"+path, "--jq", jq)))
}
// commit writes a file to a branch through the API.
func (r optionsRepo) commit(branch, name string) {
payload, err := json.Marshal(map[string]string{"branch": branch, "message": "Add " + name, "content": base64.StdEncoding.EncodeToString([]byte(name + "\n"))})
if err != nil {
panic(err)
}
r.deps.Streams.In = strings.NewReader(string(payload))
r.execute("api", "repos/"+r.FullName+"/contents/"+name, "--input", "-")
}
// pull makes a branch with a commit and a pull request from it into the default branch.
func (r optionsRepo) pull(t *testing.T, branch string) (number, head string) {
t.Helper()
r.scoped("branch", "create", branch)
r.commit(branch, branch+".txt")
var pull services.Pull
require.NoError(t, json.Unmarshal(r.scoped("pr", "create", "--title", "Change "+branch, "--body", "b", "--head", branch, "--base", r.DefaultBranch, "--json"), &pull))
number = strconv.FormatInt(pull.Number, 10)
return number, r.api("pulls/"+number, ".head.sha")
}
func (r optionsRepo) fails(args ...string) error {
return Execute(context.Background(), *r.deps, append(args, "-R", r.FullName, "--no-input"))
}
func TestGiteaPullMergeAdminMatchHeadCommitAndDisableAuto(t *testing.T) {
repo := newOptionsRepo(t, "gt-merge-options")
t.Run("match-head-commit", func(t *testing.T) {
number, reviewed := repo.pull(t, "reviewed")
repo.commit("reviewed", "pushed-after-review.txt")
moved := repo.api("pulls/"+number, ".head.sha")
require.NotEqual(t, reviewed, moved)
err := repo.fails("pr", "merge", number, "--squash", "--yes", "--match-head-commit", reviewed)
require.Equal(t, clierr.HeadMismatch, clierr.ExitCode(err), "the head moved after the review")
require.ErrorContains(t, err, "is "+moved[:7]+", not "+reviewed[:7])
require.Equal(t, "false", repo.api("pulls/"+number, ".merged"), "nothing was merged")
require.NoError(t, repo.fails("pr", "merge", number, "--squash", "--yes", "--match-head-commit", strings.ToUpper(moved[:10])))
require.Equal(t, "true", repo.api("pulls/"+number, ".merged"), "the commit that was named is the head, so it merges")
})
t.Run("admin", func(t *testing.T) {
repo.scoped("branch", "protect", repo.DefaultBranch, "--required-approvals", "1")
number, _ := repo.pull(t, "needs-approval")
require.Error(t, repo.fails("pr", "merge", number, "--squash", "--yes"), "the protection asks for an approval that there is none of")
require.Equal(t, "false", repo.api("pulls/"+number, ".merged"))
require.NoError(t, repo.fails("pr", "merge", number, "--squash", "--yes", "--admin"))
require.Equal(t, "true", repo.api("pulls/"+number, ".merged"), "an administrator merges past the protection")
repo.scoped("branch", "unprotect", repo.DefaultBranch, "--yes")
})
t.Run("disable-auto", func(t *testing.T) {
repo.scoped("branch", "protect", repo.DefaultBranch, "--status-check", "ci/never")
number, head := repo.pull(t, "scheduled")
repo.execute("api", "repos/"+repo.FullName+"/statuses/"+head, "-f", "state=pending", "-f", "context=ci/never")
require.NoError(t, repo.fails("pr", "merge", number, "--auto", "--squash", "--yes"))
require.Equal(t, "false", repo.api("pulls/"+number, ".merged"), "the merge waits for the check")
require.NoError(t, repo.fails("pr", "merge", number, "--disable-auto"))
require.NoError(t, repo.fails("pr", "merge", number, "--disable-auto"), "a second cancel finds nothing scheduled and says so")
repo.execute("api", "repos/"+repo.FullName+"/statuses/"+head, "-f", "state=success", "-f", "context=ci/never")
time.Sleep(3 * time.Second)
require.Equal(t, "false", repo.api("pulls/"+number, ".merged"), "the canceled merge does not happen when the check passes")
require.Equal(t, clierr.Usage, clierr.ExitCode(repo.fails("pr", "merge", number, "--disable-auto", "--squash")))
})
}
func TestGiteaPullChecksRequired(t *testing.T) {
repo := newOptionsRepo(t, "gt-required-checks")
repo.scoped("branch", "protect", repo.DefaultBranch, "--status-check", "ci/required,lint/*")
number, head := repo.pull(t, "checked")
report := func(context, state string) {
repo.execute("api", "repos/"+repo.FullName+"/statuses/"+head, "-f", "state="+state, "-f", "context="+context)
}
checks := func(args ...string) (string, error) {
deps := *repo.deps
buffer := &strings.Builder{}
deps.Streams.Out = buffer
err := Execute(context.Background(), deps, append([]string{"pr", "checks", number, "-R", repo.FullName, "--no-input", "--json", "name,state"}, args...))
return buffer.String(), err
}
report("ci/required", "pending")
report("ci/optional", "failure")
report("lint/go", "success")
out, err := checks()
require.Equal(t, 1, clierr.ExitCode(err), "the optional check failed")
require.JSONEq(t, `[{"name":"ci/optional","state":"failure"},{"name":"ci/required","state":"pending"},{"name":"lint/go","state":"success"}]`, out)
repo.scoped("branch", "protect", repo.DefaultBranch, "--status-check", "ci/required,lint/*,ci/late")
out, err = checks("--required")
require.Equal(t, clierr.Pending, clierr.ExitCode(err))
require.JSONEq(t, `[{"name":"ci/late","state":"pending"},{"name":"ci/required","state":"pending"},{"name":"lint/go","state":"success"}]`, out, "a required check that has not reported is pending")
repo.scoped("branch", "protect", repo.DefaultBranch, "--status-check", "ci/required,lint/*")
out, err = checks("--required")
require.Equal(t, clierr.Pending, clierr.ExitCode(err), "the required check is still running")
require.JSONEq(t, `[{"name":"ci/required","state":"pending"},{"name":"lint/go","state":"success"}]`, out, "the optional check is not shown, and lint/* matches lint/go")
report("ci/required", "success")
out, err = checks("--required", "--watch", "--interval", "1s", "--timeout", "30s")
require.NoError(t, err, "with the required checks done the failed optional one does not hold --watch")
require.JSONEq(t, `[{"name":"ci/required","state":"success"},{"name":"lint/go","state":"success"}]`, out)
// A pull request into an unprotected branch has no required checks.
repo.scoped("branch", "create", "unprotected")
repo.scoped("branch", "create", "feature-2")
repo.commit("feature-2", "feature-2.txt")
var pull services.Pull
require.NoError(t, json.Unmarshal(repo.scoped("pr", "create", "--title", "Into unprotected", "--head", "feature-2", "--base", "unprotected", "--json"), &pull))
buffer := &strings.Builder{}
deps := *repo.deps
deps.Streams.Out = buffer
require.ErrorContains(t, Execute(context.Background(), deps, []string{"pr", "checks", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName, "--required", "--no-input", "--json"}), "no required checks reported on the 'feature-2' branch")
require.Empty(t, buffer.String())
}
// TestGiteaPullCreateFillFirstAndFillVerbose makes a branch of three commits in a clone and opens
// pull requests from it, which the flags fill from the commits.
func TestGiteaPullCreateFillFirstAndFillVerbose(t *testing.T) {
gitea, deps, out, diagnostics := giteaDeps(t)
execute := outputExecutor(t, &deps, out, diagnostics)
var repo services.Repository
require.NoError(t, json.Unmarshal(execute("repo", "create", fmt.Sprintf("gt-fill-%d", time.Now().UnixNano()), "--auto-init", "--private", "--json"), &repo))
t.Cleanup(func() {
if err := Execute(context.Background(), deps, []string{"repo", "delete", "-R", repo.FullName, "--yes"}); err != nil {
t.Errorf("repository cleanup: %v", err)
}
})
env := append(os.Environ(), "GIT_CONFIG_GLOBAL="+filepath.Join(t.TempDir(), "gitconfig"), "GIT_CONFIG_NOSYSTEM=1", "GIT_TERMINAL_PROMPT=0",
"GIT_AUTHOR_NAME=gt", "[email protected]", "GIT_COMMITTER_NAME=gt", "[email protected]")
clone := filepath.Join(t.TempDir(), "clone")
run := func(dir string, args ...string) {
t.Helper()
command := exec.CommandContext(context.Background(), "git", args...)
command.Dir, command.Env = dir, env
output, err := command.CombinedOutput()
require.NoError(t, err, "git %s: %s", strings.Join(args, " "), output)
}
user, _, _ := strings.Cut(repo.FullName, "/")
authenticated := strings.Replace(gitea.url, "://", "://"+user+":"+gitea.token+"@", 1) + "/" + repo.FullName + ".git"
run(t.TempDir(), "clone", "-q", authenticated, clone)
run(clone, "checkout", "-q", "-b", "feature")
for i, message := range []string{"Add the form\n\nIt validates the input.", "Fix a typo", "Handle empty input\n\nNeeds a test too."} {
require.NoError(t, os.WriteFile(filepath.Join(clone, fmt.Sprintf("file-%d.txt", i)), []byte("x\n"), 0o600))
run(clone, "add", ".")
run(clone, "commit", "-q", "-m", message)
}
run(clone, "push", "-q", "-u", "origin", "feature")
deps.Git = git.System{Env: env}
var pull services.Pull
create := func(args ...string) services.Pull {
t.Helper()
out.Reset()
diagnostics.Reset()
require.NoError(t, Execute(context.Background(), deps, append([]string{"pr", "create", "-R", repo.FullName, "--cwd", clone, "--head", "feature", "--base", repo.DefaultBranch, "--json", "--no-input", "--yes"}, args...)))
require.NoError(t, json.Unmarshal(out.Bytes(), &pull))
return pull
}
closeLast := func() {
execute("pr", "close", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName)
}
filled := create("--fill")
require.Equal(t, "Feature", filled.Title, "--fill takes the branch name when there are several commits")
require.Empty(t, filled.Body)
closeLast()
filled = create("--fill-first")
require.Equal(t, "Add the form", filled.Title)
require.Equal(t, "It validates the input.", filled.Body)
closeLast()
filled = create("--fill-verbose")
require.Equal(t, "Feature", filled.Title)
require.Equal(t, "Add the form\n\nIt validates the input.\n\n---\n\nFix a typo\n\n---\n\nHandle empty input\n\nNeeds a test too.", filled.Body)
closeLast()
}
+310
View File
@@ -0,0 +1,310 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package app
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"strings"
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
func TestPullMergeAdminAndMatchHeadCommit(t *testing.T) {
// merge runs gt against a server that has not merged anything yet, and returns what it was sent.
merge := func(args ...string) (map[string]any, error) {
var payload map[string]any
server := newAuthenticatedServer(mergeServer(t, strings.ReplaceAll(openPull, "abc123", "abc1234567"), &payload))
defer server.Close()
deps, _, _ := serverDeps(t, server.URL)
err := Execute(context.Background(), deps, append([]string{"pr", "merge", "3", "-R", "alice/project", "--method", "squash", "--yes"}, args...))
return payload, err
}
payload, err := merge()
require.NoError(t, err)
require.Equal(t, false, payload["force_merge"], "a merge does not override the branch protection unless asked")
payload, err = merge("--admin")
require.NoError(t, err)
require.Equal(t, true, payload["force_merge"])
payload, err = merge("--match-head-commit", "ABC1234")
require.NoError(t, err)
require.Equal(t, "abc1234567", payload["head_commit_id"], "a prefix of the head matches, whatever its case, and the whole head is sent")
payload, err = merge("--match-head-commit", "def4567")
require.Equal(t, clierr.HeadMismatch, clierr.ExitCode(err))
require.ErrorContains(t, err, "the head of pull request alice/project#3 (Add login) is abc1234, not def4567")
require.Nil(t, payload, "a head that moved is not merged")
for _, args := range [][]string{{"--match-head-commit", "xyz"}, {"--match-head-commit", "abc"}} {
_, err := merge(args...)
require.Equal(t, clierr.Usage, clierr.ExitCode(err), args)
}
for _, flag := range []string{"--admin", "--match-head-commit=abc1234"} {
_, err := merge("--method", "manually-merged", "--commit", "abc1234", flag)
require.Equal(t, clierr.Usage, clierr.ExitCode(err), flag)
}
}
func TestPullMergeReportsAHeadThatMoved(t *testing.T) {
// head is what Gitea reports after it refused the merge, and "" when it cannot be read.
for head, want := range map[string]string{
"def4567890": "the head of pull request alice/project#3 (Add login) is def4567, not abc1234; look at what was pushed and merge again",
"abc1234567": "the head of pull request alice/project#3 (Add login) is no longer abc1234; look at what was pushed and merge again",
"": "the head of pull request alice/project#3 (Add login) is no longer abc1234; look at what was pushed and merge again",
} {
refused := false
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project":
_, _ = w.Write([]byte(mergeRepository))
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/pulls/3" && refused && head == "":
w.WriteHeader(http.StatusInternalServerError)
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/pulls/3" && refused:
_, _ = w.Write([]byte(strings.ReplaceAll(openPull, "abc123", head)))
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/pulls/3":
_, _ = w.Write([]byte(strings.ReplaceAll(openPull, "abc123", "abc1234567")))
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos/alice/project/pulls/3/merge":
refused = true
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"message":"head out of date"}`))
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
deps, _, _ := serverDeps(t, server.URL)
err := Execute(context.Background(), deps, []string{"pr", "merge", "3", "-R", "alice/project", "--method", "squash", "--yes", "--match-head-commit", "abc1234"})
server.Close()
require.Equal(t, clierr.HeadMismatch, clierr.ExitCode(err), head)
require.EqualError(t, err, want, head)
}
}
func TestPullMergeOfAMergedPullRequestWarnsWhateverItsHead(t *testing.T) {
var payload map[string]any
server := newAuthenticatedServer(mergeServer(t, `{"number":3,"title":"Add login","state":"closed","merged":true,"base":{"ref":"main"},"head":{"ref":"feature","sha":"abc1234567"}}`, &payload))
defer server.Close()
deps, _, diagnostics := serverDeps(t, server.URL)
deps.Streams.ErrTTY = true
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "merge", "3", "-R", "alice/project", "--method", "squash", "--yes", "--match-head-commit", "def4567"}))
require.Contains(t, diagnostics.String(), "is already merged")
require.Nil(t, payload)
}
func TestPullMergeDisableAutoCancelsTheScheduledMerge(t *testing.T) {
var deletes int
scheduled := true
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project":
_, _ = w.Write([]byte(mergeRepository))
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/pulls/3":
_, _ = w.Write([]byte(openPull))
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/git/refs/pull/3/head":
writePullRef(w, 3, "abc123")
case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/repos/alice/project/pulls/3/merge":
deletes++
if !scheduled {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"not found"}`)) // as Gitea answers, with nothing to tell it from a missing pull request
return
}
scheduled = false
w.WriteHeader(http.StatusNoContent)
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
run := func(args ...string) (string, error) {
deps, out, diagnostics := serverDeps(t, server.URL)
deps.Streams.ErrTTY = true
err := Execute(context.Background(), deps, append([]string{"pr", "merge", "3", "-R", "alice/project", "--disable-auto", "--no-input"}, args...))
return out.String() + diagnostics.String(), err
}
out, err := run("--json", "number")
require.NoError(t, err)
require.Contains(t, out, `"number":3`)
require.Equal(t, 1, deletes)
out, err = run()
require.NoError(t, err, "nothing scheduled is not a failure")
require.Contains(t, out, "No merge is scheduled for pull request alice/project#3")
require.Equal(t, 2, deletes)
for _, flag := range []string{"--auto", "--squash", "--delete-branch", "--title=x", "--admin", "--match-head-commit=abc1234", "--editor"} {
_, err := run(flag)
require.Equal(t, clierr.Usage, clierr.ExitCode(err), flag)
require.ErrorContains(t, err, strings.SplitN(flag, "=", 2)[0]+" cannot be combined with --disable-auto", flag)
}
require.Equal(t, 2, deletes, "a refused combination sends nothing")
}
func TestPullChecksRequiredShowsOnlyTheRequiredChecks(t *testing.T) {
// What Gitea tells someone who does not administer the repository: no effective_branch_protection_name.
branch := `{"name":"main","protected":true,"enable_status_check":true,"status_check_contexts":["ci/build","lint/*","{unit,e2e}/[ab]"]}`
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/repos/alice/project":
_, _ = w.Write([]byte(`{"full_name":"alice/project","has_pull_requests":true}`))
case "/api/v1/repos/alice/project/pulls/3":
_, _ = w.Write([]byte(`{"number":3,"title":"T","state":"open","base":{"ref":"main"},"head":{"ref":"feature","sha":"abc123"}}`))
case "/api/v1/repos/alice/project/branches/main":
_, _ = w.Write([]byte(branch))
case "/api/v1/repos/alice/project/statuses/abc123":
writeFirstPage(w, r, `[{"id":1,"context":"ci/build","status":"success"},{"id":2,"context":"ci/optional","status":"failure"},{"id":3,"context":"lint/go","status":"success"},{"id":4,"context":"unit/a","status":"success"}]`)
default:
t.Errorf("unexpected %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
run := func(args ...string) (string, error) {
deps, out, _ := serverDeps(t, server.URL)
err := Execute(context.Background(), deps, append([]string{"pr", "checks", "3", "-R", "alice/project", "--no-input"}, args...))
return out.String(), err
}
_, err := run("--json", "name,state")
require.Equal(t, 1, clierr.ExitCode(err), "an optional check that failed fails the command")
out, err := run("--required", "--json", "name,state")
require.NoError(t, err, "only the required checks count")
require.JSONEq(t, `[{"name":"ci/build","state":"success"},{"name":"lint/go","state":"success"},{"name":"unit/a","state":"success"}]`, out, "patterns are globs as Gitea reads them")
branch = `{"name":"main","enable_status_check":true,"status_check_contexts":["ci/build","docs"]}`
out, err = run("--required", "--json", "name,state,description")
require.Equal(t, clierr.Pending, clierr.ExitCode(err), "a required check that has not reported is pending")
require.JSONEq(t, `[{"name":"ci/build","state":"success","description":""},{"name":"docs","state":"pending","description":"Waiting for status to be reported"}]`, out)
branch = `{"name":"main","enable_status_check":true,"status_check_contexts":[]}`
out, err = run("--required", "--json", "name")
require.Equal(t, 1, clierr.ExitCode(err), "a rule without patterns requires every check")
require.JSONEq(t, `[{"name":"ci/build"},{"name":"ci/optional"},{"name":"lint/go"},{"name":"unit/a"}]`, out)
branch = `{"name":"main","status_check_contexts":["ci/optional"]}`
out, err = run("--required")
require.Equal(t, 1, clierr.ExitCode(err))
require.EqualError(t, err, "no required checks reported on the 'feature' branch")
require.Empty(t, out)
require.Equal(t, clierr.Usage, clierr.ExitCode(func() error { _, err := run("--required", "--web"); return err }()))
}
func TestPullCreateFillFirstAndFillVerbose(t *testing.T) {
var payload map[string]any
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project":
_, _ = w.Write([]byte(`{"has_pull_requests":true,"full_name":"alice/project","permissions":{"push":true}}`))
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos/alice/project/branches/main":
_, _ = w.Write([]byte(`{"name":"main"}`))
case r.Method == http.MethodPost && r.URL.Path == "/api/v1/repos/alice/project/pulls":
payload = nil
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
_, _ = w.Write([]byte(`{"number":7,"title":"PR","html_url":"https://example.test/pulls/7"}`))
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
create := func(log string, args ...string) (map[string]any, error) {
deps, _, _ := serverDeps(t, server.URL)
pushKey := credentialCall(t, deps, server.URL, "alice", "push", "--set-upstream", "--quiet", "--", "origin", "refs/heads/feature")
deps.Git = &fakeGit{results: map[string]string{
"rev-parse --is-inside-work-tree": "true",
"rev-parse --verify refs/heads/feature^{commit}": "localsha",
"remote": "origin",
"remote get-url origin": server.URL + "/alice/project.git",
"config --get branch.feature.remote": "origin",
"rev-list --count refs/remotes/origin/main..refs/heads/feature": "3",
"rev-list --count origin/main..feature": "3",
"log --reverse --format=%s%x1f%b%x1e origin/main..feature": log,
pushKey: "",
}}
payload = nil
err := Execute(context.Background(), deps, append([]string{"pr", "create", "-R", "alice/project", "--head", "feature", "--base", "main", "--json=number", "--no-input", "--yes"}, args...))
return payload, err
}
three := "Add the form\x1fIt validates.\x1eFix a typo\x1f\x1eHandle empty input\x1fNeeds a test too.\x1e"
got, err := create(three, "--fill")
require.NoError(t, err)
require.Equal(t, "Feature", got["title"], "--fill keeps its rule: the branch name, made readable, for several commits")
require.Equal(t, "", got["body"])
got, err = create(three, "--fill-first")
require.NoError(t, err)
require.Equal(t, "Add the form", got["title"], "the first commit, although there are three")
require.Equal(t, "It validates.", got["body"])
got, err = create(three, "--fill-verbose")
require.NoError(t, err)
require.Equal(t, "Feature", got["title"])
require.Equal(t, "Add the form\n\nIt validates.\n\n---\n\nFix a typo\n\n---\n\nHandle empty input\n\nNeeds a test too.", got["body"], "every message, oldest first")
got, err = create(three, "--fill-first", "--title", "Mine", "--body", "Mine too")
require.NoError(t, err)
require.Equal(t, "Mine", got["title"], "a title or body that is given wins")
require.Equal(t, "Mine too", got["body"])
got, err = create(three, "--fill-first", "--title", "Mine")
require.NoError(t, err)
require.Equal(t, "Mine", got["title"])
require.Equal(t, "It validates.", got["body"], "a given title replaces only the title")
got, err = create("Add the form\x1fIt validates.\x1e", "--fill-verbose", "--title", "Mine")
require.NoError(t, err)
require.Equal(t, "It validates.", got["body"], "the subject of a single commit is not repeated in the body")
for flag, want := range map[string]string{"--fill-first": "--fill-first needs", "--fill-verbose": "--fill-verbose needs"} {
_, err = create("", flag)
require.Equal(t, clierr.Failure, clierr.ExitCode(err), "without the commits there is nothing to fill from")
require.ErrorContains(t, err, want+" the commits of feature that main lacks")
}
}
func TestPullCreateAgitFillsFromTheCommits(t *testing.T) {
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/alice/project":
_, _ = w.Write([]byte(`{"has_pull_requests":true,"full_name":"alice/project","default_branch":"main","permissions":{"push":true}}`))
case r.Method == http.MethodGet:
_, _ = w.Write([]byte(`[]`))
default:
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
verbose := base64.StdEncoding.EncodeToString([]byte("Add the form\n\nIt validates.\n\n---\n\nFix a typo"))
for _, tc := range []struct{ flag, title, description string }{
{"--fill-first", "Add the form", "It validates."},
{"--fill-verbose", "Feature", "{base64}" + verbose},
} {
deps, _, _ := serverDeps(t, server.URL)
pushKey := credentialCall(t, deps, server.URL, "alice", "push", "-o", "title="+tc.title, "-o", "description="+tc.description, "--", "origin", "refs/heads/feature:refs/for/main/feature")
runner := &fakeGit{results: map[string]string{
"remote": "origin",
"remote get-url origin": server.URL + "/alice/project.git",
"rev-parse --is-inside-work-tree": "true",
"rev-list --count origin/main..feature": "2",
"log --reverse --format=%s%x1f%b%x1e origin/main..feature": "Add the form\x1fIt validates.\x1eFix a typo\x1f\x1e",
pushKey: "",
}}
deps.Git = runner
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "create", "--agit", "-R", "alice/project", "--head", "feature", "--base", "main", "--no-input", tc.flag}), tc.flag)
require.Contains(t, runner.calls, pushKey, tc.flag)
}
}
+5
View File
@@ -254,6 +254,11 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"pr", "attachment", "download", "1", "1", "--json"}, "attachment downloads are binary"},
{[]string{"pr", "attachment", "download", "1", "1", "--output", "-", "--json=id"}, "attachment downloads are binary"},
{[]string{"pr", "checkout", "7", "--detach", "--branch", "name"}, "--detach cannot be combined with --branch or --update"},
{[]string{"pr", "merge", "5", "--auto", "--admin"}, "--admin cannot be combined with --auto"},
{[]string{"pr", "merge", "5", "--auto", "--match-head-commit", "abc1234"}, "--match-head-commit cannot be combined with --auto"},
{[]string{"pr", "create", "--fill", "--fill-first"}, "--fill cannot be combined with --fill-first"},
{[]string{"pr", "create", "--fill", "--fill-verbose"}, "--fill cannot be combined with --fill-verbose"},
{[]string{"pr", "create", "--fill-first", "--fill-verbose"}, "--fill-first cannot be combined with --fill-verbose"},
{[]string{"pr", "create", "--milestone=-1"}, "--milestone must be a milestone title or a positive ID"},
{[]string{"pr", "create", "--assignee", "alice, "}, "assignee names cannot be empty"},
{[]string{"pr", "create", "--label", "bug, "}, "label names cannot be empty"},
+2 -1
View File
@@ -16,7 +16,8 @@ const (
Authentication = 4
// Unsuccessful reports a run that completed without success, unlike a Failure of gt itself.
Unsuccessful = 5
// HeadMismatch reports a run for another commit than gt run watch --expect-head names.
// HeadMismatch reports a run for another commit than gt run watch --expect-head names, or a
// pull request whose head is not the commit gt pr merge, as with --match-head-commit, is to merge.
HeadMismatch = 6
// Pending reports checks that have not finished, like gh pr checks.
Pending = 8
+96 -9
View File
@@ -6,12 +6,16 @@ package services
import (
"context"
"errors"
"fmt"
"net/url"
"slices"
"sort"
"strings"
"time"
gitea "gitea.dev/sdk"
"github.com/gobwas/glob"
)
// Check represents the latest status of one commit context.
@@ -47,23 +51,39 @@ func Tally(items []Check) (failing, pending, passed int) {
return failing, pending, passed
}
// Checks returns latest contexts for the PR head in its base repository, as Gitea does.
func (s Pulls) Checks(ctx context.Context, n int64) ([]Check, error) {
sha, err := s.checkHead(ctx, n)
// Checks returns latest contexts for the PR head in its base repository, as Gitea does; with
// required, only those that the protection of the base branch requires.
func (s Pulls) Checks(ctx context.Context, n int64, required bool) ([]Check, error) {
pull, err := s.checkPull(ctx, n)
if err != nil {
return nil, err
}
return s.checksForCommit(ctx, sha)
var rule *requiredChecks
if required {
if rule, err = s.requiredChecks(ctx, pull); err != nil {
return nil, err
}
}
items, err := s.checksForCommit(ctx, pull.Head.Sha)
return rule.of(pull.Head.Sha, items), err
}
func (s Pulls) checkPull(ctx context.Context, n int64) (*gitea.PullRequest, error) {
pull, err := s.get(ctx, n)
if err != nil {
return nil, err
}
if pull.Head == nil || pull.Head.Sha == "" {
return nil, errors.New("Gitea did not return the pull request head commit")
}
return pull, nil
}
func (s Pulls) checkHead(ctx context.Context, n int64) (string, error) {
pull, err := s.get(ctx, n)
pull, err := s.checkPull(ctx, n)
if err != nil {
return "", err
}
if pull.Head == nil || pull.Head.Sha == "" {
return "", errors.New("Gitea did not return the pull request head commit")
}
return pull.Head.Sha, nil
}
@@ -121,10 +141,20 @@ func (s Pulls) checksForCommit(ctx context.Context, sha string) ([]Check, error)
// WatchChecks follows the current PR head until contexts finish or a check fails.
// An empty status set waits for checks to be registered instead of claiming success.
func (s Pulls) WatchChecks(ctx context.Context, n int64, interval time.Duration, changed func([]Check) error) ([]Check, error) {
func (s Pulls) WatchChecks(ctx context.Context, n int64, interval time.Duration, required bool, changed func([]Check) error) ([]Check, error) {
if interval <= 0 {
return nil, errors.New("check polling interval must be positive")
}
var rule *requiredChecks
if required {
pull, err := s.checkPull(ctx, n)
if err != nil {
return nil, err
}
if rule, err = s.requiredChecks(ctx, pull); err != nil {
return nil, err
}
}
var previous []Check
reported := false
var failures outage
@@ -133,6 +163,7 @@ func (s Pulls) WatchChecks(ctx context.Context, n int64, interval time.Duration,
var items []Check
if err == nil {
items, err = s.checksForCommit(ctx, sha)
items = rule.of(sha, items)
}
if failures.retry(ctx, err) {
if err := sleepCtx(ctx, interval); err != nil {
@@ -175,3 +206,59 @@ func (s Pulls) WatchChecks(ctx context.Context, n int64, interval time.Duration,
}
}
}
// requiredChecks is what the protection of a base branch requires of the checks of a pull request.
type requiredChecks struct{ patterns []*glob.Pattern }
// requiredChecks reads the checks that the protection of the base branch requires from the branch
// itself, as Gitea names its protection rule only to administrators. It fails when the branch
// requires none.
func (s Pulls) requiredChecks(ctx context.Context, pull *gitea.PullRequest) (*requiredChecks, error) {
if pull.Base == nil || pull.Base.Ref == "" {
return nil, errors.New("Gitea did not return the base branch of the pull request")
}
branch, err := repoCall(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, name string) (*gitea.Branch, *gitea.Response, error) {
return c.Repositories.GetRepoBranch(ctx, owner, name, pull.Base.Ref)
})
if err != nil {
return nil, Classify(err, "branch", pull.Base.Ref, s.Repository)
}
if !branch.EnableStatusCheck {
return nil, fmt.Errorf("no required checks reported on the '%s' branch", pull.Head.Ref)
}
rule := &requiredChecks{}
for _, pattern := range branch.StatusCheckContexts {
if compiled, err := glob.Compile(pattern); err == nil { // Gitea skips a pattern it cannot read too
rule.patterns = append(rule.patterns, compiled)
}
}
return rule, nil
}
// of keeps the required checks of a commit. A pattern that no check matches yet is a pending check,
// as Gitea waits for it, and a rule without patterns requires every check.
func (r *requiredChecks) of(sha string, items []Check) []Check {
if r == nil || len(r.patterns) == 0 {
return items
}
matched := make([]bool, len(r.patterns))
kept := make([]Check, 0, len(items))
for _, item := range items {
keep := false
for i, pattern := range r.patterns {
if pattern.Match(item.Name) {
matched[i], keep = true, true
}
}
if keep {
kept = append(kept, item)
}
}
for i, found := range matched {
if !found {
kept = append(kept, Check{SHA: sha, Name: r.patterns[i].String(), State: "pending", Description: "Waiting for status to be reported"})
}
}
slices.SortStableFunc(kept, func(a, b Check) int { return strings.Compare(a.Name, b.Name) })
return kept
}
+3 -3
View File
@@ -47,7 +47,7 @@ func TestCheckWatchRevalidatesHeadBeforeReturning(t *testing.T) {
service := Pulls{Client: client, Repository: "owner/repo"}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
items, err := service.WatchChecks(ctx, 7, time.Millisecond, nil)
items, err := service.WatchChecks(ctx, 7, time.Millisecond, false, nil)
require.NoError(t, err)
require.Len(t, items, 1)
require.Equal(t, "new", items[0].SHA)
@@ -77,7 +77,7 @@ func TestCheckWatchReportsTheEmptyStateOnce(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
var reported []int
_, err := (Pulls{Client: client, Repository: "owner/repo"}).WatchChecks(ctx, 7, time.Millisecond, func(items []Check) error {
_, err := (Pulls{Client: client, Repository: "owner/repo"}).WatchChecks(ctx, 7, time.Millisecond, false, func(items []Check) error {
reported = append(reported, len(items))
return nil
})
@@ -105,7 +105,7 @@ func TestCheckWatchTreatsSkippedAsPassing(t *testing.T) {
}))
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
items, err := (Pulls{Client: client, Repository: "owner/repo"}).WatchChecks(ctx, 7, time.Millisecond, nil)
items, err := (Pulls{Client: client, Repository: "owner/repo"}).WatchChecks(ctx, 7, time.Millisecond, false, nil)
require.NoError(t, err)
require.Equal(t, 2, snapshots)
require.Equal(t, "success", items[1].State)
+1 -1
View File
@@ -120,7 +120,7 @@ func TestCheckWatchRidesOutAShortOutage(t *testing.T) {
_, _ = w.Write([]byte(`[{"id":1,"context":"build","status":"` + state + `"}]`))
}))
client.Retries = 0
items, err := Pulls{Client: client, Repository: "owner/repo"}.WatchChecks(context.Background(), 7, time.Millisecond, nil)
items, err := Pulls{Client: client, Repository: "owner/repo"}.WatchChecks(context.Background(), 7, time.Millisecond, false, nil)
require.NoError(t, err)
require.Equal(t, "success", items[0].State)
}
+19 -1
View File
@@ -1258,6 +1258,8 @@ func (s Pulls) Files(ctx context.Context, n int64) ([]string, error) {
type MergeOptions struct {
Method, Title, Message string
DeleteBranch, Auto bool
// Force merges although the branch protection is not met, if Gitea lets the user bypass it.
Force bool
// HeadSHA is the head commit the user chose to merge; Gitea refuses the merge once the head
// moved past it. Empty merges the current head.
HeadSHA string
@@ -1302,6 +1304,22 @@ func (s Pulls) MergeSettings(ctx context.Context) (MergeSettings, error) {
return settings, nil
}
// CancelAutoMerge cancels the merge that Gitea scheduled for when the checks succeed. It reports
// false when none was scheduled, which Gitea answers with a bare 404 like that of a missing pull
// request: the caller has found the pull request already.
func (s Pulls) CancelAutoMerge(ctx context.Context, n int64) (bool, error) {
err := repoDo(ctx, s.Client, s.Repository, func(ctx context.Context, c *gitea.Client, owner, name string) (*gitea.Response, error) {
return c.PullRequests.CancelScheduledAutoMerge(ctx, owner, name, n)
})
if IsNotFound(err) {
return false, nil
}
if err != nil {
return false, Classify(err, "pull request", "#"+strconv.FormatInt(n, 10), s.Repository)
}
return true, nil
}
// ErrPullUpToDate reports a head branch that already has every commit of its base branch.
var ErrPullUpToDate = errors.New("the head branch already has the commits of the base branch")
@@ -1380,7 +1398,7 @@ func (s Pulls) Merge(ctx context.Context, n int64, opts MergeOptions) error {
}
option := gitea.MergePullRequestOption{
Style: gitea.MergeStyle(opts.Method), Title: opts.Title, Message: opts.Message, DeleteBranchAfterMerge: &opts.DeleteBranch,
MergeWhenChecksSucceed: opts.Auto, MergeCommitID: opts.Commit,
MergeWhenChecksSucceed: opts.Auto, MergeCommitID: opts.Commit, ForceMerge: opts.Force,
}
if option.HeadCommitId = opts.HeadSHA; option.HeadCommitId == "" && pull.Head != nil {
option.HeadCommitId = pull.Head.Sha
+1 -1
View File
@@ -156,7 +156,7 @@ of the diff; gt refuses lines outside the diff. See [resources.md](references/re
| 3 | Canceled: a declined confirmation or prompt, or a wait's `--timeout` expired |
| 4 | Authentication missing or rejected |
| 5 | `gt run watch` and `gt workflow run --follow`: the run completed without success |
| 6 | `gt run watch --expect-head`: the run is for another commit |
| 6 | `gt run watch --expect-head`: the run is for another commit; `gt pr merge`: the head is not the commit to merge, such as the one `--match-head-commit` names |
| 8 | `gt pr checks`: checks still pending |
| 130 | Interrupted with Ctrl-C |
+3
View File
@@ -178,6 +178,9 @@ gt pr review resolve 1234 --no-input
```sh
gt pr merge 18 --squash --delete-branch --no-input --yes
gt pr merge 18 --auto --no-input --yes # merge once required checks succeed
gt pr merge 18 --disable-auto --no-input # cancel that scheduled merge
gt pr merge 18 --squash --match-head-commit 4b825dc --no-input --yes # only the commit that was reviewed
gt pr checks 18 --required --watch --no-input # only the checks the branch protection requires
gt pr clean 18 --no-input --yes # delete the branches of a merged pull request
gt pr backport 18 --to release/v1.2 --no-input --yes --json pull
```