Compare commits

..

3 Commits

Author SHA1 Message Date
lunny b06d902687 feat(pulls): support branch-validated stack reordering
Assisted-by: Codet:GPT-5-Codex
2026-09-24 23:31:32 -07:00
lunny f28a5e696a fix(pulls): report stack merge API permission errors
Assisted-by: Codet:GPT-5-Codex
2026-09-24 23:27:23 -07:00
lunny ba167a7352 feat(pulls): add tea pr stack list|show|push|restack|merge
Adds a CLI client for the Gitea EE pull request stack API
(GET/POST /repos/{owner}/{repo}/stacks[/{id}[/entries|/restack|/merge]]):

- modules/stack holds the Stack/Entry/MergeResult types shared between
  the API client and its output formatting, avoiding an import cycle
  between modules/task and modules/print.
- modules/task/pull_stack.go implements the HTTP calls on top of
  modules/api.Client, which gains a context-aware DoContext method.
- modules/print/pull_stack.go formats stack listings (table/json/...)
  and a single stack's ordered entries.
- cmd/pulls/stack adds the list, show, push, restack and merge
  subcommands, wired in as 'tea pr stack' via cmd/pulls.go, following
  the repo/login flag routing used by the rest of the pulls commands.

Assisted-by: Codet:GPT-5-Codex
2026-09-24 23:24:26 -07:00
34 changed files with 1274 additions and 223 deletions
-5
View File
@@ -6,11 +6,6 @@
[![Go Report Card](https://goreportcard.com/badge/gitea.dev/tea)](https://goreportcard.com/report/gitea.dev/tea) [![GoDoc](https://pkg.go.dev/badge/gitea.dev/tea?status.svg)](https://godoc.org/gitea.dev/tea)
![Tea Release Status](https://gitea.com/gitea/tea/actions/workflows/release-nightly.yml/badge.svg)
> [!IMPORTANT]
> tea has been replaced by [gt](https://gitea.com/gitea/cli), the new official CLI for Gitea, and this repository will be archived.
> Please use gt and open new issues and pull requests at https://gitea.com/gitea/cli.
> See [Migrating from tea](https://gitea.com/gitea/cli/src/branch/main/docs/migrating-from-tea.md) for the command mapping.
## The official CLI for Gitea
![demo gif](./demo.gif)
+1
View File
@@ -82,6 +82,7 @@ var CmdPulls = cli.Command{
&pulls.CmdPullsReviewComments,
&pulls.CmdPullsResolve,
&pulls.CmdPullsUnresolve,
&pulls.CmdPullsStack,
},
}
+32
View File
@@ -0,0 +1,32 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package pulls
import (
stdctx "context"
"gitea.dev/tea/cmd/pulls/stack"
"github.com/urfave/cli/v3"
)
// CmdPullsStack represents the stack command to manage pull request stacks
var CmdPullsStack = cli.Command{
Name: "stack",
Usage: "Manage pull request stacks",
Description: "List, show, push, reorder, restack, and merge pull request stacks",
Action: runPullsStackDefault,
Commands: []*cli.Command{
&stack.CmdStackList,
&stack.CmdStackShow,
&stack.CmdStackPush,
&stack.CmdStackRestack,
&stack.CmdStackReorder,
&stack.CmdStackMerge,
},
}
func runPullsStackDefault(ctx stdctx.Context, cmd *cli.Command) error {
return stack.RunStackList(ctx, cmd)
}
+53
View File
@@ -0,0 +1,53 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
stdctx "context"
"gitea.dev/tea/cmd/flags"
"gitea.dev/tea/modules/context"
"gitea.dev/tea/modules/print"
"gitea.dev/tea/modules/task"
"github.com/urfave/cli/v3"
)
var stackFieldsFlag = flags.FieldsFlag(print.PullStackFields, []string{
"id", "title", "base", "state", "entries",
})
// CmdStackList represents a sub command to list pull request stacks
var CmdStackList = cli.Command{
Name: "list",
Aliases: []string{"ls"},
Usage: "List pull request stacks of the repository",
Description: "List pull request stacks of the repository",
ArgsUsage: " ", // command does not accept arguments
Action: RunStackList,
Flags: append([]cli.Flag{stackFieldsFlag}, flags.AllDefaultFlags...),
}
// RunStackList lists pull request stacks of the repository
func RunStackList(requestCtx stdctx.Context, cmd *cli.Command) error {
ctx, err := context.InitCommand(cmd)
if err != nil {
return err
}
if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
return err
}
stacks, err := task.ListPullStacks(requestCtx, ctx.Login, ctx.Owner, ctx.Repo)
if err != nil {
return err
}
fields, err := stackFieldsFlag.GetValues(cmd)
if err != nil {
return err
}
return print.PullStacksList(stacks, ctx.Output, fields)
}
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v3"
"gitea.dev/tea/modules/config"
)
func TestRunStackListRequiresRepoContext(t *testing.T) {
oldWd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(t.TempDir()))
t.Cleanup(func() {
require.NoError(t, os.Chdir(oldWd))
})
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
Name: "test",
URL: "https://gitea.example.com",
Token: "token",
User: "tester",
Default: true,
}},
})
cmd := &cli.Command{
Name: CmdStackList.Name,
Flags: CmdStackList.Flags,
}
require.NoError(t, cmd.Set("login", "test"))
err = RunStackList(t.Context(), cmd)
require.ErrorContains(t, err, "remote repository required")
}
+73
View File
@@ -0,0 +1,73 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
stdctx "context"
"fmt"
"gitea.dev/tea/cmd/flags"
"gitea.dev/tea/modules/context"
"gitea.dev/tea/modules/task"
"gitea.dev/tea/modules/utils"
"github.com/urfave/cli/v3"
)
// CmdStackMerge represents a sub command to merge a pull request stack in order
var CmdStackMerge = cli.Command{
Name: "merge",
Aliases: []string{"m"},
Usage: "Merge a pull request stack in order",
Description: "Merge every pull request of a stack in order, bottom first",
ArgsUsage: "<stack id>",
Action: RunStackMerge,
Flags: append([]cli.Flag{
&cli.StringFlag{
Name: "style",
Aliases: []string{"s"},
Usage: "Kind of merge to perform: merge, rebase, squash, rebase-merge",
Value: "merge",
},
&cli.BoolFlag{
Name: "wait-for-ci",
Usage: "Schedule the merge to run once required checks pass, instead of merging immediately",
},
}, flags.AllDefaultFlags...),
}
// RunStackMerge merges every pull request of a stack in order
func RunStackMerge(requestCtx stdctx.Context, cmd *cli.Command) error {
if cmd.Args().Len() != 1 {
return fmt.Errorf("stack id is required")
}
id, err := utils.ArgToIndex(cmd.Args().First())
if err != nil {
return err
}
ctx, err := context.InitCommand(cmd)
if err != nil {
return err
}
if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
return err
}
result, queued, err := task.MergePullStack(requestCtx, ctx.Login, ctx.Owner, ctx.Repo, id,
cmd.String("style"), cmd.Bool("wait-for-ci"))
if queued {
fmt.Fprintf(ctx.Writer, "merge for stack #%d scheduled\n", id)
return nil
}
if err != nil {
if result != nil {
return fmt.Errorf("merged %d pull request(s) before failing: %w", result.Merged, err)
}
return err
}
fmt.Fprintf(ctx.Writer, "merged %d pull request(s) of stack #%d\n", result.Merged, id)
return nil
}
+32
View File
@@ -0,0 +1,32 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
"context"
"testing"
"gitea.dev/tea/modules/config"
"github.com/stretchr/testify/assert"
)
func TestStackMergeRequiresStackID(t *testing.T) {
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
Name: "testLogin",
URL: "https://gitea.example.com",
Token: "test-token",
User: "testUser",
Default: true,
}},
})
t.Cleanup(func() {
config.SetConfigForTesting(config.LocalConfig{})
})
cmd := CmdStackMerge
err := cmd.Run(context.Background(), []string{"merge", "--login", "testLogin", "--repo", "user/repo"})
assert.ErrorContains(t, err, "stack id is required")
}
+69
View File
@@ -0,0 +1,69 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
stdctx "context"
"fmt"
"gitea.dev/tea/cmd/flags"
"gitea.dev/tea/modules/context"
"gitea.dev/tea/modules/print"
pullstack "gitea.dev/tea/modules/stack"
"gitea.dev/tea/modules/task"
"gitea.dev/tea/modules/utils"
"github.com/urfave/cli/v3"
)
// CmdStackPush represents a sub command to link a pull request onto a stack
var CmdStackPush = cli.Command{
Name: "push",
Usage: "Link a pull request onto a stack",
Description: "Link a child pull request onto its parent, creating a new stack or extending an existing one with --stack",
ArgsUsage: "<parent index> <child index>",
Action: RunStackPush,
Flags: append([]cli.Flag{
&cli.Int64Flag{
Name: "stack",
Usage: "id of an existing stack to append the pull requests to, instead of creating a new stack",
},
}, flags.AllDefaultFlags...),
}
// RunStackPush links a parent and a child pull request into a stack
func RunStackPush(requestCtx stdctx.Context, cmd *cli.Command) error {
if cmd.Args().Len() != 2 {
return fmt.Errorf("parent index and child index are required")
}
parentIndex, err := utils.ArgToIndex(cmd.Args().Get(0))
if err != nil {
return err
}
childIndex, err := utils.ArgToIndex(cmd.Args().Get(1))
if err != nil {
return err
}
ctx, err := context.InitCommand(cmd)
if err != nil {
return err
}
if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
return err
}
var s *pullstack.Stack
if stackID := cmd.Int64("stack"); stackID != 0 {
s, err = task.AddPullStackEntry(requestCtx, ctx.Login, ctx.Owner, ctx.Repo, stackID, parentIndex, childIndex)
} else {
s, err = task.CreatePullStack(requestCtx, ctx.Login, ctx.Owner, ctx.Repo, parentIndex, childIndex)
}
if err != nil {
return err
}
print.PullStackDetail(s)
return nil
}
+63
View File
@@ -0,0 +1,63 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
"context"
"testing"
"gitea.dev/tea/modules/config"
"github.com/stretchr/testify/assert"
)
func TestStackPush(t *testing.T) {
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
Name: "testLogin",
URL: "https://gitea.example.com",
Token: "test-token",
User: "testUser",
Default: true,
}},
})
t.Cleanup(func() {
config.SetConfigForTesting(config.LocalConfig{})
})
tests := []struct {
name string
args []string
errContains string
}{
{
name: "no arguments",
args: []string{},
errContains: "parent index and child index are required",
},
{
name: "missing child index",
args: []string{"1"},
errContains: "parent index and child index are required",
},
{
name: "non-numeric parent index",
args: []string{"abc", "2"},
errContains: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := CmdStackPush
args := append([]string{"push"}, tt.args...)
args = append(args, "--login", "testLogin", "--repo", "user/repo")
err := cmd.Run(context.Background(), args)
assert.Error(t, err)
if tt.errContains != "" {
assert.Contains(t, err.Error(), tt.errContains)
}
})
}
}
+53
View File
@@ -0,0 +1,53 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
stdctx "context"
"fmt"
"gitea.dev/tea/cmd/flags"
"gitea.dev/tea/modules/context"
"gitea.dev/tea/modules/task"
"gitea.dev/tea/modules/utils"
"github.com/urfave/cli/v3"
)
// CmdStackReorder stores a validated, already-linked PR branch order.
var CmdStackReorder = cli.Command{
Name: "reorder", Usage: "Reorder PRs after their branches have been rebased",
ArgsUsage: "<stack id> <pull index> <pull index> [more pull indices]",
Flags: flags.AllDefaultFlags, Action: RunStackReorder,
}
func RunStackReorder(requestCtx stdctx.Context, cmd *cli.Command) error {
if cmd.Args().Len() < 3 {
return fmt.Errorf("stack id and at least two pull numbers are required")
}
stackID, err := utils.ArgToIndex(cmd.Args().Get(0))
if err != nil {
return err
}
indices := make([]int64, 0, cmd.Args().Len()-1)
for i := 1; i < cmd.Args().Len(); i++ {
index, err := utils.ArgToIndex(cmd.Args().Get(i))
if err != nil {
return err
}
indices = append(indices, index)
}
ctx, err := context.InitCommand(cmd)
if err != nil {
return err
}
if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
return err
}
if _, err := task.ReorderPullStack(requestCtx, ctx.Login, ctx.Owner, ctx.Repo, stackID, indices); err != nil {
return err
}
fmt.Fprintf(ctx.Writer, "reordered stack #%d\n", stackID)
return nil
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
func TestStackReorderRequiresCompleteOrder(t *testing.T) {
cmd := CmdStackReorder
err := cmd.Run(context.Background(), []string{"reorder", "5", "2"})
assert.ErrorContains(t, err, "at least two pull numbers")
}
+52
View File
@@ -0,0 +1,52 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
stdctx "context"
"fmt"
"gitea.dev/tea/cmd/flags"
"gitea.dev/tea/modules/context"
"gitea.dev/tea/modules/task"
"gitea.dev/tea/modules/utils"
"github.com/urfave/cli/v3"
)
// CmdStackRestack represents a sub command to queue a stack restack
var CmdStackRestack = cli.Command{
Name: "restack",
Usage: "Queue a pull request stack restack",
Description: "Retarget every open pull request above a merged one in the stack onto its parent's new base",
ArgsUsage: "<stack id>",
Action: RunStackRestack,
Flags: flags.AllDefaultFlags,
}
// RunStackRestack queues a restack of a pull request stack
func RunStackRestack(requestCtx stdctx.Context, cmd *cli.Command) error {
if cmd.Args().Len() != 1 {
return fmt.Errorf("stack id is required")
}
id, err := utils.ArgToIndex(cmd.Args().First())
if err != nil {
return err
}
ctx, err := context.InitCommand(cmd)
if err != nil {
return err
}
if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
return err
}
if err := task.RestackPullStack(requestCtx, ctx.Login, ctx.Owner, ctx.Repo, id); err != nil {
return err
}
fmt.Fprintf(ctx.Writer, "restack for stack #%d queued\n", id)
return nil
}
+32
View File
@@ -0,0 +1,32 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
"context"
"testing"
"gitea.dev/tea/modules/config"
"github.com/stretchr/testify/assert"
)
func TestStackRestackRequiresStackID(t *testing.T) {
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
Name: "testLogin",
URL: "https://gitea.example.com",
Token: "test-token",
User: "testUser",
Default: true,
}},
})
t.Cleanup(func() {
config.SetConfigForTesting(config.LocalConfig{})
})
cmd := CmdStackRestack
err := cmd.Run(context.Background(), []string{"restack", "--login", "testLogin", "--repo", "user/repo"})
assert.ErrorContains(t, err, "stack id is required")
}
+62
View File
@@ -0,0 +1,62 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
stdctx "context"
"encoding/json"
"fmt"
"gitea.dev/tea/cmd/flags"
"gitea.dev/tea/modules/context"
"gitea.dev/tea/modules/print"
"gitea.dev/tea/modules/task"
"gitea.dev/tea/modules/utils"
"github.com/urfave/cli/v3"
)
// CmdStackShow represents a sub command to show a pull request stack
var CmdStackShow = cli.Command{
Name: "show",
Aliases: []string{"get"},
Usage: "Show a pull request stack",
Description: "Show a pull request stack, its base branch and its ordered pull requests",
ArgsUsage: "<stack id>",
Action: RunStackShow,
Flags: flags.AllDefaultFlags,
}
// RunStackShow shows a pull request stack
func RunStackShow(requestCtx stdctx.Context, cmd *cli.Command) error {
if cmd.Args().Len() != 1 {
return fmt.Errorf("stack id is required")
}
id, err := utils.ArgToIndex(cmd.Args().First())
if err != nil {
return err
}
ctx, err := context.InitCommand(cmd)
if err != nil {
return err
}
if err := ctx.Ensure(context.CtxRequirement{RemoteRepo: true}); err != nil {
return err
}
s, err := task.GetPullStack(requestCtx, ctx.Login, ctx.Owner, ctx.Repo, id)
if err != nil {
return err
}
if ctx.String("output") == "json" {
encoder := json.NewEncoder(ctx.Writer)
encoder.SetIndent("", "\t")
return encoder.Encode(s)
}
print.PullStackDetail(s)
return nil
}
+51
View File
@@ -0,0 +1,51 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package stack
import (
"context"
"testing"
"gitea.dev/tea/modules/config"
"github.com/stretchr/testify/assert"
)
func TestStackShowRequiresStackID(t *testing.T) {
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
Name: "testLogin",
URL: "https://gitea.example.com",
Token: "test-token",
User: "testUser",
Default: true,
}},
})
t.Cleanup(func() {
config.SetConfigForTesting(config.LocalConfig{})
})
cmd := CmdStackShow
err := cmd.Run(context.Background(), []string{"show", "--login", "testLogin", "--repo", "user/repo"})
assert.ErrorContains(t, err, "stack id is required")
}
func TestStackShowRejectsInvalidStackID(t *testing.T) {
config.SetConfigForTesting(config.LocalConfig{
Logins: []config.Login{{
Name: "testLogin",
URL: "https://gitea.example.com",
Token: "test-token",
User: "testUser",
Default: true,
}},
})
t.Cleanup(func() {
config.SetConfigForTesting(config.LocalConfig{})
})
cmd := CmdStackShow
err := cmd.Run(context.Background(), []string{"show", "notanumber", "--login", "testLogin", "--repo", "user/repo"})
assert.Error(t, err)
}
+1 -1
View File
@@ -2,7 +2,7 @@ module gitea.dev/tea
go 1.26.0
toolchain go1.26.10
toolchain go1.26.6
require (
charm.land/glamour/v2 v2.0.1
+7 -1
View File
@@ -4,6 +4,7 @@
package api
import (
"context"
"crypto/tls"
"fmt"
"io"
@@ -43,13 +44,18 @@ func NewClient(login *config.Login) *Client {
// Do executes an HTTP request with authentication headers
func (c *Client) Do(method, endpoint string, body io.Reader, headers map[string]string) (*http.Response, error) {
return c.DoContext(context.Background(), method, endpoint, body, headers)
}
// DoContext executes an HTTP request with authentication headers, bound to ctx
func (c *Client) DoContext(ctx context.Context, method, endpoint string, body io.Reader, headers map[string]string) (*http.Response, error) {
// Build the full URL
reqURL, err := c.buildURL(endpoint)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, reqURL, body)
req, err := http.NewRequestWithContext(ctx, method, reqURL, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
+3 -12
View File
@@ -489,7 +489,7 @@ func (l *Login) ClientWithoutRefresh(options ...gitea.ClientOption) *gitea.Clien
fmt.Fprintf(os.Stderr, "Failed to read SSH passphrase: %s\n", err)
os.Exit(1)
}
options = append(options, gitea.UseSSHCert(l.SSHCertPrincipal, l.SSHKeyPath(), l.SSHPassphrase))
options = append(options, gitea.UseSSHCert(l.SSHCertPrincipal, l.SSHKey, l.SSHPassphrase))
}
if l.SSHKeyFingerprint != "" {
@@ -497,7 +497,7 @@ func (l *Login) ClientWithoutRefresh(options ...gitea.ClientOption) *gitea.Clien
fmt.Fprintf(os.Stderr, "Failed to read SSH passphrase: %s\n", err)
os.Exit(1)
}
options = append(options, gitea.UseSSHPubkey(l.SSHKeyFingerprint, l.SSHKeyPath(), l.SSHPassphrase))
options = append(options, gitea.UseSSHPubkey(l.SSHKeyFingerprint, l.SSHKey, l.SSHPassphrase))
}
client, err := gitea.NewClient(l.URL, options...)
@@ -513,7 +513,7 @@ func (l *Login) ClientWithoutRefresh(options ...gitea.ClientOption) *gitea.Clien
}
func (l *Login) askForSSHPassphrase() error {
if ok, err := utils.IsKeyEncrypted(l.SSHKeyPath()); ok && err == nil && l.SSHPassphrase == "" {
if ok, err := utils.IsKeyEncrypted(l.SSHKey); ok && err == nil && l.SSHPassphrase == "" {
return huh.NewInput().
Title("ssh-key is encrypted please enter the passphrase: ").
Validate(huh.ValidateNotEmpty()).
@@ -525,15 +525,6 @@ func (l *Login) askForSSHPassphrase() error {
return nil
}
// SSHKeyPath returns the on-disk SSH key to use, or an empty string when the
// login is configured to authenticate through a running ssh-agent.
func (l *Login) SSHKeyPath() string {
if l.SSHAgent {
return ""
}
return l.SSHKey
}
// GetSSHHost returns SSH host name
func (l *Login) GetSSHHost() string {
if l.SSHHost != "" {
-33
View File
@@ -90,39 +90,6 @@ func TestLoginClientWithSSHPubkeyDoesNotDeadlockOnFirstRequest(t *testing.T) {
assert.EqualValues(t, 1, signedIssueRequests.Load())
}
func TestLoginSSHKeyPath(t *testing.T) {
t.Parallel()
tests := []struct {
name string
login Login
want string
}{
{
name: "disk key",
login: Login{SSHKey: "/tmp/id_ed25519"},
want: "/tmp/id_ed25519",
},
{
name: "ssh agent ignores disk key",
login: Login{SSHKey: "/tmp/id_ed25519", SSHAgent: true},
want: "",
},
{
name: "ssh agent without disk key",
login: Login{SSHAgent: true},
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tt.want, tt.login.SSHKeyPath())
})
}
}
func writeTestSSHKey(t *testing.T) (string, string) {
t.Helper()
+1 -16
View File
@@ -258,21 +258,6 @@ func (e *gitCommandError) Unwrap() error {
return e.err
}
func gitCommandEnv(authEnv []string) []string {
baseEnv := os.Environ()
env := make([]string, 0, len(baseEnv)+len(authEnv)+3)
for _, value := range baseEnv {
if strings.HasPrefix(value, "LC_ALL=") ||
strings.HasPrefix(value, "LANG=") ||
strings.HasPrefix(value, "LANGUAGE=") {
continue
}
env = append(env, value)
}
env = append(env, authEnv...)
return append(env, "LC_ALL=C", "LANG=C", "LANGUAGE=C")
}
func runGitCommand(dir string, auth *AuthMethod, extraConfigs []string, args ...string) (string, error) {
authConfigs, authEnv, cleanup, err := prepareCLIAuth(auth)
if err != nil {
@@ -293,7 +278,7 @@ func runGitCommand(dir string, auth *AuthMethod, extraConfigs []string, args ...
if dir != "" {
cmd.Dir = dir
}
cmd.Env = gitCommandEnv(authEnv)
cmd.Env = append(os.Environ(), authEnv...)
var stdout bytes.Buffer
var stderr bytes.Buffer
-40
View File
@@ -1,40 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package git
import (
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/require"
)
func TestOpenClassifiesLocalizedNotRepoError(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("test uses a POSIX shell script as fake git")
}
fakeGitDir := t.TempDir()
fakeGit := filepath.Join(fakeGitDir, "git")
script := `#!/bin/sh
locale="${LC_ALL:-${LANG:-C}}"
if [ "$locale" = "C" ]; then
echo "fatal: not a git repository (or any of the parent directories): .git" >&2
else
echo "fatal: Kein Git-Repository (oder irgendein Elternverzeichnis bis zum Einhangepunkt /)" >&2
fi
exit 128
`
require.NoError(t, os.WriteFile(fakeGit, []byte(script), 0o755))
t.Setenv("PATH", fakeGitDir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("LC_ALL", "de_DE.UTF-8")
t.Setenv("LANG", "de_DE.UTF-8")
t.Setenv("LANGUAGE", "de_DE:de")
_, err := (cliBackend{}).Open(t.TempDir())
require.ErrorIs(t, err, ErrRepositoryNotExists)
}
+6 -20
View File
@@ -5,8 +5,6 @@ package interact
import (
stdctx "context"
"os"
"strconv"
gitea "gitea.dev/sdk"
"gitea.dev/tea/modules/context"
@@ -45,14 +43,12 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext) (err error)
}
}
if isAgitPromptEnabled() {
if err := huh.NewConfirm().
Title("Do you want to create an agit flow pull request?").
Value(&agit).
WithTheme(theme.GetTheme()).
Run(); err != nil {
return err
}
if err := huh.NewConfirm().
Title("Do you want to create an agit flow pull request?").
Value(&agit).
WithTheme(theme.GetTheme()).
Run(); err != nil {
return err
}
if agit {
@@ -154,13 +150,3 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext) (err error)
return nil
}
func isAgitPromptEnabled() bool {
value, ok := os.LookupEnv("TEA_USE_AGIT")
if !ok {
return true
}
useAgit, err := strconv.ParseBool(value)
return err != nil || useAgit
}
-50
View File
@@ -1,50 +0,0 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package interact
import (
"os"
"testing"
)
func TestIsAgitPromptEnabled(t *testing.T) {
t.Run("default enabled", func(t *testing.T) {
previous, hadPrevious := os.LookupEnv("TEA_USE_AGIT")
if err := os.Unsetenv("TEA_USE_AGIT"); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if hadPrevious {
if err := os.Setenv("TEA_USE_AGIT", previous); err != nil {
t.Fatal(err)
}
}
})
if !isAgitPromptEnabled() {
t.Fatal("isAgitPromptEnabled() = false, want true")
}
})
tests := []struct {
name string
value string
want bool
}{
{name: "zero disables", value: "0", want: false},
{name: "false disables", value: "false", want: false},
{name: "true enables", value: "true", want: true},
{name: "invalid enables", value: "invalid", want: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Setenv("TEA_USE_AGIT", test.value)
if got := isAgitPromptEnabled(); got != test.want {
t.Fatalf("isAgitPromptEnabled() = %v, want %v", got, test.want)
}
})
}
}
+71
View File
@@ -0,0 +1,71 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package print
import (
"fmt"
"strings"
"gitea.dev/tea/modules/stack"
)
// PullStackFields are all available fields to print with PullStacksList()
var PullStackFields = []string{
"id",
"title",
"base",
"state",
"auto-restack",
"entries",
}
// PullStacksList prints a listing of pull request stacks
func PullStacksList(stacks []*stack.Stack, output string, fields []string) error {
printables := make([]printable, len(stacks))
for i, s := range stacks {
printables[i] = &printablePullStack{s}
}
t := tableFromItems(fields, printables, isMachineReadable(output))
return t.print(output)
}
type printablePullStack struct {
*stack.Stack
}
func (x printablePullStack) FormatField(field string, machineReadable bool) string {
switch field {
case "id":
return fmt.Sprintf("%d", x.ID)
case "title":
return x.Title
case "base":
return x.BaseBranch
case "state":
return x.State
case "auto-restack":
return formatBoolean(x.AutoRestack, !machineReadable)
case "entries":
return fmt.Sprintf("%d", len(x.Entries))
}
return ""
}
// PullStackDetail prints a pull request stack, bottom entry first, rendered to stdout
func PullStackDetail(s *stack.Stack) {
out := fmt.Sprintf(
"# Stack #%d: %s (%s)\nbase: **%s**\tauto-restack: %s\n\n",
s.ID, s.Title, s.State, s.BaseBranch, formatBoolean(s.AutoRestack, true),
)
for _, entry := range s.Entries {
if entry.ParentPullID == 0 {
out += fmt.Sprintf("- #%d (%s)\n", entry.PullID, entry.State)
} else {
out += fmt.Sprintf("- #%d <- #%d (%s)\n", entry.PullID, entry.ParentPullID, entry.State)
}
}
outputMarkdown(strings.TrimRight(out, "\n")+"\n", "")
}
+61
View File
@@ -0,0 +1,61 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package print
import (
"bytes"
"encoding/json"
"testing"
"gitea.dev/tea/modules/stack"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPullStacksListJSON(t *testing.T) {
stacks := []*stack.Stack{
{
ID: 1, Title: "feat: base", BaseBranch: "main", State: "open", AutoRestack: true,
Entries: []stack.Entry{{PullID: 10}, {PullID: 11}},
},
}
buf := &bytes.Buffer{}
tbl := tableFromItems(
PullStackFields,
[]printable{&printablePullStack{stacks[0]}},
true,
)
require.NoError(t, tbl.fprint(buf, "json"))
var result []map[string]string
require.NoError(t, json.Unmarshal(buf.Bytes(), &result))
require.Len(t, result, 1)
assert.Equal(t, "1", result[0]["id"])
assert.Equal(t, "feat: base", result[0]["title"])
assert.Equal(t, "main", result[0]["base"])
assert.Equal(t, "open", result[0]["state"])
assert.Equal(t, "true", result[0]["auto-restack"])
assert.Equal(t, "2", result[0]["entries"])
}
func TestPullStackDetailShowsEntries(t *testing.T) {
s := &stack.Stack{
ID: 3, Title: "feat: base", BaseBranch: "main", State: "open", AutoRestack: true,
Entries: []stack.Entry{
{PullID: 10, Position: 0, State: "merged"},
{PullID: 11, ParentPullID: 10, Position: 1, State: "open"},
},
}
out := captureStdout(t, func() {
PullStackDetail(s)
})
assert.Contains(t, out, "feat: base")
assert.Contains(t, out, "main")
assert.Contains(t, out, "#10")
assert.Contains(t, out, "#11")
}
+33
View File
@@ -0,0 +1,33 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// Package stack holds the data types shared between the pull request stack API
// client (modules/task) and its output formatting (modules/print).
package stack
// Entry is one pull request participating in a pull request stack.
type Entry struct {
PullID int64 `json:"pull_id"`
ParentPullID int64 `json:"parent_pull_id"`
Position int `json:"position"`
State string `json:"state"`
LastRestackedSHA string `json:"last_restacked_sha"`
}
// Stack is a same-repository chain of pull requests, bottom first.
type Stack struct {
ID int64 `json:"id"`
RepoID int64 `json:"repo_id"`
OwnerID int64 `json:"owner_id"`
Title string `json:"title"`
BaseBranch string `json:"base_branch"`
State string `json:"state"`
AutoRestack bool `json:"auto_restack"`
Entries []Entry `json:"entries"`
}
// MergeResult reports how many pull requests of a stack were merged.
type MergeResult struct {
Merged int64 `json:"merged"`
Error string `json:"error,omitempty"`
}
+1 -5
View File
@@ -153,7 +153,7 @@ func CreateLogin(ctx stdctx.Context, name, token, user, passwd, otp, scopes, ssh
// so we just use the host
login.SSHHost = serverURL.Host
if shouldFindSSHKey(sshKey, sshAgent) {
if len(sshKey) == 0 {
login.SSHKey, err = findSSHKey(ctx, client)
if err != nil {
fmt.Printf("Warning: problem while finding a SSH key: %s\n", err)
@@ -176,10 +176,6 @@ func CreateLogin(ctx stdctx.Context, name, token, user, passwd, otp, scopes, ssh
return nil
}
func shouldFindSSHKey(sshKey string, sshAgent bool) bool {
return sshKey == "" && !sshAgent
}
func shouldCheckTokenUniqueness(token string, sshAgent bool, sshKey, sshCertPrincipal, sshKeyFingerprint string) bool {
if sshAgent || sshKey != "" || sshCertPrincipal != "" || sshKeyFingerprint != "" {
return false
-32
View File
@@ -55,35 +55,3 @@ func TestShouldCheckTokenUniqueness(t *testing.T) {
})
}
}
func TestShouldFindSSHKey(t *testing.T) {
tests := []struct {
name string
sshKey string
sshAgent bool
want bool
}{
{
name: "explicit key",
sshKey: "~/.ssh/id_ed25519",
want: false,
},
{
name: "ssh agent",
sshAgent: true,
want: false,
},
{
name: "no key configured",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := shouldFindSSHKey(tt.sshKey, tt.sshAgent); got != tt.want {
t.Fatalf("expected %v, got %v", tt.want, got)
}
})
}
}
+5 -4
View File
@@ -61,9 +61,10 @@ func remoteURLForPR(login *config.Login, pr *gitea.PullRequest) string {
if isRemoteDeleted(pr) {
repo = pr.Base.Repository
}
if login.SSHKeyPath() != "" || login.SSHAgent {
// Use SSH when a key file is configured, or when the login authenticates
// through a running ssh-agent. In both cases we have a working SSH setup.
if len(login.SSHKey) != 0 {
// login.SSHKey is nonempty, if user specified a key manually or we automatically
// found a matching private key on this machine during login creation.
// this means, we are very likely to have a working ssh setup.
return repo.SSHURL
}
return repo.CloneURL
@@ -83,7 +84,7 @@ func doPRFetch(
if err != nil {
return "", err
}
auth, err := local_git.GetAuthForURL(url, login.GetAccessToken(), login.SSHKeyPath(), callback)
auth, err := local_git.GetAuthForURL(url, login.GetAccessToken(), login.SSHKey, callback)
if err != nil {
return "", err
}
+1 -1
View File
@@ -95,7 +95,7 @@ call me again with the --ignore-sha flag`, remoteBranch)
if urlErr != nil {
return urlErr
}
auth, authErr := local_git.GetAuthForURL(url, login.GetAccessToken(), login.SSHKeyPath(), callback)
auth, authErr := local_git.GetAuthForURL(url, login.GetAccessToken(), login.SSHKey, callback)
if authErr != nil {
return authErr
}
+1 -1
View File
@@ -210,7 +210,7 @@ func CreateAgitFlowPull(requestCtx stdctx.Context, ctx *context.TeaContext, remo
return err
}
auth, err := local_git.GetAuthForURL(url, ctx.Login.GetAccessToken(), ctx.Login.SSHKeyPath(), callback)
auth, err := local_git.GetAuthForURL(url, ctx.Login.GetAccessToken(), ctx.Login.SSHKey, callback)
if err != nil {
return err
}
+187
View File
@@ -0,0 +1,187 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package task
import (
"bytes"
stdctx "context"
"encoding/json"
"fmt"
"io"
"net/http"
"gitea.dev/tea/modules/api"
"gitea.dev/tea/modules/config"
"gitea.dev/tea/modules/stack"
)
func stackAPIError(resp *http.Response) error {
data, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("body read on HTTP error %d: %w", resp.StatusCode, err)
}
var errBody struct {
Message string `json:"message"`
}
if err := json.Unmarshal(data, &errBody); err == nil && errBody.Message != "" {
return fmt.Errorf("%s", errBody.Message)
}
return fmt.Errorf("%s: %s", resp.Status, string(data))
}
func decodeStackResponse(resp *http.Response, wantStatus int, out any) error {
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != wantStatus {
return stackAPIError(resp)
}
if out == nil {
return nil
}
return json.NewDecoder(resp.Body).Decode(out)
}
// pullStackLinkOption links a parent and a child pull request in the same repository.
type pullStackLinkOption struct {
ParentIndex int64 `json:"parent_index"`
ChildIndex int64 `json:"child_index"`
}
func postStackJSON(ctx stdctx.Context, login *config.Login, endpoint string, body any, wantStatus int, out any) error {
client := api.NewClient(login)
var reader io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(encoded)
}
resp, err := client.DoContext(ctx, http.MethodPost, endpoint, reader, nil)
if err != nil {
return err
}
return decodeStackResponse(resp, wantStatus, out)
}
// ListPullStacks lists the pull request stacks of a repository.
func ListPullStacks(ctx stdctx.Context, login *config.Login, owner, repo string) ([]*stack.Stack, error) {
client := api.NewClient(login)
resp, err := client.DoContext(ctx, http.MethodGet, fmt.Sprintf("/repos/%s/%s/stacks", owner, repo), nil, nil)
if err != nil {
return nil, err
}
var stacks []*stack.Stack
if err := decodeStackResponse(resp, http.StatusOK, &stacks); err != nil {
return nil, err
}
return stacks, nil
}
// GetPullStack retrieves one stack with its ordered pull requests.
func GetPullStack(ctx stdctx.Context, login *config.Login, owner, repo string, id int64) (*stack.Stack, error) {
client := api.NewClient(login)
resp, err := client.DoContext(ctx, http.MethodGet, fmt.Sprintf("/repos/%s/%s/stacks/%d", owner, repo, id), nil, nil)
if err != nil {
return nil, err
}
var s stack.Stack
if err := decodeStackResponse(resp, http.StatusOK, &s); err != nil {
return nil, err
}
return &s, nil
}
// CreatePullStack explicitly links two same-repository pull requests, forming a new stack.
func CreatePullStack(ctx stdctx.Context, login *config.Login, owner, repo string, parentIndex, childIndex int64) (*stack.Stack, error) {
var s stack.Stack
err := postStackJSON(ctx, login, fmt.Sprintf("/repos/%s/%s/stacks", owner, repo),
pullStackLinkOption{ParentIndex: parentIndex, ChildIndex: childIndex}, http.StatusCreated, &s)
if err != nil {
return nil, err
}
return &s, nil
}
// AddPullStackEntry appends one pull request to the tip of an existing stack.
func AddPullStackEntry(ctx stdctx.Context, login *config.Login, owner, repo string, id, parentIndex, childIndex int64) (*stack.Stack, error) {
var s stack.Stack
err := postStackJSON(ctx, login, fmt.Sprintf("/repos/%s/%s/stacks/%d/entries", owner, repo, id),
pullStackLinkOption{ParentIndex: parentIndex, ChildIndex: childIndex}, http.StatusCreated, &s)
if err != nil {
return nil, err
}
return &s, nil
}
// ReorderPullStack records the order of PR branches that are already linked.
func ReorderPullStack(ctx stdctx.Context, login *config.Login, owner, repo string, id int64, pullIndices []int64) (*stack.Stack, error) {
var s stack.Stack
err := postStackJSON(ctx, login, fmt.Sprintf("/repos/%s/%s/stacks/%d/reorder", owner, repo, id),
struct {
PullIndices []int64 `json:"pull_indices"`
}{PullIndices: pullIndices}, http.StatusOK, &s)
if err != nil {
return nil, err
}
return &s, nil
}
// RestackPullStack queues a restack starting at the stack's base branch.
func RestackPullStack(ctx stdctx.Context, login *config.Login, owner, repo string, id int64) error {
client := api.NewClient(login)
resp, err := client.DoContext(ctx, http.MethodPost, fmt.Sprintf("/repos/%s/%s/stacks/%d/restack", owner, repo, id), nil, nil)
if err != nil {
return err
}
return decodeStackResponse(resp, http.StatusAccepted, nil)
}
type pullStackMergeOption struct {
Style string `json:"style"`
WaitForCI bool `json:"wait_for_ci"`
}
// MergePullStack merges every pull request of a stack in order. If waitForCI is set, the merge is
// scheduled instead of applied immediately and MergePullStack returns with queued=true. Otherwise
// it returns the number of pull requests merged; a non-nil error means the merge stopped partway,
// with result.Merged reporting how many pull requests succeeded before that.
func MergePullStack(ctx stdctx.Context, login *config.Login, owner, repo string, id int64, style string, waitForCI bool) (result *stack.MergeResult, queued bool, err error) {
client := api.NewClient(login)
encoded, err := json.Marshal(pullStackMergeOption{Style: style, WaitForCI: waitForCI})
if err != nil {
return nil, false, err
}
resp, err := client.DoContext(ctx, http.MethodPost, fmt.Sprintf("/repos/%s/%s/stacks/%d/merge", owner, repo, id),
bytes.NewReader(encoded), nil)
if err != nil {
return nil, false, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusAccepted {
return nil, true, nil
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusConflict {
return nil, false, stackAPIError(resp)
}
var body stack.MergeResult
if decodeErr := json.NewDecoder(resp.Body).Decode(&body); decodeErr != nil {
return nil, false, fmt.Errorf("%s: failed to decode response: %w", resp.Status, decodeErr)
}
if resp.StatusCode != http.StatusOK {
if body.Error == "" {
return &body, false, fmt.Errorf("%s", resp.Status)
}
return &body, false, fmt.Errorf("%s", body.Error)
}
return &body, false, nil
}
+261
View File
@@ -0,0 +1,261 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package task
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"gitea.dev/tea/modules/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestListPullStacks(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"id":1,"repo_id":2,"owner_id":3,"title":"feat: base","base_branch":"main","state":"open","auto_restack":true,"entries":[{"pull_id":10,"parent_pull_id":0,"position":0,"state":"open","last_restacked_sha":"abc"}]}]`))
}))
defer server.Close()
stacks, err := ListPullStacks(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo")
require.NoError(t, err)
require.Len(t, stacks, 1)
assert.Equal(t, int64(1), stacks[0].ID)
assert.Equal(t, "feat: base", stacks[0].Title)
assert.Equal(t, "main", stacks[0].BaseBranch)
assert.True(t, stacks[0].AutoRestack)
require.Len(t, stacks[0].Entries, 1)
assert.Equal(t, int64(10), stacks[0].Entries[0].PullID)
}
func TestGetPullStack(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks/7", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":7,"repo_id":2,"owner_id":3,"title":"feat: base","base_branch":"main","state":"open","auto_restack":false,"entries":[]}`))
}))
defer server.Close()
stack, err := GetPullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 7)
require.NoError(t, err)
assert.Equal(t, int64(7), stack.ID)
assert.Equal(t, "open", stack.State)
}
func TestGetPullStackNotFound(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"stack does not exist"}`))
}))
defer server.Close()
_, err := GetPullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 7)
require.Error(t, err)
assert.Equal(t, "stack does not exist", err.Error())
}
func TestCreatePullStack(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks", r.URL.Path)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.JSONEq(t, `{"parent_index":1,"child_index":2}`, string(body))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":9,"repo_id":2,"owner_id":3,"title":"feat: base","base_branch":"main","state":"open","auto_restack":true,"entries":[]}`))
}))
defer server.Close()
stack, err := CreatePullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 1, 2)
require.NoError(t, err)
assert.Equal(t, int64(9), stack.ID)
}
func TestCreatePullStackConflict(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"message":"parent_index and child_index are required"}`))
}))
defer server.Close()
_, err := CreatePullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 0, 2)
require.Error(t, err)
assert.Equal(t, "parent_index and child_index are required", err.Error())
}
func TestAddPullStackEntry(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks/5/entries", r.URL.Path)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.JSONEq(t, `{"parent_index":2,"child_index":3}`, string(body))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":5,"repo_id":2,"owner_id":3,"title":"feat: base","base_branch":"main","state":"open","auto_restack":true,"entries":[]}`))
}))
defer server.Close()
stack, err := AddPullStackEntry(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 5, 2, 3)
require.NoError(t, err)
assert.Equal(t, int64(5), stack.ID)
}
func TestReorderPullStack(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks/5/reorder", r.URL.Path)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.JSONEq(t, `{"pull_indices":[2,3]}`, string(body))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":5,"repo_id":2,"owner_id":3,"title":"feat: base","base_branch":"main","state":"open","auto_restack":true,"entries":[]}`))
}))
defer server.Close()
result, err := ReorderPullStack(t.Context(), &config.Login{
Name: "test", URL: server.URL, Token: "secret-token",
}, "owner", "repo", 5, []int64{2, 3})
require.NoError(t, err)
assert.Equal(t, int64(5), result.ID)
}
func TestRestackPullStack(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks/4/restack", r.URL.Path)
w.WriteHeader(http.StatusAccepted)
}))
defer server.Close()
err := RestackPullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 4)
require.NoError(t, err)
}
func TestRestackPullStackConflict(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"message":"stack is not open"}`))
}))
defer server.Close()
err := RestackPullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 4)
require.Error(t, err)
assert.Equal(t, "stack is not open", err.Error())
}
func TestMergePullStack(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.Equal(t, "/api/v1/repos/owner/repo/stacks/6/merge", r.URL.Path)
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.JSONEq(t, `{"style":"squash","wait_for_ci":false}`, string(body))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"merged":3}`))
}))
defer server.Close()
result, queued, err := MergePullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 6, "squash", false)
require.NoError(t, err)
assert.False(t, queued)
require.NotNil(t, result)
assert.Equal(t, int64(3), result.Merged)
}
func TestMergePullStackQueued(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.JSONEq(t, `{"style":"merge","wait_for_ci":true}`, string(body))
w.WriteHeader(http.StatusAccepted)
}))
defer server.Close()
result, queued, err := MergePullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 6, "merge", true)
require.NoError(t, err)
assert.True(t, queued)
assert.Nil(t, result)
}
func TestMergePullStackPartialFailure(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"merged":1,"error":"PR #4 is not mergeable"}`))
}))
defer server.Close()
result, queued, err := MergePullStack(t.Context(), &config.Login{
Name: "test",
URL: server.URL,
Token: "secret-token",
}, "owner", "repo", 6, "merge", false)
require.Error(t, err)
assert.Equal(t, "PR #4 is not mergeable", err.Error())
assert.False(t, queued)
require.NotNil(t, result)
assert.Equal(t, int64(1), result.Merged)
}
func TestMergePullStackPermissionDenied(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"merge not permitted"}`))
}))
defer server.Close()
result, queued, err := MergePullStack(t.Context(), &config.Login{
Name: "test", URL: server.URL, Token: "secret-token",
}, "owner", "repo", 6, "merge", false)
require.ErrorContains(t, err, "merge not permitted")
assert.False(t, queued)
assert.Nil(t, result)
}
+2 -2
View File
@@ -33,7 +33,7 @@ func RepoClone(
return nil, err
}
auth, err := local_git.GetAuthForURL(originURL, login.GetAccessToken(), login.SSHKeyPath(), callback)
auth, err := local_git.GetAuthForURL(originURL, login.GetAccessToken(), login.SSHKey, callback)
if err != nil {
return nil, err
}
@@ -68,7 +68,7 @@ func RepoClone(
func cloneURL(repo *gitea.Repository, login *config.Login) (*url.URL, error) {
urlStr := repo.CloneURL
if login.SSHKeyPath() != "" || login.SSHAgent {
if login.SSHKey != "" {
urlStr = repo.SSHURL
}
return local_git.ParseURL(urlStr)