mirror of
https://gitea.com/gitea/tea.git
synced 2026-10-26 19:11:25 +01:00
refactor: remove features beyond the UX plan
Drop additions that the UX plan does not ask for: - the interactive label edit form; label edit now requires a flag - label clone and the skip mode of label creation it needed - repo rename rewriting the Git remote or tea.repository; it now warns that the remote still points to the old name - the extra "source" remote on clones of pull mirrors - run artifact download, which duplicates run download --zip - 256-color and 24-bit label swatches; colors stay ANSI 16 - config list --show-source (config get keeps it) - the membership and access GETs before team member/repo add and remove; Gitea's PUT and DELETE are idempotent label edit/delete keep --by-name: it is the only way to address a label whose name is a number that is also another label's ID. Signed-off-by: bircni <bircni@icloud.com>
This commit is contained in:
22 files changed
+69
-560
No files matched your search
@@ -25,10 +25,8 @@ import (
|
||||
func (a *application) artifactCommand() *cobra.Command {
|
||||
group := &cobra.Command{
|
||||
Use: "artifact",
|
||||
Short: "List and download the artifacts of runs",
|
||||
Long: `List the artifacts that a run uploaded and download one as a ZIP archive.
|
||||
|
||||
To download and extract the artifacts of a run by name, use tea run download.`,
|
||||
Short: "List the artifacts of runs",
|
||||
Long: "List the artifacts that a run uploaded. To download them, use tea run download.",
|
||||
}
|
||||
var limit, page int
|
||||
list := &cobra.Command{
|
||||
@@ -55,55 +53,6 @@ $ tea run artifact list 34`,
|
||||
list.ValidArgsFunction = a.completeRunArg()
|
||||
group.AddCommand(list)
|
||||
|
||||
var destination downloadFlags
|
||||
download := &cobra.Command{
|
||||
Use: "download <artifact-id>",
|
||||
Short: "Download an artifact as a ZIP archive",
|
||||
Long: "Download an artifact as a ZIP archive without extracting it, named after the artifact by default.",
|
||||
Example: `# download artifact 7 to <name>.zip
|
||||
$ tea run artifact download 7
|
||||
# write it to standard output
|
||||
$ tea run artifact download 7 --output - > build.zip`,
|
||||
Annotations: textOutput("artifact downloads are binary"),
|
||||
Args: argsExact(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
id, err := number(args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := a.resolve(cmd.Context(), true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service := services.Actions{Client: t.client, Repository: t.Repo}
|
||||
name := ""
|
||||
if destination.output == "" || isDirectory(destination.output) {
|
||||
artifact, err := service.Artifact(cmd.Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name = artifact.Name + ".zip"
|
||||
}
|
||||
path, skip, err := destination.destination(name)
|
||||
if err != nil || skip {
|
||||
return err
|
||||
}
|
||||
body, err := service.DownloadArtifact(cmd.Context(), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer body.Close()
|
||||
if err := a.download(cmd, destination, path, body); err != nil {
|
||||
return err
|
||||
}
|
||||
if path != "-" {
|
||||
a.done(cmd, "Downloaded artifact %d to %s", id, path)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
destination.register(download)
|
||||
group.AddCommand(download)
|
||||
return group
|
||||
}
|
||||
|
||||
|
||||
@@ -16,13 +16,11 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestArtifactDownloadsValidateDestinationAndKeepBinaryOutputClean(t *testing.T) {
|
||||
requests := 0
|
||||
func TestRunDownloadZipToStdoutKeepsBinaryOutputClean(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/repos/owner/repo/actions/artifacts/9":
|
||||
_, _ = w.Write([]byte(`{"id":9,"name":"build"}`))
|
||||
case "/api/v1/repos/owner/repo/actions/runs/29/artifacts":
|
||||
_, _ = w.Write([]byte(`{"total_count":1,"artifacts":[{"id":9,"name":"build"}]}`))
|
||||
case "/api/v1/repos/owner/repo/actions/artifacts/9/zip":
|
||||
require.Equal(t, "token token", r.Header.Get("Authorization"))
|
||||
http.Redirect(w, r, "/signed?signature=private", http.StatusFound)
|
||||
@@ -36,27 +34,11 @@ func TestArtifactDownloadsValidateDestinationAndKeepBinaryOutputClean(t *testing
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, diagnostics := serverDeps(t, server.URL)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"run", "artifact", "download", "9", "-R", "owner/repo", "--output-file", "-"}))
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"run", "download", "29", "-R", "owner/repo", "--zip", "-n", "build", "-O", "-"}))
|
||||
require.Equal(t, []byte{0x50, 0x4b, 0, 0xff}, out.Bytes())
|
||||
require.Empty(t, diagnostics.String())
|
||||
|
||||
dir := t.TempDir()
|
||||
out.Reset()
|
||||
args := []string{"run", "artifact", "download", "#9", "-R", "owner/repo", "--dir", dir}
|
||||
require.NoError(t, Execute(context.Background(), deps, args))
|
||||
data, err := os.ReadFile(filepath.Join(dir, "build.zip"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte{0x50, 0x4b, 0, 0xff}, data)
|
||||
require.Empty(t, out.String())
|
||||
before := requests
|
||||
err = Execute(context.Background(), deps, append(args, "--output", filepath.Join(dir, "build.zip")))
|
||||
require.ErrorContains(t, err, "--output and --dir cannot be combined")
|
||||
err = Execute(context.Background(), deps, []string{"run", "artifact", "download", "9", "-R", "owner/repo", "--output", filepath.Join(dir, "build.zip")})
|
||||
require.ErrorContains(t, err, "already exists; pass --clobber")
|
||||
require.Equal(t, before, requests)
|
||||
err = Execute(context.Background(), deps, []string{"run", "artifact", "download", "9", "-R", "owner/repo", "-O", "-", "--json"})
|
||||
require.ErrorContains(t, err, "binary")
|
||||
require.Equal(t, before, requests)
|
||||
err := Execute(context.Background(), deps, []string{"run", "download", "29", "-R", "owner/repo", "--zip", "-n", "build", "-O", "-", "--json"})
|
||||
require.ErrorContains(t, err, "run download writes files")
|
||||
}
|
||||
|
||||
// zipOf returns a ZIP archive of files, by name.
|
||||
|
||||
@@ -150,28 +150,6 @@ func TestSSHCloneTrustsAPIEndpointUnlessSSHHostIsConfigured(t *testing.T) {
|
||||
require.Empty(t, runner.calls)
|
||||
}
|
||||
|
||||
func TestCloneAddsSourceRemoteForMirrors(t *testing.T) {
|
||||
original := ""
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintf(w, `{"id":9,"name":"project","full_name":"alice/project","mirror":true,"clone_url":"http://%s/alice/project.git","original_url":%q}`, r.Host, original)
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, _ := serverDeps(t, server.URL)
|
||||
clone := credentialCall(t, deps, server.URL, "alice", "clone", "--", server.URL+"/alice/project.git", "destination")
|
||||
original = "https://github.com/upstream/project.git"
|
||||
runner := &fakeGit{results: map[string]string{clone: "", "remote add -- source " + original: ""}}
|
||||
deps.Git = runner
|
||||
args := []string{"repo", "clone", "alice/project", "destination", "--no-input", "--json"}
|
||||
require.NoError(t, Execute(context.Background(), deps, args))
|
||||
require.Equal(t, []string{clone, "remote add -- source " + original}, runner.calls)
|
||||
require.NotContains(t, out.String(), "github.com")
|
||||
for _, unsafe := range []string{"https://user:secret@github.com/upstream/project.git", "file:///srv/project.git", "ext::sh -c touch% /tmp/pwned"} {
|
||||
original, runner.calls = unsafe, nil
|
||||
require.NoError(t, Execute(context.Background(), deps, args), unsafe)
|
||||
require.Equal(t, []string{clone}, runner.calls, unsafe)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClonePassesGitFlagsAndNamesTheUpstreamRemote(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprintf(w, `{"name":"project","full_name":"bob/project","fork":true,"clone_url":"http://%[1]s/bob/project.git","parent":{"full_name":"alice/project","default_branch":"main","clone_url":"http://%[1]s/alice/project.git"}}`, r.Host)
|
||||
|
||||
+10
-21
@@ -107,11 +107,10 @@ func (a *application) effectivePreferences(snapshot settings.Snapshot) (settings
|
||||
return preferences, sources, nil
|
||||
}
|
||||
|
||||
// configSetting is one effective setting and where its value comes from.
|
||||
// configSetting is one effective setting.
|
||||
type configSetting struct {
|
||||
Key string
|
||||
Value any
|
||||
Source string
|
||||
Key string
|
||||
Value any
|
||||
}
|
||||
|
||||
// settingValues returns the effective preferences, the settings of the selected instance when it is
|
||||
@@ -242,45 +241,35 @@ $ tea config get ssh_key --host https://gitea.com --user alice`,
|
||||
}
|
||||
get.Flags().BoolVar(&getSource, "show-source", false, "Also print where the value comes from")
|
||||
group.AddCommand(get)
|
||||
var listSource bool
|
||||
list := &cobra.Command{
|
||||
Use: "list", Short: "List settings and their values", Args: argsExact(0),
|
||||
Example: `$ tea config list
|
||||
# Include the settings of an instance and where each value comes from
|
||||
$ tea config list --host https://gitea.com --show-source`,
|
||||
# Include the settings of an instance
|
||||
$ tea config list --host https://gitea.com`,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
snapshot, err := a.deps.Settings.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
values, sources, err := a.settingValues(snapshot)
|
||||
values, _, err := a.settingValues(snapshot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if a.options.json != "" {
|
||||
return a.writeSettingsJSON(cmd, values, sources, listSource)
|
||||
return a.writeJSON(cmd, values)
|
||||
}
|
||||
items := make([]configSetting, 0, len(values))
|
||||
for _, key := range slices.Sorted(maps.Keys(values)) {
|
||||
items = append(items, configSetting{key, values[key], settingSource(sources, key)})
|
||||
}
|
||||
columns := []terminal.Column{{Header: "Key"}, {Header: "Value", Flex: true}}
|
||||
if listSource {
|
||||
columns = append(columns, terminal.Column{Header: "Source"})
|
||||
items = append(items, configSetting{key, values[key]})
|
||||
}
|
||||
return writeTable(a, cmd, items, listSpec[configSetting]{
|
||||
Columns: columns,
|
||||
Columns: []terminal.Column{{Header: "Key"}, {Header: "Value", Flex: true}},
|
||||
Row: func(item configSetting) []terminal.Cell {
|
||||
row := []terminal.Cell{{Text: item.Key}, {Text: fmt.Sprint(item.Value)}}
|
||||
if listSource {
|
||||
row = append(row, terminal.Cell{Text: item.Source, Muted: true})
|
||||
}
|
||||
return row
|
||||
return []terminal.Cell{{Text: item.Key}, {Text: fmt.Sprint(item.Value)}}
|
||||
},
|
||||
}, listPage{Number: 1})
|
||||
},
|
||||
}
|
||||
list.Flags().BoolVar(&listSource, "show-source", false, "Show where each value comes from")
|
||||
group.AddCommand(list)
|
||||
group.AddCommand(&cobra.Command{
|
||||
Use: "set <key> <value>", Short: "Change a setting", Args: argsExact(2), ValidArgsFunction: a.completeConfig,
|
||||
|
||||
@@ -33,13 +33,12 @@ func (a *application) display() terminal.Display {
|
||||
preferences, _ := a.preferences()
|
||||
streams := a.deps.Streams
|
||||
return terminal.Display{
|
||||
TTY: streams.OutTTY,
|
||||
Color: terminal.ColorEnabled(preferences.Color, streams.OutTTY, a.deps.Getenv),
|
||||
TrueColor: terminal.TrueColor(a.deps.Getenv),
|
||||
Links: terminal.HyperlinksEnabled(preferences.Hyperlinks, streams.OutTTY, a.deps.Getenv),
|
||||
Markdown: terminal.MarkdownEnabled(preferences.Markdown, streams.OutTTY),
|
||||
Width: streams.Width,
|
||||
Now: a.deps.Now(),
|
||||
TTY: streams.OutTTY,
|
||||
Color: terminal.ColorEnabled(preferences.Color, streams.OutTTY, a.deps.Getenv),
|
||||
Links: terminal.HyperlinksEnabled(preferences.Hyperlinks, streams.OutTTY, a.deps.Getenv),
|
||||
Markdown: terminal.MarkdownEnabled(preferences.Markdown, streams.OutTTY),
|
||||
Width: streams.Width,
|
||||
Now: a.deps.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,12 +62,11 @@ func TestLabelListAppliesColorAndPagesWithNoInput(t *testing.T) {
|
||||
_, _ = w.Write([]byte(`[{"id":1,"name":"bug","color":"ff0000","description":"Defect"},{"id":2,"name":"docs","color":"00ff00","description":"Docs"}]`))
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, diagnostics, pager := pagedDeps(t, server.URL, map[string]string{"PAGER": "fake-pager", "COLORTERM": "truecolor"}, "color", "always")
|
||||
deps, out, diagnostics, pager := pagedDeps(t, server.URL, map[string]string{"PAGER": "fake-pager"}, "color", "always")
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"label", "list", "-R", "alice/project", "--no-input"}))
|
||||
require.Equal(t, 1, pager.calls)
|
||||
require.Equal(t, "fake-pager", pager.command)
|
||||
require.Contains(t, pager.input, "\x1b[38;2;255;0;0m● ff0000\x1b[0m")
|
||||
require.Contains(t, pager.input, "\x1b[38;2;0;255;0m● 00ff00\x1b[0m")
|
||||
require.Contains(t, pager.input, "\x1b[90mID\x1b[0m")
|
||||
require.Equal(t, "PAGED:"+pager.input, out.String())
|
||||
require.Empty(t, diagnostics.String())
|
||||
}
|
||||
@@ -120,7 +119,7 @@ func TestTeaPagerAndColorEnvironmentOverrides(t *testing.T) {
|
||||
deps, out, _, pager := pagedDeps(t, server.URL, env, "pager", "configured-pager", "color", "never")
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"label", "list", "-R", "alice/project", "--no-input"}))
|
||||
require.Equal(t, "tea-pager", pager.command)
|
||||
require.Contains(t, pager.input, "\x1b[38;5;196m● ff0000\x1b[0m")
|
||||
require.Contains(t, pager.input, "\x1b[90mID\x1b[0m")
|
||||
out.Reset()
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"config", "get", "pager", "--show-source", "--json"}))
|
||||
require.JSONEq(t, `{"pager":{"value":"tea-pager","source":"TEA_PAGER"}}`, withoutANSI(out.String()))
|
||||
@@ -142,7 +141,7 @@ func TestColorAutoUsesStdoutTTY(t *testing.T) {
|
||||
out.Reset()
|
||||
deps.Streams.OutTTY = true
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"label", "list", "-R", "alice/project", "--no-input"}))
|
||||
require.Contains(t, out.String(), "\x1b[38;5;196m● ff0000\x1b[0m")
|
||||
require.Contains(t, out.String(), "\x1b[90mID\x1b[0m")
|
||||
}
|
||||
|
||||
func TestMultiItemHumanOutputPagesOnce(t *testing.T) {
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/tea/internal/terminal"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -96,15 +95,11 @@ func TestLabelsByName(t *testing.T) {
|
||||
labels := `[{"id":11,"name":"bug","color":"ee0701"},{"id":12,"name":"kind/feature","color":"84b6eb","exclusive":true},{"id":13,"name":"2026","color":"cccccc"}]`
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET /api/v1/repos/alice/project/labels", "GET /api/v1/repos/bob/source/labels":
|
||||
case "GET /api/v1/repos/alice/project/labels":
|
||||
if r.URL.Query().Get("page") != "1" {
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/bob/source/labels" {
|
||||
_, _ = w.Write([]byte(`[{"id":1,"name":"bug","color":"000000"},{"id":2,"name":"docs","color":"0000ff","description":"Docs"}]`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(labels))
|
||||
default:
|
||||
changed = append(changed, r.Method+" "+r.URL.Path+" "+requestFields(t, r, "name", "color", "description"))
|
||||
@@ -131,15 +126,12 @@ func TestLabelsByName(t *testing.T) {
|
||||
require.NoError(t, run("label", "edit", "2026", "--by-name", "-d", "Year"))
|
||||
require.NoError(t, run("label", "delete", "BUG", "12", "--yes"))
|
||||
require.Equal(t, "✓ Deleted label \"bug\" from alice/project\n✓ Deleted label \"kind/feature\" from alice/project\n", diagnostics.String())
|
||||
require.NoError(t, run("label", "clone", "bob/source"))
|
||||
require.Equal(t, "! Skipped label \"bug\" in alice/project: it exists already\n✓ Created label \"docs\" in alice/project\n", diagnostics.String())
|
||||
require.Equal(t, []string{
|
||||
"POST /api/v1/repos/alice/project/labels name=docs color=0000FF description=Docs",
|
||||
"PATCH /api/v1/repos/alice/project/labels/12 name=kind/enhancement color=<nil> description=<nil>",
|
||||
"PATCH /api/v1/repos/alice/project/labels/13 name=<nil> color=<nil> description=Year",
|
||||
"DELETE /api/v1/repos/alice/project/labels/11 ",
|
||||
"DELETE /api/v1/repos/alice/project/labels/12 ",
|
||||
"POST /api/v1/repos/alice/project/labels name=docs color=0000ff description=Docs",
|
||||
}, changed)
|
||||
for _, test := range []struct {
|
||||
args []string
|
||||
@@ -194,45 +186,3 @@ func TestLabelCreatePicksAColorAndPrompts(t *testing.T) {
|
||||
require.Equal(t, "From a prompt", created[1]["description"])
|
||||
require.Equal(t, []string{"Label name", "Color (hex, e.g. d73a4a; empty = random):", "Description (optional):"}, prompt.asked)
|
||||
}
|
||||
|
||||
// labelFormPrompter answers the label form with edit applied to the current values.
|
||||
type labelFormPrompter struct {
|
||||
scriptedPrompter
|
||||
heading string
|
||||
edit func(*terminal.LabelFormValues)
|
||||
}
|
||||
|
||||
func (p *labelFormPrompter) EditLabel(_ context.Context, heading string, current terminal.LabelFormValues) (terminal.LabelFormValues, error) {
|
||||
p.heading = heading
|
||||
p.edit(¤t)
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func TestLabelEditFormStartsFromTheLabel(t *testing.T) {
|
||||
var edited string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET /api/v1/repos/alice/project/labels":
|
||||
if r.URL.Query().Get("page") != "1" {
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`[{"id":11,"name":"bug","color":"ee0701","description":"Broken"}]`))
|
||||
case "PATCH /api/v1/repos/alice/project/labels/11":
|
||||
edited = requestFields(t, r, "name", "color", "description", "exclusive")
|
||||
_, _ = w.Write([]byte(`{"id":11,"name":"defect"}`))
|
||||
default:
|
||||
t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, _, _ := serverDeps(t, server.URL)
|
||||
deps.Streams.InTTY, deps.Streams.ErrTTY = true, true
|
||||
prompt := &labelFormPrompter{edit: func(v *terminal.LabelFormValues) { v.Name, v.Exclusive = "defect", true }}
|
||||
deps.Prompter = prompt
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"label", "edit", "bug", "-R", "alice/project"}))
|
||||
require.Equal(t, `Editing label "bug" in alice/project`, prompt.heading)
|
||||
require.Equal(t, "name=defect color=ee0701 description=Broken exclusive=true", edited)
|
||||
deps.Streams.InTTY, deps.Streams.ErrTTY = false, false
|
||||
require.ErrorIs(t, Execute(context.Background(), deps, []string{"label", "edit", "bug", "-R", "alice/project"}), errNothingToEdit)
|
||||
}
|
||||
+6
-50
@@ -42,7 +42,7 @@ addressed by name or ID.`}
|
||||
}
|
||||
complete := a.completeScopedLabels(&org)
|
||||
group.AddCommand(a.labelListCommand(scope), a.labelCreateCommand(scope), a.labelEditCommand(scope, complete), a.labelDeleteCommand(scope, complete),
|
||||
a.labelImportCommand(scope), a.labelCloneCommand(scope), a.labelExportCommand(scope))
|
||||
a.labelImportCommand(scope), a.labelExportCommand(scope))
|
||||
return group
|
||||
}
|
||||
|
||||
@@ -240,16 +240,14 @@ func (a *application) reportLabel(cmd *cobra.Command, s services.Labels, item se
|
||||
func (a *application) labelEditCommand(scope labelScope, complete cobra.CompletionFunc) *cobra.Command {
|
||||
var fields labelFields
|
||||
var byName bool
|
||||
cmd := &cobra.Command{Use: "edit <label>", Short: "Edit a label", Long: "Edit a label. Without flags on a terminal, a form starts from the current values.", Example: `$ tea label edit bug --name defect --color b60205
|
||||
cmd := &cobra.Command{Use: "edit <label>", Short: "Edit a label", Example: `$ tea label edit bug --name defect --color b60205
|
||||
$ tea label edit "kind/question" --description "Further information is requested"
|
||||
$ tea label edit old-stuff --archived`, Annotations: map[string]string{"tea.arguments": labelArguments}, Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
opts, err := fields.options(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prompt := a.canPrompt()
|
||||
form, hasForm := a.deps.Prompter.(terminal.LabelForm)
|
||||
if opts == (services.LabelOptions{}) && (!prompt || !hasForm) {
|
||||
if opts == (services.LabelOptions{}) {
|
||||
return errNothingToEdit
|
||||
}
|
||||
s, err := scope(cmd)
|
||||
@@ -260,16 +258,6 @@ $ tea label edit old-stuff --archived`, Annotations: map[string]string{"tea.argu
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts == (services.LabelOptions{}) {
|
||||
current := found[0]
|
||||
values, err := form.EditLabel(cmd.Context(), "Editing "+labelName(s, current), terminal.LabelFormValues{
|
||||
Name: current.Name, Color: current.Color, Description: current.Description, Exclusive: current.Exclusive, Archived: current.Archived,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts = services.LabelOptions{Name: &values.Name, Color: &values.Color, Description: &values.Description, Exclusive: &values.Exclusive, Archived: &values.Archived}
|
||||
}
|
||||
item, err := s.Edit(cmd.Context(), found[0].ID, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -345,12 +333,12 @@ func (a *application) importLabels(cmd *cobra.Command, scope labelScope, file st
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.createLabels(cmd, s, rows, force, false)
|
||||
return a.createLabels(cmd, s, rows, force)
|
||||
}
|
||||
|
||||
// createLabels creates each label in rows, continuing past failures. A label that exists already
|
||||
// is updated with force, skipped with skip, and fails otherwise.
|
||||
func (a *application) createLabels(cmd *cobra.Command, s services.Labels, rows []services.LabelOptions, force, skip bool) error {
|
||||
// is updated with force and fails otherwise.
|
||||
func (a *application) createLabels(cmd *cobra.Command, s services.Labels, rows []services.LabelOptions, force bool) error {
|
||||
existing, err := s.All(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -358,11 +346,7 @@ func (a *application) createLabels(cmd *cobra.Command, s services.Labels, rows [
|
||||
outcome := map[string]string{}
|
||||
results, failures := applyBatch(cmd, rows, func(row services.LabelOptions) string { return "label " + strconv.Quote(*row.Name) }, func(row services.LabelOptions) (services.Label, error) {
|
||||
item, updated, err := s.CreateUnique(cmd.Context(), existing, row, force)
|
||||
var conflict *services.ConflictError
|
||||
switch {
|
||||
case skip && errors.As(err, &conflict) && conflict.Reason == services.ReasonExists:
|
||||
outcome[*row.Name] = "Skipped"
|
||||
return services.Label{Name: *row.Name}, nil
|
||||
case err != nil:
|
||||
return item, err
|
||||
case updated:
|
||||
@@ -373,10 +357,6 @@ func (a *application) createLabels(cmd *cobra.Command, s services.Labels, rows [
|
||||
}
|
||||
return item, nil
|
||||
}, func(item services.Label) {
|
||||
if outcome[item.Name] == "Skipped" {
|
||||
a.warn(cmd, "Skipped %s: it exists already", labelName(s, item))
|
||||
return
|
||||
}
|
||||
a.done(cmd, "%s %s", outcome[item.Name], labelName(s, item))
|
||||
})
|
||||
if a.options.json != "" {
|
||||
@@ -385,30 +365,6 @@ func (a *application) createLabels(cmd *cobra.Command, s services.Labels, rows [
|
||||
return errors.Join(failures...)
|
||||
}
|
||||
|
||||
func (a *application) labelCloneCommand(scope labelScope) *cobra.Command {
|
||||
var force bool
|
||||
cmd := &cobra.Command{Use: "clone <source-repository>", Short: "Copy the labels of another repository", Long: `Create the labels of the source repository in the selected repository or organization.
|
||||
Labels that exist already are skipped unless --force updates them.`, Example: `$ tea label clone alice/project
|
||||
$ tea label clone alice/project --repo alice/new --force`, Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
|
||||
s, err := scope(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
source, err := (services.Labels{Client: s.Client, Repository: args[0]}).All(cmd.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]services.LabelOptions, len(source))
|
||||
for i, item := range source {
|
||||
rows[i] = services.LabelOptions{Name: &item.Name, Color: &item.Color, Description: &item.Description, Exclusive: &item.Exclusive}
|
||||
}
|
||||
return a.createLabels(cmd, s, rows, force, true)
|
||||
}}
|
||||
cmd.Flags().BoolVarP(&force, "force", "f", false, "Update labels that exist already")
|
||||
cmd.ValidArgsFunction = a.completeRepos()
|
||||
return cmd
|
||||
}
|
||||
|
||||
// completeScopedLabels completes the label names of the repository or, with --org, of the
|
||||
// organization that *org names.
|
||||
func (a *application) completeScopedLabels(org *string) cobra.CompletionFunc {
|
||||
|
||||
@@ -41,7 +41,7 @@ func TestManIncludesFullCommandTree(t *testing.T) {
|
||||
deps, out, _ := testDeps(t)
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"man"}))
|
||||
manual := out.String()
|
||||
for _, command := range []string{"tea-pr-checkout", "tea-issue-comment-create", "tea-auth-login", "tea-run-artifact-download"} {
|
||||
for _, command := range []string{"tea-pr-checkout", "tea-issue-comment-create", "tea-auth-login", "tea-run-artifact-list"} {
|
||||
require.Contains(t, manual, command)
|
||||
}
|
||||
require.Contains(t, manual, `.TH "TEA-PR-CHECKOUT" "1" "Jan 2026"`)
|
||||
|
||||
@@ -487,13 +487,6 @@ func (a *application) cloneRepository(cmd *cobra.Command, t target, item service
|
||||
}
|
||||
a.done(cmd, "Added remote %s for %s; tea commands in the clone target it (change with tea repo set-default)", opts.upstream, item.Parent.FullName)
|
||||
}
|
||||
// The remote is named source because repository discovery prefers a remote named upstream.
|
||||
if source := mirrorSourceURL(item); source != "" {
|
||||
if _, err := a.gitIn(cmd.Context(), clone, "remote", "add", "--", "source", source); err != nil {
|
||||
return clone, fmt.Errorf("cloned the mirror, but could not add the source remote: %w", err)
|
||||
}
|
||||
a.done(cmd, "Added remote source for the mirror's source")
|
||||
}
|
||||
return clone, nil
|
||||
}
|
||||
|
||||
@@ -593,9 +586,7 @@ func (a *application) repoRenameCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "rename <new-name>",
|
||||
Short: "Rename a repository",
|
||||
Long: `Rename a repository; its owner stays the same. Gitea redirects the old name to the new one. When
|
||||
the repository was found through a Git remote of the current clone, or through tea repo set-default,
|
||||
that remote or setting moves to the new name.`,
|
||||
Long: "Rename a repository; its owner stays the same. Gitea redirects the old name to the new one.",
|
||||
Example: `# Rename the repository of the current clone
|
||||
$ tea repo rename new-name
|
||||
|
||||
@@ -630,8 +621,8 @@ $ tea repo rename new-name -R alice/old-name`,
|
||||
return err
|
||||
}
|
||||
a.done(cmd, "Renamed repository %s to %s", t.Repo, item.FullName)
|
||||
if err := a.followRename(cmd, t, current, item); err != nil {
|
||||
return err
|
||||
if remote, ok := strings.CutPrefix(t.RepoSource, "remote "); ok {
|
||||
a.warn(cmd, "Git remote %s still points to %s; update it with git remote set-url", remote, t.Repo)
|
||||
}
|
||||
return a.writeMutationJSON(cmd, item)
|
||||
},
|
||||
@@ -639,46 +630,6 @@ $ tea repo rename new-name -R alice/old-name`,
|
||||
return command
|
||||
}
|
||||
|
||||
// followRename points the Git remote or the saved default repository that selected a renamed
|
||||
// repository, previously named old, at its new name.
|
||||
func (a *application) followRename(cmd *cobra.Command, t target, old string, item services.Repository) error {
|
||||
if remote, ok := strings.CutPrefix(t.RepoSource, "remote "); ok {
|
||||
raw, err := a.git(cmd.Context(), "remote", "get-url", remote)
|
||||
if err != nil {
|
||||
return fmt.Errorf("renamed %s, but could not read Git remote %s: %w", item.FullName, remote, err)
|
||||
}
|
||||
renamed, ok := renamedURL(raw, old, item.Name)
|
||||
if !ok {
|
||||
a.warn(cmd, "Git remote %s still points to %s; update it with git remote set-url", remote, t.Repo)
|
||||
return nil
|
||||
}
|
||||
if _, err := a.git(cmd.Context(), "remote", "set-url", remote, renamed); err != nil {
|
||||
return fmt.Errorf("renamed %s, but could not update Git remote %s: %w", item.FullName, remote, err)
|
||||
}
|
||||
a.done(cmd, "Updated Git remote %s to %s", remote, item.FullName)
|
||||
}
|
||||
if t.RepoSource == "git config tea.repository" {
|
||||
if _, err := a.git(cmd.Context(), "config", "--local", "tea.repository", t.Host+"/"+item.FullName); err != nil {
|
||||
return fmt.Errorf("renamed %s, but could not update the default repository: %w", item.FullName, err)
|
||||
}
|
||||
a.done(cmd, "Set %s as the default repository for this clone", item.FullName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// renamedURL replaces the repository name old at the end of a remote URL with name, keeping the
|
||||
// rest of the URL, such as an SSH host alias, and its .git suffix.
|
||||
func renamedURL(raw, old, name string) (string, bool) {
|
||||
base, suffix := strings.TrimSuffix(raw, "/"), ""
|
||||
if trimmed, ok := strings.CutSuffix(base, ".git"); ok {
|
||||
base, suffix = trimmed, ".git"
|
||||
}
|
||||
if len(base) <= len(old) || !strings.EqualFold(base[len(base)-len(old):], old) || !strings.ContainsRune("/:", rune(base[len(base)-len(old)-1])) {
|
||||
return "", false
|
||||
}
|
||||
return base[:len(base)-len(old)] + name + suffix, true
|
||||
}
|
||||
|
||||
func (a *application) repoDeleteCommand() *cobra.Command {
|
||||
command := &cobra.Command{
|
||||
Use: "delete [<repository>]",
|
||||
|
||||
@@ -124,7 +124,7 @@ func TestRepoArchiveAsksWithTheConsequence(t *testing.T) {
|
||||
require.Equal(t, []string{"Archive alice/project (from git remote upstream)? It becomes read-only."}, prompt.confirmations)
|
||||
}
|
||||
|
||||
func TestRepoRenameFollowsTheRemote(t *testing.T) {
|
||||
func TestRepoRenameHintsAtTheRemote(t *testing.T) {
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPatch+" /api/v1/repos/alice/project", r.Method+" "+r.URL.Path)
|
||||
requirePayload(t, `{"name":"renamed"}`, r.Body)
|
||||
@@ -132,31 +132,14 @@ func TestRepoRenameFollowsTheRemote(t *testing.T) {
|
||||
}))
|
||||
defer server.Close()
|
||||
deps, out, diagnostics := repoTTYDeps(t, server.URL)
|
||||
runner := &fakeGit{results: map[string]string{
|
||||
"symbolic-ref --short HEAD": "main",
|
||||
"config --get branch.main.remote": "origin",
|
||||
"remote get-url origin": server.URL + "/alice/project.git",
|
||||
"remote set-url origin " + server.URL + "/alice/renamed.git": "",
|
||||
deps.Git = &fakeGit{results: map[string]string{
|
||||
"symbolic-ref --short HEAD": "main",
|
||||
"config --get branch.main.remote": "origin",
|
||||
"remote get-url origin": server.URL + "/alice/project.git",
|
||||
}}
|
||||
deps.Git = runner
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "rename", "renamed", "--yes"}))
|
||||
require.Contains(t, runner.calls, "remote set-url origin "+server.URL+"/alice/renamed.git")
|
||||
require.Empty(t, out.String())
|
||||
require.Equal(t, "✓ Renamed repository alice/project to alice/renamed\n✓ Updated Git remote origin to alice/renamed\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestRenamedURL(t *testing.T) {
|
||||
for _, test := range []struct{ raw, want string }{
|
||||
{"https://gitea.test/alice/project.git", "https://gitea.test/alice/renamed.git"},
|
||||
{"https://gitea.test/alice/project/", "https://gitea.test/alice/renamed"},
|
||||
{"git@gitea-alias:alice/Project.git", "git@gitea-alias:alice/renamed.git"},
|
||||
{"ssh://git@gitea.test:2222/alice/project", "ssh://git@gitea.test:2222/alice/renamed"},
|
||||
{"https://gitea.test/alice/subproject.git", ""},
|
||||
} {
|
||||
renamed, ok := renamedURL(test.raw, "project", "renamed")
|
||||
require.Equal(t, test.want != "", ok, test.raw)
|
||||
require.Equal(t, test.want, renamed, test.raw)
|
||||
}
|
||||
require.Equal(t, "✓ Renamed repository alice/project to alice/renamed\n! Git remote origin still points to alice/project; update it with git remote set-url\n", diagnostics.String())
|
||||
}
|
||||
|
||||
func TestRepoForkReportsAnExistingFork(t *testing.T) {
|
||||
|
||||
+2
-38
@@ -537,14 +537,6 @@ $ tea team member add 2 bob carol`,
|
||||
return err
|
||||
}
|
||||
for _, username := range args[1:] {
|
||||
member, err := service.IsMember(cmd.Context(), team.ID, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if member {
|
||||
a.warn(cmd, "%s is already a member of team %s", username, team.Slug())
|
||||
continue
|
||||
}
|
||||
if err := service.SetMember(cmd.Context(), team.ID, username, true); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -566,21 +558,7 @@ $ tea team member add 2 bob carol`,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var members []string
|
||||
for _, username := range args[1:] {
|
||||
member, err := service.IsMember(cmd.Context(), team.ID, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
a.warn(cmd, "%s is not a member of team %s", username, team.Slug())
|
||||
continue
|
||||
}
|
||||
members = append(members, username)
|
||||
}
|
||||
if len(members) == 0 {
|
||||
return nil
|
||||
}
|
||||
members := args[1:]
|
||||
if err := a.confirmAction(cmd, terminal.Confirmation{
|
||||
Prompt: fmt.Sprintf("Remove %s from team %s?", joinNames(members), team.Slug()),
|
||||
NonTTY: fmt.Sprintf("remove %s from team %s", joinNames(members), team.Slug()),
|
||||
@@ -683,21 +661,7 @@ repositories of other owners cannot be granted to a team.`,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
has, err := service.HasRepository(cmd.Context(), team.ID, repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case has && grant:
|
||||
a.warn(cmd, "Team %s already has access to %s", team.Slug(), repo)
|
||||
case !has && !grant:
|
||||
a.warn(cmd, "Team %s has no access to %s", team.Slug(), repo)
|
||||
default:
|
||||
repos = append(repos, repo)
|
||||
}
|
||||
}
|
||||
if len(repos) == 0 {
|
||||
return nil
|
||||
repos = append(repos, repo)
|
||||
}
|
||||
if !grant {
|
||||
if err := a.confirmAction(cmd, terminal.Confirmation{
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -86,8 +87,6 @@ func TestTeamRepoAddTakesRepositoriesAsArguments(t *testing.T) {
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET /api/v1/teams/5":
|
||||
_, _ = w.Write([]byte(`{"id":5,"name":"devs","permission":"none","organization":{"username":"acme"}}`))
|
||||
case "GET /api/v1/teams/5/repos/acme/service", "GET /api/v1/teams/5/repos/acme/website":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case "PUT /api/v1/teams/5/repos/acme/service", "PUT /api/v1/teams/5/repos/acme/website":
|
||||
granted = append(granted, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
@@ -182,18 +181,14 @@ func TestTeamPermissionSetsEveryUnit(t *testing.T) {
|
||||
require.Equal(t, map[string]any{"permission": "read", "units_map": wikiWrite}, sent[1])
|
||||
}
|
||||
|
||||
func TestTeamMemberRemoveNamesMembersAndSkipsOthers(t *testing.T) {
|
||||
func TestTeamMemberRemoveConfirmsOnce(t *testing.T) {
|
||||
var removed []string
|
||||
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET /api/v1/teams/5":
|
||||
_, _ = w.Write([]byte(`{"id":5,"name":"devs","organization":{"username":"acme"}}`))
|
||||
case "GET /api/v1/teams/5/members/carol":
|
||||
_, _ = w.Write([]byte(`{"login":"carol"}`))
|
||||
case "GET /api/v1/teams/5/members/dave":
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case "DELETE /api/v1/teams/5/members/carol":
|
||||
removed = append(removed, "carol")
|
||||
case "DELETE /api/v1/teams/5/members/carol", "DELETE /api/v1/teams/5/members/dave":
|
||||
removed = append(removed, path.Base(r.URL.Path))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
@@ -205,7 +200,7 @@ func TestTeamMemberRemoveNamesMembersAndSkipsOthers(t *testing.T) {
|
||||
prompt := &scriptedPrompter{accept: true}
|
||||
deps.Prompter = prompt
|
||||
require.NoError(t, Execute(context.Background(), deps, []string{"team", "member", "remove", "5", "carol", "dave"}))
|
||||
require.Equal(t, []string{"Remove carol from team acme/devs?"}, prompt.confirmations)
|
||||
require.Equal(t, []string{"carol"}, removed)
|
||||
require.Equal(t, "! dave is not a member of team acme/devs\n✓ Removed carol from team acme/devs\n", withoutANSI(diagnostics.String()))
|
||||
require.Equal(t, []string{"Remove carol and dave from team acme/devs?"}, prompt.confirmations)
|
||||
require.Equal(t, []string{"carol", "dave"}, removed)
|
||||
require.Equal(t, "✓ Removed carol from team acme/devs\n✓ Removed dave from team acme/devs\n", withoutANSI(diagnostics.String()))
|
||||
}
|
||||
Reference in new issue
Block a user