Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b06d902687 | |||
| f28a5e696a | |||
| ba167a7352 | |||
| 9c12138d62 | |||
| 4d09587d4c | |||
| b2bab268d7 | |||
| 58931b5d17 | |||
| c2947c23d9 | |||
| 8bfdec40c6 | |||
| 22d43ec9b6 | |||
| bfda25be63 | |||
| dfe89dfb6b | |||
| ee531914cd | |||
| 276a4b735a | |||
| 943d4c1512 | |||
| 4233ebcbb1 |
@@ -12,11 +12,10 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- run: git fetch --force --tags
|
||||
# Custom publishers (the R2 mirror below) run as the very last
|
||||
# Custom publishers (the R2 upload below) run as the very last
|
||||
# step of goreleaser's publish pipeline, after the Gitea release
|
||||
# has already been created and every artifact already uploaded
|
||||
# to S3. Fail here instead, before anything is built or
|
||||
# published, if the R2 secrets are missing.
|
||||
# has already been created. Fail here instead, before anything
|
||||
# is built or published, if the R2 secrets are missing.
|
||||
- name: check R2 configuration
|
||||
run: sh scripts/upload-r2.sh --check-config
|
||||
env:
|
||||
@@ -46,11 +45,6 @@ jobs:
|
||||
env:
|
||||
SDK_VERSION: ${{ steps.sdk_version.outputs.version }}
|
||||
GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
|
||||
AWS_REGION: ${{ secrets.AWS_REGION }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
S3_REGION: ${{ secrets.AWS_REGION }}
|
||||
S3_BUCKET: ${{ secrets.AWS_BUCKET }}
|
||||
R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}
|
||||
R2_BUCKET: ${{ secrets.R2_BUCKET }}
|
||||
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
|
||||
@@ -77,7 +71,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
@@ -13,11 +13,10 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- run: git fetch --force --tags
|
||||
# Custom publishers (the R2 mirror below) run as the very last
|
||||
# Custom publishers (the R2 upload below) run as the very last
|
||||
# step of goreleaser's publish pipeline, after the Gitea release
|
||||
# has already been created and every artifact already uploaded
|
||||
# to S3. Fail here instead, before anything is built or
|
||||
# published, if the R2 secrets are missing.
|
||||
# has already been created. Fail here instead, before anything
|
||||
# is built or published, if the R2 secrets are missing.
|
||||
- name: check R2 configuration
|
||||
run: sh scripts/upload-r2.sh --check-config
|
||||
env:
|
||||
@@ -47,11 +46,6 @@ jobs:
|
||||
env:
|
||||
SDK_VERSION: ${{ steps.sdk_version.outputs.version }}
|
||||
GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
|
||||
AWS_REGION: ${{ secrets.AWS_REGION }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
S3_REGION: ${{ secrets.AWS_REGION }}
|
||||
S3_BUCKET: ${{ secrets.AWS_BUCKET }}
|
||||
R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}
|
||||
R2_BUCKET: ${{ secrets.R2_BUCKET }}
|
||||
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
|
||||
@@ -78,7 +72,7 @@ jobs:
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
+7
-18
@@ -76,24 +76,13 @@ builds:
|
||||
- cmd: sh .goreleaser.checksum.sh {{ .Path }}
|
||||
- cmd: sh .goreleaser.checksum.sh {{ .Path }}.xz
|
||||
|
||||
blobs:
|
||||
-
|
||||
provider: s3
|
||||
bucket: "{{ .Env.S3_BUCKET }}"
|
||||
region: "{{ .Env.S3_REGION }}"
|
||||
directory: "tea/{{.Version}}"
|
||||
extra_files:
|
||||
- glob: ./**.xz
|
||||
- glob: ./**.sha256
|
||||
|
||||
# Mirrors the S3 `blobs:` upload above into Cloudflare R2 during the
|
||||
# parallel S3+R2 period (S3 will be removed once migration completes).
|
||||
# A second `blobs:` entry is impossible here since the blob pipe
|
||||
# authenticates from the global AWS_* env with no per-entry
|
||||
# credentials; `publishers:` supports per-entry `env:` instead, so
|
||||
# it's used to invoke scripts/upload-r2.sh once per artifact. Custom
|
||||
# publishers inherit almost nothing from the environment, hence the
|
||||
# explicit R2_* forwarding below.
|
||||
# Uploads the release artifacts to Cloudflare R2. A `blobs:` entry is
|
||||
# not used here since the blob pipe authenticates from the global
|
||||
# AWS_* env with no per-entry credentials; `publishers:` supports
|
||||
# per-entry `env:` instead, so it's used to invoke
|
||||
# scripts/upload-r2.sh once per artifact. Custom publishers inherit
|
||||
# almost nothing from the environment, hence the explicit R2_*
|
||||
# forwarding below.
|
||||
#
|
||||
# This publisher fires more than once per distinct key because
|
||||
# goreleaser's release pipe already registers `release.extra_files`
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
// stdinPiped reports whether stdin is not a terminal, e.g. when a description
|
||||
// is piped from a file, command substitution, or a CI harness.
|
||||
func stdinPiped() bool {
|
||||
return !term.IsTerminal(int(os.Stdin.Fd()))
|
||||
}
|
||||
|
||||
// resolveCreateBody returns the issue/PR description for create commands.
|
||||
//
|
||||
// Precedence:
|
||||
// 1. --description-file (read from the file, or stdin when the path is "-")
|
||||
// 2. --description
|
||||
// 3. piped stdin
|
||||
func resolveCreateBody(description, descriptionFile string, descriptionFileSet, stdinPiped bool, stdin io.Reader) (string, error) {
|
||||
if descriptionFileSet {
|
||||
return readDescriptionSource(descriptionFile, stdin)
|
||||
}
|
||||
if description != "" {
|
||||
return description, nil
|
||||
}
|
||||
if stdinPiped {
|
||||
return readDescriptionStdin(stdin)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// resolveEditBody returns the new issue/PR body when a description flag was
|
||||
// provided, or nil when the caller should leave the body unchanged.
|
||||
func resolveEditBody(description string, descriptionSet bool, descriptionFile string, descriptionFileSet bool, stdin io.Reader) (*string, error) {
|
||||
if descriptionFileSet {
|
||||
body, err := readDescriptionSource(descriptionFile, stdin)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &body, nil
|
||||
}
|
||||
if descriptionSet {
|
||||
body := description
|
||||
return &body, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func readDescriptionSource(source string, stdin io.Reader) (string, error) {
|
||||
if source == "-" {
|
||||
return readDescriptionStdin(stdin)
|
||||
}
|
||||
data, err := os.ReadFile(source)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not read description file %q: %w", source, err)
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func readDescriptionStdin(stdin io.Reader) (string, error) {
|
||||
data, err := io.ReadAll(stdin)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not read description from stdin: %w", err)
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package flags
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestResolveCreateBody(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), "body.md")
|
||||
require.NoError(t, os.WriteFile(file, []byte("from file"), 0o600))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
description string
|
||||
descriptionFile string
|
||||
descriptionFileSet bool
|
||||
stdinPiped bool
|
||||
stdin string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "description flag",
|
||||
description: "from -d",
|
||||
want: "from -d",
|
||||
},
|
||||
{
|
||||
name: "description file",
|
||||
descriptionFile: file,
|
||||
descriptionFileSet: true,
|
||||
want: "from file",
|
||||
},
|
||||
{
|
||||
name: "description file wins over description",
|
||||
description: "from -d",
|
||||
descriptionFile: file,
|
||||
descriptionFileSet: true,
|
||||
want: "from file",
|
||||
},
|
||||
{
|
||||
name: "dash reads stdin",
|
||||
descriptionFile: "-",
|
||||
descriptionFileSet: true,
|
||||
stdin: "from stdin",
|
||||
want: "from stdin",
|
||||
},
|
||||
{
|
||||
name: "description wins over piped stdin",
|
||||
description: "from -d",
|
||||
stdinPiped: true,
|
||||
stdin: "from stdin",
|
||||
want: "from -d",
|
||||
},
|
||||
{
|
||||
name: "piped stdin",
|
||||
stdinPiped: true,
|
||||
stdin: "from stdin",
|
||||
want: "from stdin",
|
||||
},
|
||||
{
|
||||
name: "empty description falls back to piped stdin",
|
||||
description: "",
|
||||
stdinPiped: true,
|
||||
stdin: "from stdin",
|
||||
want: "from stdin",
|
||||
},
|
||||
{
|
||||
name: "empty when no source provided",
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := resolveCreateBody(tt.description, tt.descriptionFile, tt.descriptionFileSet, tt.stdinPiped, strings.NewReader(tt.stdin))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveEditBody(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), "body.md")
|
||||
require.NoError(t, os.WriteFile(file, []byte("from file"), 0o600))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
description string
|
||||
descriptionSet bool
|
||||
descriptionFile string
|
||||
descriptionFileSet bool
|
||||
stdin string
|
||||
wantBody string
|
||||
wantSet bool
|
||||
}{
|
||||
{
|
||||
name: "no description flag",
|
||||
},
|
||||
{
|
||||
name: "description flag",
|
||||
description: "from -d",
|
||||
descriptionSet: true,
|
||||
wantBody: "from -d",
|
||||
wantSet: true,
|
||||
},
|
||||
{
|
||||
name: "empty description clears body",
|
||||
descriptionSet: true,
|
||||
wantSet: true,
|
||||
},
|
||||
{
|
||||
name: "description file",
|
||||
descriptionFile: file,
|
||||
descriptionFileSet: true,
|
||||
wantBody: "from file",
|
||||
wantSet: true,
|
||||
},
|
||||
{
|
||||
name: "description file wins over description",
|
||||
description: "from -d",
|
||||
descriptionSet: true,
|
||||
descriptionFile: file,
|
||||
descriptionFileSet: true,
|
||||
wantBody: "from file",
|
||||
wantSet: true,
|
||||
},
|
||||
{
|
||||
name: "dash reads stdin",
|
||||
descriptionFile: "-",
|
||||
descriptionFileSet: true,
|
||||
stdin: "from stdin",
|
||||
wantBody: "from stdin",
|
||||
wantSet: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := resolveEditBody(tt.description, tt.descriptionSet, tt.descriptionFile, tt.descriptionFileSet, strings.NewReader(tt.stdin))
|
||||
require.NoError(t, err)
|
||||
if !tt.wantSet {
|
||||
assert.Nil(t, got)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, tt.wantBody, *got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDescriptionSourceError(t *testing.T) {
|
||||
_, err := resolveCreateBody("", filepath.Join(t.TempDir(), "missing.md"), true, false, strings.NewReader(""))
|
||||
require.ErrorContains(t, err, "could not read description file")
|
||||
}
|
||||
+28
-5
@@ -100,6 +100,10 @@ var issuePRFlags = append([]cli.Flag{
|
||||
Name: "description",
|
||||
Aliases: []string{"d"},
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "description-file",
|
||||
Usage: "Read description from file ('-' for stdin)",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "referenced-version",
|
||||
Aliases: []string{"v"},
|
||||
@@ -133,12 +137,22 @@ var IssuePRCreateFlags = append([]cli.Flag{
|
||||
|
||||
// GetIssuePRCreateFlags parses all IssuePREditFlags
|
||||
func GetIssuePRCreateFlags(requestCtx stdctx.Context, ctx *context.TeaContext) (*gitea.CreateIssueOption, error) {
|
||||
body, err := resolveCreateBody(
|
||||
ctx.String("description"),
|
||||
ctx.String("description-file"),
|
||||
ctx.IsSet("description-file"),
|
||||
stdinPiped(),
|
||||
ctx.Reader,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
opts := gitea.CreateIssueOption{
|
||||
Title: ctx.String("title"),
|
||||
Body: ctx.String("description"),
|
||||
Body: body,
|
||||
Assignees: strings.Split(ctx.String("assignees"), ","),
|
||||
}
|
||||
var err error
|
||||
|
||||
date := ctx.String("deadline")
|
||||
if date != "" {
|
||||
@@ -208,9 +222,18 @@ func GetIssuePREditFlags(ctx *context.TeaContext) (*task.EditIssueOption, error)
|
||||
val := ctx.String("title")
|
||||
opts.Title = &val
|
||||
}
|
||||
if ctx.IsSet("description") {
|
||||
val := ctx.String("description")
|
||||
opts.Body = &val
|
||||
body, err := resolveEditBody(
|
||||
ctx.String("description"),
|
||||
ctx.IsSet("description"),
|
||||
ctx.String("description-file"),
|
||||
ctx.IsSet("description-file"),
|
||||
ctx.Reader,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if body != nil {
|
||||
opts.Body = body
|
||||
}
|
||||
if ctx.IsSet("referenced-version") {
|
||||
val := ctx.String("referenced-version")
|
||||
|
||||
+43
-3
@@ -5,13 +5,18 @@ package issues
|
||||
|
||||
import (
|
||||
stdctx "context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
"github.com/urfave/cli/v3"
|
||||
|
||||
"gitea.dev/tea/cmd/flags"
|
||||
"gitea.dev/tea/modules/context"
|
||||
"gitea.dev/tea/modules/interact"
|
||||
"gitea.dev/tea/modules/print"
|
||||
"gitea.dev/tea/modules/task"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// CmdIssuesCreate represents a sub command of issues to create issue
|
||||
@@ -47,9 +52,44 @@ func runIssuesCreate(requestCtx stdctx.Context, cmd *cli.Command) error {
|
||||
return err
|
||||
}
|
||||
|
||||
return task.CreateIssue(requestCtx, ctx.Login,
|
||||
issue, err := task.CreateIssue(requestCtx, ctx.Login,
|
||||
ctx.Owner,
|
||||
ctx.Repo,
|
||||
*opts,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ctx.IsSet("output") {
|
||||
switch ctx.String("output") {
|
||||
case "json":
|
||||
return writeCreatedIssueAsJSON(ctx.Writer, issue)
|
||||
}
|
||||
}
|
||||
|
||||
print.IssueDetails(issue, nil)
|
||||
|
||||
fmt.Println(issue.HTMLURL)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createdIssueJSON is the machine-readable representation of a freshly
|
||||
// created issue, mirroring the create-PR equivalent in cmd/pulls/create.go
|
||||
// (createdPullJSON).
|
||||
type createdIssueJSON struct {
|
||||
Index int64 `json:"index"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
State gitea.StateType `json:"state"`
|
||||
}
|
||||
|
||||
func writeCreatedIssueAsJSON(w io.Writer, issue *gitea.Issue) error {
|
||||
return json.NewEncoder(w).Encode(createdIssueJSON{
|
||||
Index: issue.Index,
|
||||
Title: issue.Title,
|
||||
URL: issue.HTMLURL,
|
||||
State: issue.State,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package issues
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWriteCreatedIssueAsJSON(t *testing.T) {
|
||||
issue := &gitea.Issue{
|
||||
Index: 42,
|
||||
Title: "test title",
|
||||
HTMLURL: "https://gitea.example.com/owner/repo/issues/42",
|
||||
State: gitea.StateOpen,
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, writeCreatedIssueAsJSON(&buf, issue))
|
||||
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
|
||||
assert.Equal(t, float64(42), got["index"])
|
||||
assert.Equal(t, "test title", got["title"])
|
||||
assert.Equal(t, "https://gitea.example.com/owner/repo/issues/42", got["url"])
|
||||
assert.Equal(t, "open", got["state"])
|
||||
|
||||
// exactly the lean field set, nothing extra
|
||||
assert.Len(t, got, 4)
|
||||
|
||||
// machine-readable output must not contain terminal escape sequences
|
||||
assert.NotContains(t, buf.String(), "\x1b")
|
||||
}
|
||||
@@ -31,6 +31,7 @@ var CmdLogin = cli.Command{
|
||||
&login.CmdLoginSetDefault,
|
||||
&login.CmdLoginHelper,
|
||||
&login.CmdLoginOAuthRefresh,
|
||||
&login.CmdLoginStatus,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package login
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gitea.dev/tea/cmd/flags"
|
||||
"gitea.dev/tea/modules/config"
|
||||
"gitea.dev/tea/modules/print"
|
||||
"gitea.dev/tea/modules/task"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// CmdLoginStatus represents a command to show authentication status for logins.
|
||||
var CmdLoginStatus = cli.Command{
|
||||
Name: "status",
|
||||
Usage: "Show authentication status for Gitea logins",
|
||||
Description: `Verify the stored token for one or all Gitea logins and report its validity.`,
|
||||
ArgsUsage: "[<login name>]",
|
||||
Action: RunLoginStatus,
|
||||
Flags: []cli.Flag{&flags.OutputFlag},
|
||||
}
|
||||
|
||||
// RunLoginStatus verifies one login, or every configured login when no name is
|
||||
// provided, and prints a short authentication report.
|
||||
func RunLoginStatus(requestCtx context.Context, cmd *cli.Command) error {
|
||||
var logins []config.Login
|
||||
|
||||
switch cmd.Args().Len() {
|
||||
case 0:
|
||||
var err error
|
||||
logins, err = config.GetLogins()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case 1:
|
||||
login, err := config.GetLoginByName(cmd.Args().First())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if login == nil {
|
||||
return fmt.Errorf("login '%s' not found", cmd.Args().First())
|
||||
}
|
||||
logins = []config.Login{*login}
|
||||
default:
|
||||
return fmt.Errorf("too many arguments")
|
||||
}
|
||||
|
||||
statuses := make([]print.LoginStatus, 0, len(logins))
|
||||
for i := range logins {
|
||||
statuses = append(statuses, task.CheckLoginStatus(requestCtx, &logins[i]))
|
||||
}
|
||||
|
||||
return print.LoginStatuses(statuses, cmd.String("output"))
|
||||
}
|
||||
@@ -82,6 +82,7 @@ var CmdPulls = cli.Command{
|
||||
&pulls.CmdPullsReviewComments,
|
||||
&pulls.CmdPullsResolve,
|
||||
&pulls.CmdPullsUnresolve,
|
||||
&pulls.CmdPullsStack,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+48
-1
@@ -5,6 +5,9 @@ package pulls
|
||||
|
||||
import (
|
||||
stdctx "context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
"github.com/urfave/cli/v3"
|
||||
@@ -12,6 +15,7 @@ import (
|
||||
"gitea.dev/tea/cmd/flags"
|
||||
"gitea.dev/tea/modules/context"
|
||||
"gitea.dev/tea/modules/interact"
|
||||
"gitea.dev/tea/modules/print"
|
||||
"gitea.dev/tea/modules/task"
|
||||
"gitea.dev/tea/modules/utils"
|
||||
)
|
||||
@@ -80,6 +84,12 @@ func runPullsCreate(requestCtx stdctx.Context, cmd *cli.Command) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// agit flow creates the PR via git push and returns no PR object, so
|
||||
// --output cannot be honored there; fail fast before any API calls
|
||||
if ctx.Bool("agit") && ctx.IsSet("output") {
|
||||
return fmt.Errorf("--output cannot be combined with --agit: the PR is created via git push, so no pull request object is available to print")
|
||||
}
|
||||
|
||||
// else use args to create PR
|
||||
opts, err := flags.GetIssuePRCreateFlags(requestCtx, ctx)
|
||||
if err != nil {
|
||||
@@ -108,7 +118,7 @@ func runPullsCreate(requestCtx stdctx.Context, cmd *cli.Command) error {
|
||||
allowMaintainerEdits = gitea.OptionalBool(ctx.Bool("allow-maintainer-edits"))
|
||||
}
|
||||
|
||||
return task.CreatePull(
|
||||
pr, err := task.CreatePull(
|
||||
requestCtx,
|
||||
ctx,
|
||||
ctx.String("base"),
|
||||
@@ -116,4 +126,41 @@ func runPullsCreate(requestCtx stdctx.Context, cmd *cli.Command) error {
|
||||
allowMaintainerEdits,
|
||||
opts,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ctx.IsSet("output") {
|
||||
switch ctx.String("output") {
|
||||
case "json":
|
||||
return writeCreatedPullAsJSON(ctx.Writer, pr)
|
||||
}
|
||||
}
|
||||
|
||||
print.PullDetails(pr, nil, nil)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createdPullJSON is the machine-readable representation of a freshly
|
||||
// created pull request. A new PR has no reviews, comments or CI yet, so
|
||||
// this is intentionally leaner than the detail view's pullData (cmd/pulls.go).
|
||||
type createdPullJSON struct {
|
||||
Index int64 `json:"index"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
State gitea.StateType `json:"state"`
|
||||
Base string `json:"base"`
|
||||
Head string `json:"head"`
|
||||
}
|
||||
|
||||
func writeCreatedPullAsJSON(w io.Writer, pr *gitea.PullRequest) error {
|
||||
return json.NewEncoder(w).Encode(createdPullJSON{
|
||||
Index: pr.Index,
|
||||
Title: pr.Title,
|
||||
URL: pr.HTMLURL,
|
||||
State: pr.State,
|
||||
Base: pr.Base.Ref,
|
||||
Head: pr.Head.Ref,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package pulls_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/tea/cmd"
|
||||
"gitea.dev/tea/modules/config"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestPullsCreateAgitOutputRejected verifies that --output (parsed via the
|
||||
// urfave/cli v3 ancestor-flag cascade, since create itself does not declare
|
||||
// it) is rejected for the agit flow before any API call or git push happens.
|
||||
func TestPullsCreateAgitOutputRejected(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{})
|
||||
})
|
||||
|
||||
app := cmd.App()
|
||||
args := []string{
|
||||
"tea", "pulls", "create",
|
||||
"--agit",
|
||||
"--output", "json",
|
||||
"--head", "topic-branch",
|
||||
"--title", "test",
|
||||
"--login", "testLogin",
|
||||
"--repo", "user/repo",
|
||||
}
|
||||
|
||||
err := app.Run(context.Background(), args)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "--output cannot be combined with --agit")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package pulls
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWriteCreatedPullAsJSON(t *testing.T) {
|
||||
pr := &gitea.PullRequest{
|
||||
Index: 33,
|
||||
Title: "test title",
|
||||
HTMLURL: "https://gitea.example.com/owner/repo/pulls/33",
|
||||
State: gitea.StateOpen,
|
||||
Base: &gitea.PRBranchInfo{Ref: "main"},
|
||||
Head: &gitea.PRBranchInfo{Ref: "feature"},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, writeCreatedPullAsJSON(&buf, pr))
|
||||
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
|
||||
assert.Equal(t, float64(33), got["index"])
|
||||
assert.Equal(t, "test title", got["title"])
|
||||
assert.Equal(t, "https://gitea.example.com/owner/repo/pulls/33", got["url"])
|
||||
assert.Equal(t, "open", got["state"])
|
||||
assert.Equal(t, "main", got["base"])
|
||||
assert.Equal(t, "feature", got["head"])
|
||||
|
||||
// exactly the lean field set, nothing extra
|
||||
assert.Len(t, got, 6)
|
||||
|
||||
// machine-readable output must not contain terminal escape sequences
|
||||
assert.NotContains(t, buf.String(), "\x1b")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
+14
@@ -109,6 +109,12 @@ Return the stored token for a URL (git credential protocol)
|
||||
|
||||
Refresh an OAuth token
|
||||
|
||||
### status
|
||||
|
||||
Show authentication status for Gitea logins
|
||||
|
||||
**--output, -o**="": Output format. (simple, table, csv, tsv, yaml, json)
|
||||
|
||||
## logout
|
||||
|
||||
Log out from a Gitea server
|
||||
@@ -221,6 +227,8 @@ Create an issue on repository
|
||||
|
||||
**--description, -d**="":
|
||||
|
||||
**--description-file**="": Read description from file ('-' for stdin)
|
||||
|
||||
**--labels, -L**="": Comma-separated list of labels to assign
|
||||
|
||||
**--login, -l**="": Use a different Gitea Login. Optional
|
||||
@@ -247,6 +255,8 @@ Edit one or more issues
|
||||
|
||||
**--description, -d**="":
|
||||
|
||||
**--description-file**="": Read description from file ('-' for stdin)
|
||||
|
||||
**--login, -l**="": Use a different Gitea Login. Optional
|
||||
|
||||
**--milestone, -m**="": Milestone to assign
|
||||
@@ -379,6 +389,8 @@ Create a pull-request
|
||||
|
||||
**--description, -d**="":
|
||||
|
||||
**--description-file**="": Read description from file ('-' for stdin)
|
||||
|
||||
**--draft**: Create as a draft (prepends "WIP: " to the title; Gitea treats WIP-prefixed PRs as drafts)
|
||||
|
||||
**--head**="": Branch name of the PR source (default is current one). To specify a different head repo, use <user>:<branch>
|
||||
@@ -437,6 +449,8 @@ Edit one or more pull requests
|
||||
|
||||
**--description, -d**="":
|
||||
|
||||
**--description-file**="": Read description from file ('-' for stdin)
|
||||
|
||||
**--draft**: Mark as draft by prepending "WIP: " to the title (idempotent)
|
||||
|
||||
**--login, -l**="": Use a different Gitea Login. Optional
|
||||
|
||||
@@ -2,7 +2,7 @@ module gitea.dev/tea
|
||||
|
||||
go 1.26.0
|
||||
|
||||
toolchain go1.26.5
|
||||
toolchain go1.26.6
|
||||
|
||||
require (
|
||||
charm.land/glamour/v2 v2.0.1
|
||||
@@ -21,7 +21,7 @@ require (
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/urfave/cli-docs/v3 v3.1.0
|
||||
github.com/urfave/cli/v3 v3.10.1
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/crypto v0.56.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/term v0.45.0
|
||||
@@ -78,10 +78,10 @@ require (
|
||||
github.com/yuin/goldmark-emoji v1.0.6 // indirect
|
||||
github.com/zalando/go-keyring v0.2.8 // indirect
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
golang.org/x/tools v0.48.0 // indirect
|
||||
)
|
||||
|
||||
retract v1.3.3 // accidental release, tag deleted
|
||||
|
||||
@@ -162,19 +162,19 @@ github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cma
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
|
||||
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM=
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -191,13 +191,13 @@ golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -366,7 +366,9 @@ func startLocalServerAndOpenBrowser(authURL, expectedState string, opts *OAuthOp
|
||||
var openBrowser = func(url string) error {
|
||||
fmt.Printf("Please authorize the application by visiting this URL in your browser:\n%s\n", url)
|
||||
|
||||
return open.Run(url)
|
||||
// Don't wait for the opener to exit, so a browser that holds the
|
||||
// foreground can't block the wait for the callback.
|
||||
return open.Start(url)
|
||||
}
|
||||
|
||||
// createLoginFromToken creates a login entry using the obtained access token
|
||||
|
||||
@@ -6,11 +6,16 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -89,3 +94,36 @@ func TestPerformBrowserOAuthFlow_RedirectURIMatchesAcrossAuthorizeAndExchange(t
|
||||
assert.Equal(t, authorizeRedirectURI, exchangeRedirectURI,
|
||||
"redirect_uri must match between authorize and token exchange (RFC 6749 §4.1.3)")
|
||||
}
|
||||
|
||||
// Regression test for the browser opener hang: xdg-open does not exit until
|
||||
// the browser it launched does, and the callback is only consumed after
|
||||
// openBrowser returns. Waiting on the opener hangs the CLI even though the
|
||||
// user authenticated successfully.
|
||||
func TestOpenBrowser_DoesNotWaitForOpener(t *testing.T) {
|
||||
if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
|
||||
t.Skip("xdg-open is not the opener on this platform")
|
||||
}
|
||||
|
||||
const (
|
||||
fakeOpenerSleepTime = 10 * time.Second
|
||||
openBrowserTimeout = 2 * time.Second
|
||||
)
|
||||
|
||||
// A stand-in xdg-open that holds the foreground the way a browser it had
|
||||
// to launch would.
|
||||
dir := t.TempDir()
|
||||
opener := filepath.Join(dir, "xdg-open")
|
||||
script := fmt.Sprintf("#!/bin/sh\nexec sleep %d\n", int(fakeOpenerSleepTime.Seconds()))
|
||||
require.NoError(t, os.WriteFile(opener, []byte(script), 0o755))
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- openBrowser("http://127.0.0.1:1/") }()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
require.NoError(t, err)
|
||||
case <-time.After(openBrowserTimeout):
|
||||
t.Fatal("openBrowser blocked on the opener; the callback would never be consumed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,6 +446,14 @@ func (l *Login) Client(options ...gitea.ClientOption) *gitea.Client {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return l.ClientWithoutRefresh(options...)
|
||||
}
|
||||
|
||||
// ClientWithoutRefresh returns a client to operate the Gitea API without
|
||||
// attempting an automatic OAuth token refresh. Commands that need to handle
|
||||
// token refresh errors themselves (such as 'tea login status') should use this
|
||||
// instead of Client, which prints to stderr and exits on refresh failure.
|
||||
func (l *Login) ClientWithoutRefresh(options ...gitea.ClientOption) *gitea.Client {
|
||||
// Configure transport-level timeouts so a stalled or unresponsive server
|
||||
// fails fast instead of hanging forever. These bound connection setup and
|
||||
// time-to-first-response-byte only, so slow-but-progressing transfers (e.g.
|
||||
|
||||
@@ -5,11 +5,13 @@ package interact
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
|
||||
"gitea.dev/tea/modules/config"
|
||||
"gitea.dev/tea/modules/print"
|
||||
"gitea.dev/tea/modules/task"
|
||||
"gitea.dev/tea/modules/theme"
|
||||
|
||||
@@ -34,7 +36,16 @@ func CreateIssue(ctx context.Context, login *config.Login, owner, repo string) e
|
||||
return err
|
||||
}
|
||||
|
||||
return task.CreateIssue(ctx, login, owner, repo, opts)
|
||||
issue, err := task.CreateIssue(ctx, login, owner, repo, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
print.IssueDetails(issue, nil)
|
||||
|
||||
fmt.Println(issue.HTMLURL)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func promptIssueProperties(ctx context.Context, login *config.Login, owner, repo string, o *gitea.CreateIssueOption) error {
|
||||
|
||||
+37
-19
@@ -200,25 +200,9 @@ func CreateLogin(ctx context.Context) error {
|
||||
}
|
||||
printTitleAndContent("Selected ssh-key:", sshKey)
|
||||
|
||||
// ssh certificate
|
||||
if strings.Contains(sshKey, "principals") {
|
||||
sshCertPrincipal = regexp.MustCompile(`.*?principals: (.*?)[,|\s]`).FindStringSubmatch(sshKey)[1]
|
||||
if strings.Contains(sshKey, "(ssh-agent)") {
|
||||
sshAgent = true
|
||||
sshKey = ""
|
||||
} else {
|
||||
sshKey = regexp.MustCompile(`\((.*?)\)$`).FindStringSubmatch(sshKey)[1]
|
||||
sshKey = strings.TrimSuffix(sshKey, "-cert.pub")
|
||||
}
|
||||
} else {
|
||||
sshKeyFingerprint = regexp.MustCompile(`(SHA256:.*?)\s`).FindStringSubmatch(sshKey)[1]
|
||||
if strings.Contains(sshKey, "(ssh-agent)") {
|
||||
sshAgent = true
|
||||
sshKey = ""
|
||||
} else {
|
||||
sshKey = regexp.MustCompile(`\((.*?)\)$`).FindStringSubmatch(sshKey)[1]
|
||||
sshKey = strings.TrimSuffix(sshKey, ".pub")
|
||||
}
|
||||
sshKey, sshCertPrincipal, sshKeyFingerprint, sshAgent, err = parseSSHPubkeySelection(sshKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -274,6 +258,40 @@ func CreateLogin(ctx context.Context) error {
|
||||
return task.CreateLogin(ctx, name, token, user, passwd, otp, scopes, sshKey, giteaURL, sshCertPrincipal, sshKeyFingerprint, insecure, sshAgent, versionCheck, helper)
|
||||
}
|
||||
|
||||
func parseSSHPubkeySelection(display string) (sshKey, sshCertPrincipal, sshKeyFingerprint string, sshAgent bool, err error) {
|
||||
if strings.Contains(display, "principals") {
|
||||
if sshCertPrincipal, err = regexpSubmatch(regexp.MustCompile(`.*?principals: (.*?)[,|\s]`), display); err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to parse SSH certificate principal from %q: %w", display, err)
|
||||
}
|
||||
if strings.HasSuffix(display, "(ssh-agent)") {
|
||||
return "", sshCertPrincipal, "", true, nil
|
||||
}
|
||||
if sshKey, err = regexpSubmatch(regexp.MustCompile(`\((.*?)\)$`), display); err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to parse SSH certificate path from %q: %w", display, err)
|
||||
}
|
||||
return strings.TrimSuffix(sshKey, "-cert.pub"), sshCertPrincipal, "", false, nil
|
||||
}
|
||||
|
||||
if sshKeyFingerprint, err = regexpSubmatch(regexp.MustCompile(`(SHA256:.*?)\s`), display); err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to parse SSH key fingerprint from %q: %w", display, err)
|
||||
}
|
||||
if strings.HasSuffix(display, "(ssh-agent)") {
|
||||
return "", "", sshKeyFingerprint, true, nil
|
||||
}
|
||||
if sshKey, err = regexpSubmatch(regexp.MustCompile(`\((.*?)\)$`), display); err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to parse SSH key path from %q: %w", display, err)
|
||||
}
|
||||
return strings.TrimSuffix(sshKey, ".pub"), "", sshKeyFingerprint, false, nil
|
||||
}
|
||||
|
||||
func regexpSubmatch(re *regexp.Regexp, s string) (string, error) {
|
||||
match := re.FindStringSubmatch(s)
|
||||
if len(match) < 2 {
|
||||
return "", fmt.Errorf("no match")
|
||||
}
|
||||
return match[1], nil
|
||||
}
|
||||
|
||||
var tokenScopeOpts = []string{
|
||||
string(gitea.AccessTokenScopeAll),
|
||||
string(gitea.AccessTokenScopeRepo),
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package interact
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseSSHPubkeySelection(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
display string
|
||||
wantSSHKey string
|
||||
wantCertPrincipal string
|
||||
wantKeyFingerprint string
|
||||
wantSSHAgent bool
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "local ed25519 key",
|
||||
display: "SHA256:abc ssh-ed25519 comment (/home/user/.ssh/id_ed25519.pub)",
|
||||
wantSSHKey: "/home/user/.ssh/id_ed25519",
|
||||
wantKeyFingerprint: "SHA256:abc",
|
||||
},
|
||||
{
|
||||
name: "agent ed25519 key",
|
||||
display: "SHA256:abc ssh-ed25519 comment (ssh-agent)",
|
||||
wantKeyFingerprint: "SHA256:abc",
|
||||
wantSSHAgent: true,
|
||||
},
|
||||
{
|
||||
name: "local certificate",
|
||||
display: "SHA256:abc ssh-ed25519-cert-v01@openssh.com comment - principals: user1,user2 (/home/user/.ssh/id_ed25519-cert.pub)",
|
||||
wantSSHKey: "/home/user/.ssh/id_ed25519",
|
||||
wantCertPrincipal: "user1",
|
||||
},
|
||||
{
|
||||
name: "agent certificate",
|
||||
display: "SHA256:abc ssh-ed25519-cert-v01@openssh.com comment - principals: user1 (ssh-agent)",
|
||||
wantCertPrincipal: "user1",
|
||||
wantSSHAgent: true,
|
||||
},
|
||||
{
|
||||
name: "unexpected display",
|
||||
display: "ssh-ed25519 comment",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
sshKey, certPrincipal, keyFingerprint, sshAgent, err := parseSSHPubkeySelection(tt.display)
|
||||
if tt.wantErr {
|
||||
require.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tt.wantSSHKey, sshKey)
|
||||
assert.Equal(t, tt.wantCertPrincipal, certPrincipal)
|
||||
assert.Equal(t, tt.wantKeyFingerprint, keyFingerprint)
|
||||
assert.Equal(t, tt.wantSSHAgent, sshAgent)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
"gitea.dev/tea/modules/context"
|
||||
"gitea.dev/tea/modules/print"
|
||||
"gitea.dev/tea/modules/task"
|
||||
"gitea.dev/tea/modules/theme"
|
||||
|
||||
@@ -134,11 +135,18 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext) (err error)
|
||||
return err
|
||||
}
|
||||
|
||||
return task.CreatePull(
|
||||
pr, err := task.CreatePull(
|
||||
requestCtx,
|
||||
ctx,
|
||||
base,
|
||||
head,
|
||||
&allowMaintainerEdits,
|
||||
&opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
print.PullDetails(pr, nil, nil)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package print
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LoginStatus contains the authentication status of a single configured login.
|
||||
type LoginStatus struct {
|
||||
Name string
|
||||
URL string
|
||||
User string
|
||||
Valid bool
|
||||
AuthMethod string
|
||||
TokenExpiry time.Time
|
||||
Helper bool
|
||||
Default bool
|
||||
Error string
|
||||
}
|
||||
|
||||
// LoginStatusFields are the available fields to print with LoginStatuses.
|
||||
var LoginStatusFields = []string{
|
||||
"name",
|
||||
"url",
|
||||
"user",
|
||||
"valid",
|
||||
"auth_method",
|
||||
"token_expiry",
|
||||
"helper",
|
||||
"default",
|
||||
}
|
||||
|
||||
// LoginStatuses prints authentication status for one or more logins.
|
||||
func LoginStatuses(statuses []LoginStatus, output string) error {
|
||||
if output != "" {
|
||||
printables := make([]printable, len(statuses))
|
||||
for i := range statuses {
|
||||
printables[i] = statuses[i]
|
||||
}
|
||||
t := tableFromItems(LoginStatusFields, printables, isMachineReadable(output))
|
||||
return t.print(output)
|
||||
}
|
||||
|
||||
if len(statuses) == 0 {
|
||||
fmt.Println("No logins configured.")
|
||||
return nil
|
||||
}
|
||||
|
||||
for i, status := range statuses {
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
printLoginStatusReport(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func printLoginStatusReport(status LoginStatus) {
|
||||
name := status.Name
|
||||
if status.Default {
|
||||
name += " (default)"
|
||||
}
|
||||
fmt.Println(name)
|
||||
|
||||
if status.Valid {
|
||||
line := " ✔ Logged in to " + status.URL
|
||||
if status.User != "" {
|
||||
line += " as " + status.User
|
||||
}
|
||||
fmt.Println(line)
|
||||
|
||||
tokenLine := " ✔ Token is valid"
|
||||
if status.AuthMethod != "" {
|
||||
tokenLine += " (" + status.AuthMethod
|
||||
if !status.TokenExpiry.IsZero() {
|
||||
tokenLine += ", " + formatTokenExpiry(status.TokenExpiry)
|
||||
}
|
||||
tokenLine += ")"
|
||||
}
|
||||
fmt.Println(tokenLine)
|
||||
} else {
|
||||
message := status.Error
|
||||
if message == "" {
|
||||
message = "Login failed"
|
||||
}
|
||||
fmt.Println(" ✗ " + message)
|
||||
}
|
||||
|
||||
if status.Helper {
|
||||
fmt.Println(" ✔ Git credential helper configured")
|
||||
} else {
|
||||
fmt.Println(" ✗ Git credential helper not configured")
|
||||
}
|
||||
}
|
||||
|
||||
func formatExpiryDuration(t time.Time) string {
|
||||
d := time.Until(t)
|
||||
if d < 0 {
|
||||
return "expired"
|
||||
}
|
||||
if d < time.Minute {
|
||||
return "in less than a minute"
|
||||
}
|
||||
return "in " + strings.TrimSuffix(d.Truncate(time.Minute).String(), "0s")
|
||||
}
|
||||
|
||||
func formatTokenExpiry(t time.Time) string {
|
||||
if t.Before(time.Now()) {
|
||||
return "expired"
|
||||
}
|
||||
return "expires " + formatExpiryDuration(t)
|
||||
}
|
||||
|
||||
// FormatField implements the printable interface for LoginStatus.
|
||||
func (s LoginStatus) FormatField(field string, machineReadable bool) string {
|
||||
switch field {
|
||||
case "name":
|
||||
return s.Name
|
||||
case "url":
|
||||
return s.URL
|
||||
case "user":
|
||||
return s.User
|
||||
case "valid":
|
||||
return formatBoolean(s.Valid, !machineReadable)
|
||||
case "auth_method":
|
||||
return s.AuthMethod
|
||||
case "token_expiry":
|
||||
if s.TokenExpiry.IsZero() {
|
||||
return ""
|
||||
}
|
||||
if machineReadable {
|
||||
return FormatTime(s.TokenExpiry, true)
|
||||
}
|
||||
return formatExpiryDuration(s.TokenExpiry)
|
||||
case "helper":
|
||||
return formatBoolean(s.Helper, !machineReadable)
|
||||
case "default":
|
||||
return formatBoolean(s.Default, !machineReadable)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package print
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLoginStatusFormatField(t *testing.T) {
|
||||
status := LoginStatus{
|
||||
Name: "gitea",
|
||||
URL: "https://gitea.com",
|
||||
User: "alice",
|
||||
Valid: true,
|
||||
AuthMethod: "oauth",
|
||||
TokenExpiry: time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC),
|
||||
Helper: true,
|
||||
Default: true,
|
||||
}
|
||||
|
||||
assert.Equal(t, "gitea", status.FormatField("name", false))
|
||||
assert.Equal(t, "https://gitea.com", status.FormatField("url", false))
|
||||
assert.Equal(t, "alice", status.FormatField("user", false))
|
||||
assert.Equal(t, "true", status.FormatField("valid", true))
|
||||
assert.Equal(t, "✔", status.FormatField("valid", false))
|
||||
assert.Equal(t, "oauth", status.FormatField("auth_method", true))
|
||||
assert.Equal(t, "2026-08-27T12:00:00Z", status.FormatField("token_expiry", true))
|
||||
assert.Equal(t, "true", status.FormatField("helper", true))
|
||||
assert.Equal(t, "✔", status.FormatField("default", false))
|
||||
}
|
||||
|
||||
func TestFormatExpiryDurationExpired(t *testing.T) {
|
||||
assert.Equal(t, "expired", formatExpiryDuration(time.Now().Add(-time.Hour)))
|
||||
}
|
||||
@@ -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", "")
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -10,24 +10,19 @@ import (
|
||||
gitea "gitea.dev/sdk"
|
||||
|
||||
"gitea.dev/tea/modules/config"
|
||||
"gitea.dev/tea/modules/print"
|
||||
)
|
||||
|
||||
// CreateIssue creates an issue in the given repo and prints the result
|
||||
func CreateIssue(requestCtx stdctx.Context, rlogin *config.Login, repoOwner, repoName string, opts gitea.CreateIssueOption) error {
|
||||
// CreateIssue creates an issue in the given repo and returns the created issue
|
||||
func CreateIssue(requestCtx stdctx.Context, rlogin *config.Login, repoOwner, repoName string, opts gitea.CreateIssueOption) (*gitea.Issue, error) {
|
||||
// title is required
|
||||
if len(opts.Title) == 0 {
|
||||
return fmt.Errorf("title is required")
|
||||
return nil, fmt.Errorf("title is required")
|
||||
}
|
||||
|
||||
issue, _, err := rlogin.Client().Issues.CreateIssue(requestCtx, repoOwner, repoName, opts)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create issue: %s", err)
|
||||
return nil, fmt.Errorf("could not create issue: %s", err)
|
||||
}
|
||||
|
||||
print.IssueDetails(issue, nil)
|
||||
|
||||
fmt.Println(issue.HTMLURL)
|
||||
|
||||
return nil
|
||||
return issue, nil
|
||||
}
|
||||
|
||||
@@ -48,6 +48,29 @@ func SetupHelper(login config.Login) (ok bool, err error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// HasGitCredentialHelper reports whether tea is registered as a git credential
|
||||
// helper for the given login. It mirrors the global git config lookup used by
|
||||
// SetupHelper.
|
||||
func HasGitCredentialHelper(login config.Login) bool {
|
||||
if login.URL == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
helperKey := fmt.Sprintf("credential.%s.helper", login.URL)
|
||||
currentHelpers, err := exec.Command("git", "config", "--global", "--get-all", helperKey).Output()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, line := range strings.Split(strings.ReplaceAll(string(currentHelpers), "\r", ""), "\n") {
|
||||
if strings.HasSuffix(strings.TrimSpace(line), "login helper") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// CreateLogin create a login to be stored in config
|
||||
func CreateLogin(ctx stdctx.Context, name, token, user, passwd, otp, scopes, sshKey, giteaURL, sshCertPrincipal, sshKeyFingerprint string, insecure, sshAgent, versionCheck, addHelper bool) error {
|
||||
// checks ...
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dev/tea/modules/config"
|
||||
"gitea.dev/tea/modules/print"
|
||||
)
|
||||
|
||||
// CheckLoginStatus verifies the stored token for a login against the server and
|
||||
// returns a printable status. Unlike config.Login.Client, refresh failures are
|
||||
// captured in the returned status instead of terminating the process.
|
||||
func CheckLoginStatus(ctx context.Context, login *config.Login) print.LoginStatus {
|
||||
status := print.LoginStatus{
|
||||
Name: login.Name,
|
||||
URL: login.URL,
|
||||
AuthMethod: loginAuthMethod(login),
|
||||
TokenExpiry: loginTokenExpiry(login),
|
||||
Helper: HasGitCredentialHelper(*login),
|
||||
Default: login.Default,
|
||||
}
|
||||
|
||||
if login.GetAccessToken() == "" {
|
||||
status.Error = "Login failed: no access token configured"
|
||||
return status
|
||||
}
|
||||
|
||||
if err := login.RefreshOAuthTokenIfNeeded(); err != nil {
|
||||
status.Error = "Token refresh failed: " + strings.TrimPrefix(err.Error(), "failed to refresh token: ")
|
||||
return status
|
||||
}
|
||||
|
||||
// A successful refresh updates the token in the secure store, so re-read the
|
||||
// expiry for the status line.
|
||||
status.TokenExpiry = loginTokenExpiry(login)
|
||||
|
||||
user, _, err := login.ClientWithoutRefresh().Users.GetMyUserInfo(ctx)
|
||||
if err != nil {
|
||||
status.Error = fmt.Sprintf("Login failed: %s", err)
|
||||
return status
|
||||
}
|
||||
|
||||
status.Valid = true
|
||||
status.User = user.UserName
|
||||
return status
|
||||
}
|
||||
|
||||
func loginAuthMethod(login *config.Login) string {
|
||||
if login.IsOAuth() {
|
||||
return config.AuthMethodOAuth
|
||||
}
|
||||
return "token"
|
||||
}
|
||||
|
||||
func loginTokenExpiry(login *config.Login) time.Time {
|
||||
expiry := login.GetTokenExpiry()
|
||||
if expiry.Equal(time.Unix(0, 0)) {
|
||||
return time.Time{}
|
||||
}
|
||||
return expiry
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/tea/modules/config"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCheckLoginStatus(t *testing.T) {
|
||||
// Keep helper detection isolated from the developer's real git config.
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), ".gitconfig"))
|
||||
|
||||
t.Run("valid token", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "/api/v1/user", r.URL.Path)
|
||||
assert.Equal(t, "token secret-token", r.Header.Get("Authorization"))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":1,"login":"alice"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
status := CheckLoginStatus(context.Background(), &config.Login{
|
||||
Name: "test",
|
||||
URL: server.URL,
|
||||
Token: "secret-token",
|
||||
VersionCheck: false,
|
||||
})
|
||||
|
||||
assert.True(t, status.Valid)
|
||||
assert.Empty(t, status.Error)
|
||||
assert.Equal(t, "test", status.Name)
|
||||
assert.Equal(t, server.URL, status.URL)
|
||||
assert.Equal(t, "alice", status.User)
|
||||
assert.Equal(t, "token", status.AuthMethod)
|
||||
assert.False(t, status.Helper)
|
||||
})
|
||||
|
||||
t.Run("invalid token", func(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.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"message":"token is invalid"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
status := CheckLoginStatus(context.Background(), &config.Login{
|
||||
Name: "test",
|
||||
URL: server.URL,
|
||||
Token: "expired-token",
|
||||
VersionCheck: false,
|
||||
})
|
||||
|
||||
assert.False(t, status.Valid)
|
||||
assert.Contains(t, status.Error, "token is invalid")
|
||||
})
|
||||
|
||||
t.Run("missing token", func(t *testing.T) {
|
||||
status := CheckLoginStatus(context.Background(), &config.Login{
|
||||
Name: "test",
|
||||
URL: "https://gitea.example.com",
|
||||
})
|
||||
|
||||
assert.False(t, status.Valid)
|
||||
assert.Contains(t, status.Error, "no access token configured")
|
||||
})
|
||||
}
|
||||
+12
-13
@@ -14,7 +14,6 @@ import (
|
||||
"gitea.dev/tea/modules/config"
|
||||
"gitea.dev/tea/modules/context"
|
||||
local_git "gitea.dev/tea/modules/git"
|
||||
"gitea.dev/tea/modules/print"
|
||||
"gitea.dev/tea/modules/utils"
|
||||
)
|
||||
|
||||
@@ -24,24 +23,26 @@ var (
|
||||
consecutive = regexp.MustCompile(`[\s]{2,}`)
|
||||
)
|
||||
|
||||
// CreatePull creates a PR in the given repo and prints the result
|
||||
func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext, base, head string, allowMaintainerEdits *bool, opts *gitea.CreateIssueOption) (err error) {
|
||||
// CreatePull creates a PR in the given repo and returns the created PR
|
||||
func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext, base, head string, allowMaintainerEdits *bool, opts *gitea.CreateIssueOption) (*gitea.PullRequest, error) {
|
||||
var err error
|
||||
|
||||
// default is default branch
|
||||
if len(base) == 0 {
|
||||
base, err = GetDefaultPRBase(requestCtx, ctx.Login, ctx.Owner, ctx.Repo)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// default is current one
|
||||
if len(head) == 0 {
|
||||
if ctx.LocalRepo == nil {
|
||||
return fmt.Errorf("no local git repo detected, please specify head branch")
|
||||
return nil, fmt.Errorf("no local git repo detected, please specify head branch")
|
||||
}
|
||||
headOwner, headBranch, err := GetDefaultPRHead(ctx.LocalRepo)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
head = GetHeadSpec(headOwner, headBranch, ctx.Owner)
|
||||
@@ -49,7 +50,7 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext, base, head s
|
||||
|
||||
// head & base may not be the same
|
||||
if head == base {
|
||||
return fmt.Errorf("can't create PR from %s to %s", head, base)
|
||||
return nil, fmt.Errorf("can't create PR from %s to %s", head, base)
|
||||
}
|
||||
|
||||
// default is head branch name
|
||||
@@ -58,7 +59,7 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext, base, head s
|
||||
}
|
||||
// title is required
|
||||
if len(opts.Title) == 0 {
|
||||
return fmt.Errorf("title is required")
|
||||
return nil, fmt.Errorf("title is required")
|
||||
}
|
||||
|
||||
client := ctx.Login.Client()
|
||||
@@ -74,7 +75,7 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext, base, head s
|
||||
Deadline: opts.Deadline,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create PR from %s to %s:%s: %s", head, ctx.Owner, base, err)
|
||||
return nil, fmt.Errorf("could not create PR from %s to %s:%s: %s", head, ctx.Owner, base, err)
|
||||
}
|
||||
|
||||
if allowMaintainerEdits != nil && pr.AllowMaintainerEdit != *allowMaintainerEdits {
|
||||
@@ -82,13 +83,11 @@ func CreatePull(requestCtx stdctx.Context, ctx *context.TeaContext, base, head s
|
||||
AllowMaintainerEdit: allowMaintainerEdits,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not enable maintainer edit on pull: %v", err)
|
||||
return nil, fmt.Errorf("could not enable maintainer edit on pull: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
print.PullDetails(pr, nil, nil)
|
||||
|
||||
return err
|
||||
return pr, nil
|
||||
}
|
||||
|
||||
// GetDefaultPRBase retrieves the default base branch for the given repo
|
||||
|
||||
@@ -19,8 +19,36 @@ func PullMerge(requestCtx stdctx.Context, login *config.Login, repoOwner, repoNa
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !success {
|
||||
return fmt.Errorf("failed to merge PR, is it still open?")
|
||||
if success {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to merge PR #%d: %s", index,
|
||||
mergeFailureReason(requestCtx, client, repoOwner, repoName, index))
|
||||
}
|
||||
|
||||
// mergeFailureReason returns why merging was refused. The SDK reports refusal as
|
||||
// success=false and discards Gitea's explanatory body, so the reason has to be
|
||||
// re-derived from the PR. Costs one API call, on the failure path only.
|
||||
func mergeFailureReason(requestCtx stdctx.Context, client *gitea.Client, repoOwner, repoName string, index int64) string {
|
||||
// Fallback naming the conditions tea cannot observe, used when the PR looks
|
||||
// mergeable but the merge was refused anyway.
|
||||
const refused = "the server refused the merge; check required status checks, requested reviews, or branch protection rules"
|
||||
|
||||
pr, _, err := client.PullRequests.GetPullRequest(requestCtx, repoOwner, repoName, index)
|
||||
if err != nil || pr == nil {
|
||||
return refused
|
||||
}
|
||||
|
||||
switch {
|
||||
case pr.HasMerged:
|
||||
return "it has already been merged"
|
||||
case pr.State == gitea.StateClosed:
|
||||
return "it is closed"
|
||||
case pr.Draft:
|
||||
return "it is a draft; mark it ready for review first"
|
||||
case !pr.Mergeable:
|
||||
return "it has conflicting files or is otherwise not mergeable"
|
||||
default:
|
||||
return refused
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
gitea "gitea.dev/sdk"
|
||||
|
||||
"gitea.dev/tea/modules/config"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// mergeTestServer answers the merge POST with mergeStatus and the PR GET with
|
||||
// prJSON, or a 404 if prJSON is empty.
|
||||
func mergeTestServer(t *testing.T, prJSON string, mergeStatus int) *httptest.Server {
|
||||
t.Helper()
|
||||
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/merge"):
|
||||
w.WriteHeader(mergeStatus)
|
||||
// Gitea explains itself here; the SDK discards it.
|
||||
_, _ = w.Write([]byte(`{"message":"Please try again later"}`))
|
||||
case r.Method == http.MethodGet:
|
||||
if prJSON == "" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"message":"pull request does not exist"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(prJSON))
|
||||
default:
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func pullJSON(state string, merged, draft, mergeable bool) string {
|
||||
return fmt.Sprintf(
|
||||
`{"number":3,"state":%q,"merged":%t,"draft":%t,"mergeable":%t,"head":{"sha":"abc123"}}`,
|
||||
state, merged, draft, mergeable)
|
||||
}
|
||||
|
||||
func TestPullMerge(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
pr string
|
||||
mergeStatus int
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "success",
|
||||
pr: pullJSON("open", false, false, true),
|
||||
mergeStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "created is also success",
|
||||
pr: pullJSON("open", false, false, true),
|
||||
mergeStatus: http.StatusCreated,
|
||||
},
|
||||
{
|
||||
// gitea/tea#1022: an open PR with conflicts was reported as
|
||||
// possibly not open.
|
||||
name: "conflicting files",
|
||||
pr: pullJSON("open", false, false, false),
|
||||
mergeStatus: http.StatusMethodNotAllowed,
|
||||
wantErr: "failed to merge PR #3: it has conflicting files or is otherwise not mergeable",
|
||||
},
|
||||
{
|
||||
name: "already merged",
|
||||
pr: pullJSON("closed", true, false, false),
|
||||
mergeStatus: http.StatusMethodNotAllowed,
|
||||
wantErr: "failed to merge PR #3: it has already been merged",
|
||||
},
|
||||
{
|
||||
name: "closed",
|
||||
pr: pullJSON("closed", false, false, false),
|
||||
mergeStatus: http.StatusMethodNotAllowed,
|
||||
wantErr: "failed to merge PR #3: it is closed",
|
||||
},
|
||||
{
|
||||
name: "draft",
|
||||
pr: pullJSON("open", false, true, false),
|
||||
mergeStatus: http.StatusMethodNotAllowed,
|
||||
wantErr: "failed to merge PR #3: it is a draft; mark it ready for review first",
|
||||
},
|
||||
{
|
||||
// Open and mergeable, yet refused.
|
||||
name: "refused while mergeable",
|
||||
pr: pullJSON("open", false, false, true),
|
||||
mergeStatus: http.StatusMethodNotAllowed,
|
||||
wantErr: "failed to merge PR #3: the server refused the merge; check required status checks, requested reviews, or branch protection rules",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := mergeTestServer(t, tt.pr, tt.mergeStatus)
|
||||
defer server.Close()
|
||||
|
||||
err := PullMerge(t.Context(), &config.Login{
|
||||
Name: "test",
|
||||
URL: server.URL,
|
||||
Token: "secret-token",
|
||||
VersionCheck: false,
|
||||
}, "owner", "repo", 3, gitea.MergePullRequestOption{Style: gitea.MergeStyleMerge})
|
||||
|
||||
if tt.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, tt.wantErr, err.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal must still explain itself when the follow-up PR lookup fails.
|
||||
func TestPullMergeReasonUnavailable(t *testing.T) {
|
||||
server := mergeTestServer(t, "", http.StatusMethodNotAllowed)
|
||||
defer server.Close()
|
||||
|
||||
err := PullMerge(t.Context(), &config.Login{
|
||||
Name: "test",
|
||||
URL: server.URL,
|
||||
Token: "secret-token",
|
||||
VersionCheck: false,
|
||||
}, "owner", "repo", 3, gitea.MergePullRequestOption{
|
||||
Style: gitea.MergeStyleMerge,
|
||||
// Set so the SDK skips its own pre-merge PR lookup.
|
||||
HeadCommitId: "abc123",
|
||||
})
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, "failed to merge PR #3: the server refused the merge; check required status checks, requested reviews, or branch protection rules", err.Error())
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -6,13 +6,9 @@
|
||||
# Cloudflare R2 bucket, using curl's built-in AWS SigV4 signer (R2 is
|
||||
# S3-API compatible).
|
||||
#
|
||||
# This is the R2 half of the release process's parallel S3+R2 upload
|
||||
# period: goreleaser's `blobs:` pipe still uploads every release
|
||||
# artifact to AWS S3, and this script is invoked once per artifact
|
||||
# (via a goreleaser `publishers:` entry) to mirror the same artifact
|
||||
# into R2. Once the migration away from S3 is complete, the `blobs:`
|
||||
# block and the AWS_* secrets can be dropped without touching this
|
||||
# script.
|
||||
# It is invoked once per release artifact via a goreleaser
|
||||
# `publishers:` entry, and is the only artifact storage upload in the
|
||||
# release process.
|
||||
#
|
||||
# Usage:
|
||||
# upload-r2.sh <local-file> <remote-key>
|
||||
@@ -24,7 +20,7 @@
|
||||
# preflight step in CI: goreleaser custom publishers run as the very
|
||||
# last step of the publish pipeline, so without a preflight check a
|
||||
# missing R2_* secret would only be discovered after the Gitea release
|
||||
# has already been created and every artifact already uploaded to S3.
|
||||
# has already been created.
|
||||
#
|
||||
# Required environment variables:
|
||||
# R2_ENDPOINT Base URL of the R2 endpoint, e.g.
|
||||
|
||||
Reference in New Issue
Block a user