gitea.tea/modules/task/pull_delete_branch_test.go
Jan Baer 5aedf30e7b feat(pulls): offer to delete the source branch after merging
Implements #1050.

Prompt to delete the source branch after a successful tea pr merge,
displaying the branch name because deletion cannot be undone.
--delete-branch skips the prompt for scripts; this flag was requested
in #810 for gh parity before being closed as an upstream Gitea bug.

PullDeleteBranch takes a confirmation callback rather than prompting
directly, fetching the pull request once and passing the branch name
to the caller. The callback runs after state and permission checks so
the user is not prompted for a deletion that would fail anyway.

Deletion uses the API against the head repository, so it works for
pull requests opened from a fork never checked out locally.
tea pr clean is unsuitable because it requires a local repo and fails
when the branch is not found locally. A matching local branch is still
removed as a best effort, matched by commit rather than name so a branch
with unpushed commits is left alone; PullClean makes the same choice
and only accepts name matching behind --ignore-sha.

The prompt is gated on stdin and stdout both being terminals, following
the existing check in modules/context. TeaContext.IsInteractiveMode
could not be used: despite its doc comment, it only reports whether any
flag was passed, so a script running a bare tea pr merge <idx> would
have blocked on a prompt it could not answer.

Branches already deleted server-side, PRs still open, and head
repositories the user cannot push to are each handled explicitly rather
than surfacing a raw API error.

Signed-off-by: Jan Baer <jan.s.baer@googlemail.com>
2026-09-01 09:00:22 +02:00

162 lines
4.9 KiB
Go

// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package task
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitea.dev/tea/modules/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// testHeadSHA stands in for the head commit when no local repo is involved.
const testHeadSHA = "abc123"
// prJSON builds a merged PR with its head in headOwner/headRepo. A headRef of
// "refs/pull/7/head" is how Gitea reports an already-deleted branch.
func prJSON(headOwner, headRepo, headRef, headSHA string, canPush bool) string {
return fmt.Sprintf(`{
"number": 7,
"state": "closed",
"merged": true,
"base": {"ref": "main"},
"head": {
"label": "feature-x",
"ref": %q,
"sha": %q,
"repo": {
"name": %q,
"full_name": "%s/%s",
"owner": {"login": %q},
"clone_url": "https://example.invalid/%s/%s.git",
"permissions": {"admin": false, "push": %t, "pull": true}
}
}
}`, headRef, headSHA, headRepo, headOwner, headRepo, headOwner, headOwner, headRepo, canPush)
}
// deleteBranchServer serves the PR and records any branch DELETE, so tests can
// assert which repo it was addressed to.
func deleteBranchServer(t *testing.T, pr string, deleted *string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodDelete && strings.Contains(r.URL.Path, "/branches/") {
*deleted = r.URL.Path
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method == http.MethodGet {
_, _ = w.Write([]byte(pr))
return
}
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusInternalServerError)
}))
}
func TestPullDeleteBranch(t *testing.T) {
tests := []struct {
name string
pr string
confirm func(branch string) (bool, error)
wantDeleted string
wantErr string
}{
{
// The branch is in the fork, so the DELETE must go there.
name: "deletes the head branch in the fork",
pr: prJSON("contributor", "tea", "feature-x", testHeadSHA, true),
wantDeleted: "/api/v1/repos/contributor/tea/branches/feature-x",
},
{
name: "same-repo branch",
pr: prJSON("owner", "repo", "feature-x", testHeadSHA, true),
wantDeleted: "/api/v1/repos/owner/repo/branches/feature-x",
},
{
// Gitea removed it already: repo setting, or the web UI.
name: "already deleted upstream is a no-op",
pr: prJSON("contributor", "tea", "refs/pull/7/head", testHeadSHA, true),
},
{
name: "no push permission",
pr: prJSON("contributor", "tea", "feature-x", testHeadSHA, false),
wantErr: "no permission to delete branch 'feature-x' in contributor/tea",
},
{
name: "PR still open",
pr: strings.Replace(prJSON("owner", "repo", "feature-x", testHeadSHA, true), `"state": "closed"`, `"state": "open"`, 1),
wantErr: "PR is still open, won't delete branches",
},
{
// The prompt gets the real name so it can say what it deletes.
name: "confirm is asked with the branch name",
pr: prJSON("contributor", "tea", "feature-x", testHeadSHA, true),
confirm: func(branch string) (bool, error) {
if branch != "feature-x" {
return false, fmt.Errorf("confirm got branch %q, want feature-x", branch)
}
return true, nil
},
wantDeleted: "/api/v1/repos/contributor/tea/branches/feature-x",
},
{
name: "declining the prompt deletes nothing",
pr: prJSON("contributor", "tea", "feature-x", testHeadSHA, true),
confirm: func(string) (bool, error) { return false, nil },
},
{
name: "confirm error aborts",
pr: prJSON("contributor", "tea", "feature-x", testHeadSHA, true),
confirm: func(string) (bool, error) { return false, fmt.Errorf("interrupted") },
wantErr: "interrupted",
},
{
// Nothing is deletable, so don't ask.
name: "not asked when there is no push permission",
pr: prJSON("contributor", "tea", "feature-x", testHeadSHA, false),
confirm: func(string) (bool, error) {
t.Error("confirm called despite missing push permission")
return true, nil
},
wantErr: "no permission to delete branch 'feature-x' in contributor/tea",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Outside a repo, deleteLocalBranch is a no-op.
t.Chdir(t.TempDir())
var deleted string
server := deleteBranchServer(t, tt.pr, &deleted)
defer server.Close()
err := PullDeleteBranch(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
VersionCheck: false,
}, "owner", "repo", 7, tt.confirm)
if tt.wantErr == "" {
require.NoError(t, err)
} else {
require.Error(t, err)
assert.Equal(t, tt.wantErr, err.Error())
}
assert.Equal(t, tt.wantDeleted, deleted)
})
}
}