chore: align golangci-lint config with Gitea (#104)

Use the same linters, settings and formatters as Gitea's `.golangci.yml`, so code moving between the two projects meets the same bar. Rules that only apply to Gitea's codebase (its json/ini/cache wrappers, migrations, swagger, process wrapper) are left out, this repo's extra checks (`misspell`, `copyloopvar`, a few revive rules) are kept.

`gci` now owns import grouping (standard, `gitea.dev`, others), so `make fmt` and `make fmt-check` run `golangci-lint fmt`. The unused `.revive.toml` is removed. The rest of the diff fixes the newly reported issues without behavior changes.

_Written by Claude (Opus 5.5)._

Reviewed-on: https://gitea.com/gitea/cli/pulls/104
Reviewed-by: Lunny Xiao <[email protected]>
Co-authored-by: silverwind <[email protected]>
This commit is contained in:
silverwind
2026-11-07 07:45:18 +00:00
committed by bircni
parent 3a42ef8916
commit 37e51013a3
293 changed files with 933 additions and 421 deletions
+134 -22
View File
@@ -1,46 +1,158 @@
version: "2"
formatters:
enable:
- gofumpt
output:
sort-order:
- file
linters:
default: none
enable:
- govet
- revive
- misspell
- ineffassign
- unused
- bidichk
- bodyclose
- copyloopvar
- depguard
- dupl
- errcheck
- exhaustruct_v5
- forbidigo
- forcetypeassert
- gocheckcompilerdirectives
- gocritic
- govet
- ineffassign
- mirror
- misspell
- modernize
- nakedret
- nilnil
- nolintlint
- perfsprint
- revive
- staticcheck
- testifylint
- unconvert
- unparam
- unused
- usestdlibvars
- usetesting
- wastedassign
settings:
depguard:
rules:
main:
deny:
- pkg: io/ioutil
desc: use os or io instead
- pkg: golang.org/x/exp
desc: it's experimental and unreliable
- pkg: github.com/pkg/errors
desc: use builtin errors package instead
forbidigo:
forbid:
- pattern: '^(fmt\.Print(|f|ln)|print|println)$' # default
modernize:
disable:
- embedlit
nolintlint:
allow-unused: false
require-explanation: true
require-specific: true
gocritic:
enabled-checks:
- equalFold
disabled-checks:
- ifElseChain
- singleCaseSwitch
misspell:
locale: US
revive:
severity: error
rules:
- name: blank-imports
- name: constant-logical-expr
- name: context-as-argument
- name: context-keys-type
- name: dot-imports
- name: empty-lines
- name: error-naming
- name: error-return
- name: error-strings
- name: error-naming
- name: errorf
- name: exported
- name: identical-branches
- name: if-return
- name: increment-decrement
- name: var-declaration
- name: indent-error-flow
- name: modifies-value-receiver
- name: package-comments
- name: range
- name: receiver-naming
- name: redefines-builtin-id
- name: superfluous-else
- name: time-naming
- name: unexported-return
- name: indent-error-flow
- name: errorf
misspell:
locale: US
ignore-words:
- unknwon
- destory
- name: var-declaration
- name: var-naming
arguments:
- [] # AllowList - do not remove as args for the rule are positional and won't work without lists first
- [] # DenyList
- - skip-initialism-name-checks: true
staticcheck:
checks:
- all
- -ST1003
- -ST1005
- -QF1001
- -QF1006
- -QF1008
testifylint:
disable:
- empty
- go-require
- require-error
usetesting:
os-temp-dir: true
perfsprint:
concat-loop: false
govet:
enable:
- nilness
- unusedwrite
exhaustruct_v5:
explicit-mode: true
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
- linters:
- dupl
- errcheck
- forbidigo
- staticcheck
- unparam
path: _test\.go
issues:
max-issues-per-linter: 0
max-same-issues: 0
formatters:
enable:
- gci
- gofumpt
settings:
gci:
custom-order: true
sections:
- standard
- prefix(gitea.dev)
- blank
- default
gofumpt:
extra:
group-params: true
exclusions:
generated: lax
run:
timeout: 10m
-24
View File
@@ -1,24 +0,0 @@
ignoreGeneratedHeader = false
severity = "warning"
confidence = 0.8
errorCode = 1
warningCode = 1
[rule.blank-imports]
[rule.context-as-argument]
[rule.context-keys-type]
[rule.dot-imports]
[rule.error-return]
[rule.error-strings]
[rule.error-naming]
[rule.exported]
[rule.if-return]
[rule.increment-decrement]
[rule.var-naming]
[rule.var-declaration]
[rule.range]
[rule.receiver-naming]
[rule.time-naming]
[rule.unexported-return]
[rule.indent-error-flow]
[rule.errorf]
+3 -2
View File
@@ -151,14 +151,15 @@ Unit and integration tests live beside their packages; see [Testing redux](#test
### Code Style
Use `make fmt`, check with `make lint`.
Group imports into the standard library, then all other packages (local and
external) in one sorted block, as gofumpt keeps them:
Group imports into the standard library, then `gitea.dev` packages, then other
external packages, as `make fmt` sorts them:
```go
import (
"encoding/json"
"fmt"
"gitea.dev/cli/internal/services"
"github.com/foo/bar"
"gopkg.io/baz.v1"
)
+2 -11
View File
@@ -3,10 +3,7 @@ GO ?= go
export PATH := $(shell $(GO) env GOPATH)/bin:$(PATH)
GOFILES := $(shell find . -name "*.go" -type f)
# Tool packages with pinned versions
GOFUMPT_PACKAGE ?= mvdan.cc/[email protected] # renovate: datasource=go
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/v2/cmd/[email protected] # renovate: datasource=go
DEADCODE_PACKAGE ?= golang.org/x/tools/cmd/[email protected] # renovate: datasource=go
WINDOWS_TEST_IMAGE ?= dockurr/windows:6.06@sha256:16fd7c39a3e48bb946d29c59dc6015942e5b900a1fa5d7e5552053bfc48ee2ea # renovate: datasource=docker
@@ -43,7 +40,7 @@ clean:
.PHONY: fmt
fmt:
$(GO) run $(GOFUMPT_PACKAGE) -w $(GOFILES)
$(GO) run $(GOLANGCI_LINT_PACKAGE) fmt
.PHONY: vet
vet:
@@ -76,13 +73,7 @@ lint-pr-title: ## lint PR title against Conventional Commits (set PR_TITLE=...)
.PHONY: fmt-check
fmt-check:
# get all go files and run gofumpt on them
@diff=$$($(GO) run $(GOFUMPT_PACKAGE) -d $(GOFILES)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make fmt' and commit the result:"; \
echo "$${diff}"; \
exit 1; \
fi;
@$(GO) run $(GOLANGCI_LINT_PACKAGE) fmt --diff || { echo "Please run 'make fmt' and commit the result"; exit 1; }
# Man pages are dated by the last commit unless SOURCE_DATE_EPOCH is already set.
.PHONY: docs
+4 -2
View File
@@ -14,6 +14,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"testing"
@@ -25,6 +26,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -57,7 +59,7 @@ func TestSignalInterruptReturns130(t *testing.T) {
}
environment = append(environment, entry)
}
command.Env = append(environment, "GITEA_CLI_CONFIG_DIR="+t.TempDir(), "GITEA_CLI_HOST="+server.URL, "GITEA_TOKEN=disposable-test-token")
command.Env = slices.Concat(environment, []string{"GITEA_CLI_CONFIG_DIR=" + t.TempDir(), "GITEA_CLI_HOST=" + server.URL, "GITEA_TOKEN=disposable-test-token"})
var stdout, stderr bytes.Buffer
command.Stdout, command.Stderr = &stdout, &stderr
require.NoError(t, command.Start())
@@ -72,7 +74,7 @@ func TestSignalInterruptReturns130(t *testing.T) {
select {
case err := <-done:
var exit *exec.ExitError
require.True(t, errors.As(err, &exit))
require.ErrorAs(t, err, &exit)
require.Equal(t, 130, exit.ExitCode())
case <-ctx.Done():
t.Fatal("CLI did not exit after interrupt")
+6 -5
View File
@@ -5,6 +5,7 @@
package aliases
import (
"errors"
"fmt"
"regexp"
"strconv"
@@ -34,16 +35,16 @@ func validate(name, expansion string, builtins map[string]bool) error {
return fmt.Errorf("invalid alias expansion: %w", err)
}
if len(words) == 0 {
return fmt.Errorf("alias expansion cannot be empty")
return errors.New("alias expansion cannot be empty")
}
if strings.HasPrefix(words[0], "!") {
return fmt.Errorf("shell aliases are not supported")
return errors.New("shell aliases are not supported")
}
// Expansion never runs a shell; rejecting common operators only flags misleading shortcuts.
for _, word := range words {
switch word {
case "|", "||", "&", "&&", ";", "<", ">", ">>", "2>":
return fmt.Errorf("shell aliases are not supported")
return errors.New("shell aliases are not supported")
}
}
return nil
@@ -140,13 +141,13 @@ func ExpandCompletion(args []string, definitions map[string]string, builtins map
for index, word := range expanded {
if strings.Contains(word, marker) {
if word != marker || position != -1 {
return nil, fmt.Errorf("completion of embedded or repeated placeholders is ambiguous")
return nil, errors.New("completion of embedded or repeated placeholders is ambiguous")
}
position = index
}
}
if position == -1 {
return nil, fmt.Errorf("alias completion lost its current argument")
return nil, errors.New("alias completion lost its current argument")
}
result := append([]string{}, expanded[:position]...)
result = append(result, expanded[position+1:]...)
+1
View File
@@ -10,6 +10,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -19,6 +19,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
@@ -35,7 +36,7 @@ func TestRunLogsStreamWithoutMixingDiagnosticsAndVerifyJobMembership(t *testing.
_, _ = w.Write([]byte("exact log\n"))
default:
t.Errorf("unexpected endpoint %s", r.URL.Path)
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
+2 -1
View File
@@ -18,6 +18,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/mattn/go-runewidth"
"github.com/spf13/cobra"
)
@@ -103,7 +104,7 @@ $ gt run list --since 24h --json id,status,conclusion,workflow`,
},
}
pageFlags(cmd, &filters.Limit, &filters.Page)
created.register(cmd, "since", "Runs created at or after a date, RFC3339 timestamp, or duration ago (24h)", "until", "Runs created at or before a date, RFC3339 timestamp, or duration ago")
created.register(cmd, "Runs created at or after a date, RFC3339 timestamp, or duration ago (24h)", "Runs created at or before a date, RFC3339 timestamp, or duration ago")
cmd.Flags().StringVarP(&filters.Workflow, "workflow", "w", "", "Filter by workflow file or name")
cmd.Flags().StringVarP(&filters.Branch, "branch", "b", "", "Filter by branch")
cmd.Flags().StringVarP(&filters.Event, "event", "e", "", "Filter by the event that triggered the run, such as push")
+1
View File
@@ -18,6 +18,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/mattn/go-runewidth"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+4 -2
View File
@@ -9,10 +9,12 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
"testing"
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
@@ -58,7 +60,7 @@ func TestGiteaActionsQueuedRunLifecycle(t *testing.T) {
require.NoError(t, json.Unmarshal(execute("run", "list", "-R", repo.FullName, "--branch", "does-not-exist", "--json"), &matching))
require.Empty(t, matching)
id := fmt.Sprint(runs[0].ID)
id := strconv.FormatInt(runs[0].ID, 10)
var jobs []services.Job
require.NoError(t, json.Unmarshal(execute("run", "jobs", id, "-R", repo.FullName, "--json"), &jobs))
require.NotEmpty(t, jobs)
@@ -69,7 +71,7 @@ func TestGiteaActionsQueuedRunLifecycle(t *testing.T) {
require.NotNil(t, artifacts)
out.Reset()
diagnostics.Reset()
err = Execute(context.Background(), deps, []string{"run", "logs", id, "-R", repo.FullName, "--job", fmt.Sprint(jobs[0].ID), "--follow", "--interval=10ms", "--timeout=100ms"})
err = Execute(context.Background(), deps, []string{"run", "logs", id, "-R", repo.FullName, "--job", strconv.FormatInt(jobs[0].ID, 10), "--follow", "--interval=10ms", "--timeout=100ms"})
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Empty(t, out.String())
var canceled services.Run
+1
View File
@@ -11,6 +11,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+5 -3
View File
@@ -9,11 +9,13 @@ import (
"encoding/json"
"fmt"
"slices"
"strconv"
"strings"
"testing"
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
@@ -36,14 +38,14 @@ func TestGiteaActivityFeeds(t *testing.T) {
scoped := func(args ...string) []byte { return as(append(args, "-R", repo.FullName)...) }
var issue services.Issue
require.NoError(t, json.Unmarshal(scoped("issue", "create", "--title", "Crash on start", "--body", "b", "--json"), &issue))
scoped("issue", "comment", "create", fmt.Sprint(issue.Number), "--body", "Looks good to me")
scoped("issue", "close", fmt.Sprint(issue.Number))
scoped("issue", "comment", "create", strconv.FormatInt(issue.Number, 10), "--body", "Looks good to me")
scoped("issue", "close", strconv.FormatInt(issue.Number, 10))
scoped("branch", "create", "feature")
deps.Streams.In = strings.NewReader(fmt.Sprintf(`{"branch":"feature","content":%q,"message":"Add the feature"}`, base64.StdEncoding.EncodeToString([]byte("x\n"))))
as("api", "repos/"+repo.FullName+"/contents/feature.txt", "--input", "-")
var pull services.Pull
require.NoError(t, json.Unmarshal(scoped("pr", "create", "--title", "The feature", "--body", "b", "--head", "feature", "--base", repo.DefaultBranch, "--json"), &pull))
scoped("pr", "merge", fmt.Sprint(pull.Number), "--squash", "--yes")
scoped("pr", "merge", strconv.FormatInt(pull.Number, 10), "--squash", "--yes")
scoped("release", "create", "v1", "--title", "One", "--notes", "n")
run := func(args ...string) string {
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -22,6 +22,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/spf13/cobra"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
+12 -5
View File
@@ -21,6 +21,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/require"
)
@@ -35,7 +36,8 @@ func TestAPIFieldsPlaceholdersAndAtomicPagination(t *testing.T) {
require.NoError(t, json.NewDecoder(r.Body).Decode(&fields))
require.Equal(t, "123", fields["title"])
require.Equal(t, true, fields["closed"])
require.Equal(t, float64(2), fields["number"])
require.IsType(t, float64(0), fields["number"])
require.InDelta(t, float64(2), fields["number"], 0)
_, _ = w.Write([]byte(`{"number":2}`))
return
}
@@ -44,7 +46,7 @@ func TestAPIFieldsPlaceholdersAndAtomicPagination(t *testing.T) {
w.Header().Set("X-Gt-Test", "header-on-stderr")
if r.URL.Query().Get("page") == "2" {
if failSecond {
w.WriteHeader(403)
w.WriteHeader(http.StatusForbidden)
return
}
_, _ = w.Write([]byte(`[{"number":2}]`))
@@ -121,10 +123,11 @@ func TestAPIDebugLogsRequestsToStderr(t *testing.T) {
}
func TestAPIWritesErrorResponses(t *testing.T) {
const body = `{"message":"invalid","errors":["title"]}`
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("X-Gt-Test", "error-header")
w.WriteHeader(http.StatusUnprocessableEntity)
_, _ = w.Write([]byte(`{"message":"invalid","errors":["title"]}`))
_, _ = w.Write([]byte(body))
}))
defer server.Close()
deps, out, diagnostics := serverDeps(t, server.URL)
@@ -132,7 +135,9 @@ func TestAPIWritesErrorResponses(t *testing.T) {
var apiErr *transport.APIError
require.ErrorAs(t, err, &apiErr)
require.Equal(t, http.StatusUnprocessableEntity, apiErr.Status)
require.Equal(t, `{"message":"invalid","errors":["title"]}`, out.String())
if out.String() != body {
t.Fatalf("output = %q, want %q", out.String(), body)
}
require.Contains(t, diagnostics.String(), "422 Unprocessable Entity")
require.Contains(t, diagnostics.String(), "X-Gt-Test: error-header")
}
@@ -409,7 +414,9 @@ func TestAPIHelpShowsJQ(t *testing.T) {
func TestAPIIncludeSanitizesTheStatusLine(t *testing.T) {
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
conn, rw, err := w.(http.Hijacker).Hijack()
hijacker, ok := w.(http.Hijacker)
require.True(t, ok)
conn, rw, err := hijacker.Hijack()
if err != nil {
return
}
+1
View File
@@ -32,6 +32,7 @@ import (
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"gitea.dev/cli/internal/version"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
+1
View File
@@ -17,6 +17,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/version"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
+9 -9
View File
@@ -14,6 +14,7 @@ import (
"time"
"gitea.dev/cli/internal/clierr"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -158,24 +159,23 @@ func durationAgo(value string) (time.Duration, error) {
return time.ParseDuration(value)
}
// timeRange is a pair of lower and upper time bound flags.
// timeRange is a pair of --since and --until time bound flags.
type timeRange struct {
flags *pflag.FlagSet
names [2]string
values [2]string
}
// register adds the lower and upper bound flags to cmd.
func (r *timeRange) register(cmd *cobra.Command, lower, lowerUsage, upper, upperUsage string) {
r.flags, r.names = cmd.Flags(), [2]string{lower, upper}
r.flags.StringVar(&r.values[0], lower, "", lowerUsage)
r.flags.StringVar(&r.values[1], upper, "", upperUsage)
// register adds the --since and --until flags to cmd.
func (r *timeRange) register(cmd *cobra.Command, sinceUsage, untilUsage string) {
r.flags = cmd.Flags()
r.flags.StringVar(&r.values[0], "since", "", sinceUsage)
r.flags.StringVar(&r.values[1], "until", "", untilUsage)
}
// parse returns the bounds that were set and rejects inverted ranges.
func (r *timeRange) parse(now time.Time) (since, until *time.Time, err error) {
var bounds [2]*time.Time
for i, flag := range r.names {
for i, flag := range [2]string{"since", "until"} {
if !r.flags.Changed(flag) {
continue
}
@@ -184,7 +184,7 @@ func (r *timeRange) parse(now time.Time) (since, until *time.Time, err error) {
}
}
if bounds[0] != nil && bounds[1] != nil && bounds[0].After(*bounds[1]) {
return nil, nil, clierr.Wrap(clierr.Usage, fmt.Errorf("--%s must not be later than --%s", r.names[0], r.names[1]))
return nil, nil, clierr.Wrap(clierr.Usage, errors.New("--since must not be later than --until"))
}
return bounds[0], bounds[1], nil
}
+1 -1
View File
@@ -49,7 +49,7 @@ func TestParseTimeRangeRejectsOnlyInvertedBounds(t *testing.T) {
} {
cmd := &cobra.Command{}
var bounds timeRange
bounds.register(cmd, "since", "", "until", "")
bounds.register(cmd, "", "")
require.NoError(t, cmd.Flags().Parse([]string{"--since=" + tc.since, "--until=" + tc.until}))
_, _, err := bounds.parse(time.Now())
require.Equal(t, tc.wantErr, err != nil, tc.since+".."+tc.until)
+1
View File
@@ -19,6 +19,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+2 -1
View File
@@ -17,6 +17,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
@@ -33,7 +34,7 @@ func TestRunDownloadZipToStdoutKeepsBinaryOutputClean(t *testing.T) {
_, _ = w.Write([]byte{0x50, 0x4b, 0, 0xff})
default:
t.Errorf("unexpected endpoint %s", r.URL.Path)
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -15,6 +15,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -20,6 +20,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/spf13/cobra"
)
+4 -2
View File
@@ -11,6 +11,7 @@ import (
"maps"
"net/http"
"slices"
"strconv"
"strings"
"time"
@@ -21,6 +22,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/spf13/cobra"
)
@@ -299,12 +301,12 @@ func (a *application) writeAuthStatus(cmd *cobra.Command, rows []authStatusRow)
return writeTable(a, cmd, rows, listSpec[authStatusRow]{Row: func(row authStatusRow) []terminal.Cell {
verified, expires := "", terminal.Cell{}
if row.Verified != nil {
verified = fmt.Sprint(*row.Verified)
verified = strconv.FormatBool(*row.Verified)
}
if row.ExpiresAt != nil {
expires.Time = *row.ExpiresAt
}
return []terminal.Cell{{Text: row.Host}, {Text: row.User}, {Text: fmt.Sprint(row.Active)}, {Text: row.Method}, {Text: row.Store}, {Text: fmt.Sprint(row.Available)}, {Text: verified}, expires, {Text: row.Error}}
return []terminal.Cell{{Text: row.Host}, {Text: row.User}, {Text: strconv.FormatBool(row.Active)}, {Text: row.Method}, {Text: row.Store}, {Text: strconv.FormatBool(row.Available)}, {Text: verified}, expires, {Text: row.Error}}
}}, listPage{Number: 1})
}
byHost := map[string][]authStatusRow{}
+1
View File
@@ -31,6 +31,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
)
+4 -3
View File
@@ -6,11 +6,12 @@ package app
import (
"cmp"
"context"
"fmt"
"strconv"
"strings"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
@@ -132,7 +133,7 @@ $ gt branch protection list --json rule,required_approvals,status_check_required
Row: func(rule services.BranchRule) []terminal.Cell {
return []terminal.Cell{
{Text: terminal.SafeLine(rule.Rule), Bold: true},
{Text: fmt.Sprint(rule.RequiredApprovals)},
{Text: strconv.FormatInt(rule.RequiredApprovals, 10)},
{Text: terminal.SafeLine(rulePushers(rule))},
{Text: terminal.SafeLine(ruleChecks(rule))},
{Text: terminal.SafeLine(ruleNotes(rule)), Muted: true},
@@ -165,7 +166,7 @@ $ gt branch protection view 'release/*' --json push_users,push_teams`,
d := a.display()
return writeView(a, cmd, rule, func(rule services.BranchRule) terminal.View {
fields := []terminal.Field{
{Label: "Required approvals", Value: fmt.Sprint(rule.RequiredApprovals)},
{Label: "Required approvals", Value: strconv.FormatInt(rule.RequiredApprovals, 10)},
{Label: "May push", Value: rulePushers(rule)},
{Label: "May merge", Value: ruleMergers(rule)},
{Label: "Status checks", Value: ruleChecks(rule)},
@@ -11,6 +11,7 @@ import (
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -12,6 +12,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+4 -3
View File
@@ -17,6 +17,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"github.com/spf13/cobra"
)
@@ -37,7 +38,7 @@ var browsePages = []struct{ flag, page, usage string }{
func (a *application) browseCommand() *cobra.Command {
var branch, commit string
var print bool
var printURL bool
pages := make([]bool, len(browsePages))
command := &cobra.Command{
Use: "browse [<number> | <path>[:<line>] | <commit-sha>]",
@@ -173,7 +174,7 @@ $ gt browse --no-browser docs/README.md`,
link += "?display=source" + lines // Line anchors exist only in the source view of rendered files such as Markdown.
}
}
if print {
if printURL {
_, err := fmt.Fprintln(cmd.OutOrStdout(), link)
return err
}
@@ -184,7 +185,7 @@ $ gt browse --no-browser docs/README.md`,
flags.StringVarP(&branch, "branch", "b", "", "Open a path, or the root, of this branch")
flags.StringVarP(&commit, "commit", "c", "", "Open a path, or the root, at this commit; without a value, at HEAD of the clone")
flags.Lookup("commit").NoOptDefVal = "HEAD"
flags.BoolVarP(&print, "no-browser", "n", false, "Print the URL instead of opening it")
flags.BoolVarP(&printURL, "no-browser", "n", false, "Print the URL instead of opening it")
for i, page := range browsePages {
flags.BoolVarP(&pages[i], page.flag, page.flag[:1], false, page.usage)
}
+1
View File
@@ -17,6 +17,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/git"
"gitea.dev/cli/internal/git/gittest"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -9,6 +9,7 @@ import (
"strings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -10,6 +10,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/cli/internal/git"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"github.com/spf13/cobra"
)
+1
View File
@@ -18,6 +18,7 @@ import (
"gitea.dev/cli/internal/git/gittest"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -11,6 +11,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+6 -4
View File
@@ -6,6 +6,7 @@ package app
import (
"errors"
"fmt"
"slices"
"strconv"
"strings"
"time"
@@ -13,6 +14,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
@@ -175,9 +177,9 @@ func lastComment(cmd *cobra.Command, t target, n int64) (services.Comment, error
if err != nil {
return services.Comment{}, err
}
for i := len(items) - 1; i >= 0; i-- {
if strings.EqualFold(items[i].Author, t.login()) {
return items[i], nil
for _, item := range slices.Backward(items) {
if strings.EqualFold(item.Author, t.login()) {
return item, nil
}
}
return services.Comment{}, fmt.Errorf("%s has no comments on %s#%d", t.login(), t.Repo, n)
@@ -267,7 +269,7 @@ func (a *application) writeComments(cmd *cobra.Command, t target, n int64, items
var text strings.Builder
for i, comment := range items {
if !d.TTY {
text.WriteString(fmt.Sprintf("id:\t%d\nauthor:\t%s\ncreated_at:\t%s\nurl:\t%s\n--\n", comment.ID, terminal.SafeLine(comment.Author), pipedTime(comment.CreatedAt), terminal.SafeLine(comment.URL)))
fmt.Fprintf(&text, "id:\t%d\nauthor:\t%s\ncreated_at:\t%s\nurl:\t%s\n--\n", comment.ID, terminal.SafeLine(comment.Author), pipedTime(comment.CreatedAt), terminal.SafeLine(comment.URL))
text.WriteString(strings.TrimRight(terminal.SafeText(comment.Body), "\n") + "\n--\n")
continue
}
+1
View File
@@ -13,6 +13,7 @@ import (
"time"
"gitea.dev/cli/internal/settings"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
+1
View File
@@ -21,6 +21,7 @@ import (
"gitea.dev/cli/internal/git/gittest"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/stretchr/testify/require"
+1
View File
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -15,6 +15,7 @@ import (
"gitea.dev/cli/internal/auth"
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/settings"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -11,6 +11,7 @@ import (
"time"
"gitea.dev/cli/internal/clierr"
"github.com/araddon/dateparse"
"github.com/spf13/cobra"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -10,6 +10,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -11,6 +11,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/stretchr/testify/require"
)
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
@@ -100,7 +101,7 @@ search would return %[1]s with any of them.`, nouns), Example: example, RunE: fu
flags.StringVarP(&opts.Author, "author", "A", "", "Filter by author; @me for yourself")
flags.StringSliceVarP(&labels, "label", "l", nil, "Filter by label `names`; a result must have all of them (several require --repo)")
flags.StringSliceVarP(&milestones, "milestone", "m", nil, "Filter by milestone `titles`")
updated.register(command, "since", "Updated since a date, timestamp, or duration ago", "until", "Updated before a date, timestamp, or duration ago")
updated.register(command, "Updated since a date, timestamp, or duration ago", "Updated before a date, timestamp, or duration ago")
flags.BoolVar(&opts.Assigned, "assigned", false, "Assigned to you")
flags.BoolVar(&opts.Authored, "authored", false, "Created by you")
flags.BoolVar(&opts.Mentioned, "mentioned", false, "Mentioning you")
+1
View File
@@ -11,6 +11,7 @@ import (
"time"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
@@ -26,7 +27,7 @@ func TestDiscussionViews(t *testing.T) {
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/repos/alice/project/issues/3":
_, _ = w.Write([]byte(`{"number":3,"title":"Crash\u001b[2J","body":"Steps:\r\n\u001b]52;c;aGk=\u0007run‮\r","html_url":"https://example.org/i/3","state":"open","user":{"login":"bob"},"created_at":"2026-01-01T00:00:00Z","labels":[{"name":"bug","color":"ff0000"}],"assignees":[{"login":"alice"}],"comments":1}`))
_, _ = w.Write([]byte(`{"number":3,"title":"Crash\u001b[2J","body":"Steps:\r\n\u001b]52;c;aGk=\u0007run` + "\u202e" + `\r","html_url":"https://example.org/i/3","state":"open","user":{"login":"bob"},"created_at":"2026-01-01T00:00:00Z","labels":[{"name":"bug","color":"ff0000"}],"assignees":[{"login":"alice"}],"comments":1}`))
case "/api/v1/repos/alice/project/issues/3/dependencies", "/api/v1/repos/alice/project/issues/3/blocks":
_, _ = w.Write([]byte(`[]`))
case "/api/v1/repos/alice/project/pulls/4/reviews":
+1
View File
@@ -20,6 +20,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/spf13/cobra"
)
+1
View File
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/auth"
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/settings"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -19,6 +19,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+2 -1
View File
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
@@ -50,7 +51,7 @@ func TestDownloadsPublishOnlyCompleteFiles(t *testing.T) {
output := filepath.Join(directory, "logs.zip")
require.ErrorIs(t, publish(cmd, output, false, false, copyBody(failingDownload{})), io.ErrUnexpectedEOF)
_, err := os.Stat(output)
require.True(t, errors.Is(err, os.ErrNotExist))
require.ErrorIs(t, err, os.ErrNotExist)
entries, err := os.ReadDir(directory)
require.NoError(t, err)
require.Empty(t, entries)
+1
View File
@@ -9,6 +9,7 @@ import (
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/spf13/cobra"
)
+1
View File
@@ -10,6 +10,7 @@ import (
"testing"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"time"
"gitea.dev/cli/internal/auth"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/require"
)
+8 -4
View File
@@ -8,15 +8,19 @@ import (
"testing"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
func TestErrorFormatEnvironment(t *testing.T) {
for value, want := range map[string]bool{"": false, "text": false, "json": true, " json ": true} {
for _, test := range []struct {
value string
want bool
}{{"", false}, {"text", false}, {"json", true}, {" json ", true}} {
deps, _, _ := testDeps(t)
deps.Getenv = envFunc(map[string]string{errorFormatEnv: value})
require.Equal(t, want, JSONErrors(deps), value)
require.NoError(t, Execute(context.Background(), deps, []string{"alias", "list"}), value)
deps.Getenv = envFunc(map[string]string{errorFormatEnv: test.value})
require.Equal(t, test.want, JSONErrors(deps), test.value)
require.NoError(t, Execute(context.Background(), deps, []string{"alias", "list"}), test.value)
}
deps, _, _ := testDeps(t)
deps.Getenv = envFunc(map[string]string{errorFormatEnv: "yaml"})
+5 -1
View File
@@ -18,6 +18,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/require"
)
@@ -131,7 +132,10 @@ func TestExplainWordsCredentialAndConnectionFailures(t *testing.T) {
// An unreachable proxy is named instead of the instance behind it.
proxy, err := url.Parse(closed.URL)
require.NoError(t, err)
_, err = (&http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxy)}}).Get("http://example.test/api/v1/user")
response, err := (&http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxy)}}).Get("http://example.test/api/v1/user")
if response != nil {
defer response.Body.Close()
}
err = transport.RequestError(context.Background(), "API request failed", err)
require.EqualError(t, Explain(context.Background(), deps, err), "cannot reach the proxy "+proxy.Host+" (connection refused); check HTTPS_PROXY and HTTP_PROXY")
+1
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/cli/internal/extensions"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
+1
View File
@@ -13,6 +13,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/extensions"
"github.com/spf13/cobra"
)
+1
View File
@@ -26,6 +26,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/version"
"github.com/spf13/cobra"
)
+1
View File
@@ -21,6 +21,7 @@ import (
"gitea.dev/cli/internal/extensions"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -16,6 +16,7 @@ import (
"gitea.dev/cli/internal/extensions"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+24 -15
View File
@@ -10,6 +10,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
@@ -30,6 +31,7 @@ import (
"gitea.dev/cli/internal/git/gittest"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
@@ -153,6 +155,13 @@ func extensionDeps(t *testing.T, repo *fakeExtensionRepo, env map[string]string)
return deps, runs, server
}
func extensionBuffer(t *testing.T, writer io.Writer) *bytes.Buffer {
t.Helper()
buffer, ok := writer.(*bytes.Buffer)
require.True(t, ok)
return buffer
}
func installedExtension(t *testing.T, deps Dependencies, name string) extensions.Extension {
t.Helper()
extension, err := (extensions.Store{Dir: filepath.Join(deps.DataDir, "extensions")}).Lookup(name)
@@ -199,9 +208,9 @@ func TestExtensionInstallRunAndRemove(t *testing.T) {
runs.code = 0
require.NoError(t, Execute(context.Background(), deps, []string{"--no-input", "--yes", "hello"}), "every command accepts --no-input and --yes")
deps.Streams.Out.(interface{ Reset() }).Reset()
extensionBuffer(t, deps.Streams.Out).Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "list", "--json", "name,tag,credentials,shadowed"}))
assert.JSONEq(t, `[{"name":"hello","tag":"v1.0.0","credentials":false,"shadowed":false}]`, deps.Streams.Out.(fmt.Stringer).String())
assert.JSONEq(t, `[{"name":"hello","tag":"v1.0.0","credentials":false,"shadowed":false}]`, extensionBuffer(t, deps.Streams.Out).String())
require.NoError(t, os.WriteFile(extension.Path(), []byte("replaced"), 0o755))
err = Execute(context.Background(), deps, []string{"hello"})
@@ -241,7 +250,7 @@ func TestExtensionInstallWithoutDigestAsks(t *testing.T) {
require.ErrorIs(t, err, terminal.ErrCanceled)
assert.Equal(t, []string{"Install extension hello, which gt cannot verify?"}, prompter.confirmations)
assert.Equal(t, []bool{false}, prompter.defaults)
assert.Contains(t, deps.Streams.ErrOut.(fmt.Stringer).String(), "(not published; recorded now and checked before each run)")
assert.Contains(t, extensionBuffer(t, deps.Streams.ErrOut).String(), "(not published; recorded now and checked before each run)")
_, err = (extensions.Store{Dir: filepath.Join(deps.DataDir, "extensions")}).Lookup("hello")
require.ErrorIs(t, err, extensions.ErrNotInstalled)
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "install", "alice/gt-hello", "--yes"}))
@@ -293,9 +302,9 @@ func TestExtensionsCanBeTurnedOff(t *testing.T) {
deps.Getenv = serverEnv(server.URL, map[string]string{"GITEA_CLI_NO_EXTENSIONS": "1"})
require.ErrorContains(t, Execute(context.Background(), deps, []string{"hello"}), "disabled by GITEA_CLI_NO_EXTENSIONS")
deps.Streams.Out.(interface{ Reset() }).Reset()
extensionBuffer(t, deps.Streams.Out).Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"help"}))
assert.NotContains(t, deps.Streams.Out.(fmt.Stringer).String(), "EXTENSION COMMANDS", "help offers no extension that cannot run")
assert.NotContains(t, extensionBuffer(t, deps.Streams.Out).String(), "EXTENSION COMMANDS", "help offers no extension that cannot run")
deps.Getenv = serverEnv(server.URL, nil)
policy := filepath.Join(t.TempDir(), "policy.yml")
@@ -373,9 +382,9 @@ func TestExtensionUpgradeRefusesChangedSources(t *testing.T) {
require.EqualError(t, err, "confirmation required to upgrade extension hello; rerun with --yes")
assert.Equal(t, downloads, repo.downloads, "nothing is downloaded that cannot be installed")
deps.Streams.Out.(interface{ Reset() }).Reset()
extensionBuffer(t, deps.Streams.Out).Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "upgrade", "--all", "--dry-run"}))
assert.Equal(t, "hello\tv1.0.0\tv2.0.0\n", deps.Streams.Out.(fmt.Stringer).String())
assert.Equal(t, "hello\tv1.0.0\tv2.0.0\n", extensionBuffer(t, deps.Streams.Out).String())
require.Equal(t, "v1.0.0", installedExtension(t, deps, "hello").Tag)
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "upgrade", "--all", "--yes"}))
upgraded := installedExtension(t, deps, "hello")
@@ -386,7 +395,7 @@ func TestExtensionUpgradeRefusesChangedSources(t *testing.T) {
repo.tag = "v3.0.0"
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "upgrade", "hello", "--yes"}))
assert.Equal(t, "v2.0.0", installedExtension(t, deps, "hello").Tag, "a pinned extension stays")
assert.Contains(t, deps.Streams.ErrOut.(fmt.Stringer).String(), "reinstall it with gt extension install --force "+server.URL+"/alice/gt-hello to change that")
assert.Contains(t, extensionBuffer(t, deps.Streams.ErrOut).String(), "reinstall it with gt extension install --force "+server.URL+"/alice/gt-hello to change that")
}
func TestExtensionMetadataIsChecked(t *testing.T) {
@@ -398,10 +407,10 @@ func TestExtensionMetadataIsChecked(t *testing.T) {
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "install", "alice/gt-hello", "--yes"}))
assert.Equal(t, "Say hello", installedExtension(t, deps, "hello").Metadata.Description)
assert.False(t, installedExtension(t, deps, "hello").Credentials, "gt cannot ask")
assert.Contains(t, deps.Streams.ErrOut.(fmt.Stringer).String(), "Extension hello asks for your Gitea token; allow it with gt extension install --force --allow-credentials "+server.URL+"/alice/gt-hello")
deps.Streams.Out.(interface{ Reset() }).Reset()
assert.Contains(t, extensionBuffer(t, deps.Streams.ErrOut).String(), "Extension hello asks for your Gitea token; allow it with gt extension install --force --allow-credentials "+server.URL+"/alice/gt-hello")
extensionBuffer(t, deps.Streams.Out).Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"help"}))
assert.Contains(t, deps.Streams.Out.(fmt.Stringer).String(), "EXTENSION COMMANDS\n hello:")
assert.Contains(t, extensionBuffer(t, deps.Streams.Out).String(), "EXTENSION COMMANDS\n hello:")
}
func TestGitHubExtensionsAreReadAnonymously(t *testing.T) {
@@ -492,7 +501,7 @@ func TestLocalExtensionRunsInPlace(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(dir, "gt-extension.yml"), []byte("credentials: true\n"), 0o644))
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "install", dir, "--force"}))
assert.False(t, installedExtension(t, deps, "dev").Credentials, "gt cannot ask")
assert.Contains(t, deps.Streams.ErrOut.(fmt.Stringer).String(), "Extension dev asks for your Gitea token; allow it with gt extension install --force --allow-credentials "+dir)
assert.Contains(t, extensionBuffer(t, deps.Streams.ErrOut).String(), "Extension dev asks for your Gitea token; allow it with gt extension install --force --allow-credentials "+dir)
prompt := &scriptedPrompter{accept: true}
deps.Prompter = prompt
deps.Streams.InTTY, deps.Streams.ErrTTY = true, true
@@ -645,7 +654,7 @@ func TestChangedExtensionIsNotAskedToComplete(t *testing.T) {
repo.metadata = "completion: cobra\n"
deps, runs, _ := extensionDeps(t, repo, nil)
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "install", "alice/gt-hello", "--yes"}))
out := deps.Streams.Out.(*bytes.Buffer)
out := extensionBuffer(t, deps.Streams.Out)
complete(t, deps, out, "hello", "")
require.Len(t, runs.commands, 1)
require.NoError(t, os.WriteFile(installedExtension(t, deps, "hello").Path(), []byte("replaced"), 0o755))
@@ -810,7 +819,7 @@ func TestExtensionGetsNoTokenOfAnotherInstance(t *testing.T) {
// Without its instance, the token cannot be passed, which gt explains as for its own commands.
deps.Getenv = envFunc(map[string]string{"GITEA_TOKEN": "unbound"})
require.NoError(t, Execute(context.Background(), deps, []string{"hello"}))
assert.Contains(t, deps.Streams.ErrOut.(fmt.Stringer).String(), "Could not pass your credentials to extension hello: GITEA_TOKEN requires GITEA_CLI_HOST or GITEA_INSTANCE_URL naming its instance")
assert.Contains(t, extensionBuffer(t, deps.Streams.ErrOut).String(), "Could not pass your credentials to extension hello: GITEA_TOKEN requires GITEA_CLI_HOST or GITEA_INSTANCE_URL naming its instance")
}
func TestExtensionGetsARefreshedOAuthToken(t *testing.T) {
@@ -911,7 +920,7 @@ func TestExtensionCreateReleaseWorkflowPublishesFromAFreshRunner(t *testing.T) {
require.True(t, ok, step.Run)
var args []string
shell := strings.NewReplacer(`"$GITHUB_REF_NAME"`, "v1.0.0", `"$GITHUB_SERVER_URL"`, server.URL, `"$GITHUB_REPOSITORY"`, "alice/gt-hello")
for _, arg := range strings.Fields(shell.Replace(command)) {
for arg := range strings.FieldsSeq(shell.Replace(command)) {
if arg != "dist/*" && arg != `\` {
args = append(args, arg)
}
+2 -4
View File
@@ -8,6 +8,7 @@ import (
"context"
"fmt"
"slices"
"strings"
"gitea.dev/cli/internal/clierr"
)
@@ -18,10 +19,7 @@ import (
func ExecuteGH(ctx context.Context, deps Dependencies, args []string) error {
supported := len(args) > 0 && args[0] == "api" || len(args) > 1 && (args[0] == "repo" && args[1] == "view" || args[0] == "auth" && args[1] == "token")
if !supported {
command := "gh"
for _, arg := range args[:min(len(args), 2)] {
command += " " + arg
}
command := strings.Join(append([]string{"gh"}, args[:min(len(args), 2)]...), " ")
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s is not supported by the gh shim of gt; it answers gh api, gh repo view and gh auth token", command))
}
if args[0] == "repo" {
+1
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/cli/internal/git"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"github.com/spf13/cobra"
)
@@ -10,6 +10,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
@@ -18,6 +19,7 @@ import (
"gitea.dev/cli/internal/git"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"github.com/stretchr/testify/require"
)
@@ -82,7 +84,7 @@ func TestGiteaGitCredentialHelperClonesPrivateRepository(t *testing.T) {
var pull services.Pull
require.NoError(t, json.Unmarshal(out.Bytes(), &pull))
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", fmt.Sprint(pull.Number), "-R", repo.FullName, "--cwd", gtClone, "--no-input", "--json"}))
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName, "--cwd", gtClone, "--no-input", "--json"}))
var checkout git.CheckoutResult
require.NoError(t, json.Unmarshal(out.Bytes(), &checkout))
require.Equal(t, pull.HeadSHA, checkout.Commit)
@@ -90,7 +92,7 @@ func TestGiteaGitCredentialHelperClonesPrivateRepository(t *testing.T) {
branchesBefore, err := runner.Output(context.Background(), gtClone, false, "for-each-ref", "--format=%(refname):%(objectname)", "refs/heads/")
require.NoError(t, err)
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", fmt.Sprint(pull.Number), "-R", repo.FullName, "--cwd", gtClone, "--detach", "--no-input", "--json"}))
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName, "--cwd", gtClone, "--detach", "--no-input", "--json"}))
require.NoError(t, json.Unmarshal(out.Bytes(), &checkout))
require.True(t, checkout.Detached)
require.Empty(t, checkout.Branch)
@@ -99,7 +101,7 @@ func TestGiteaGitCredentialHelperClonesPrivateRepository(t *testing.T) {
require.NoError(t, err)
require.Equal(t, branchesBefore, branchesAfter)
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", fmt.Sprint(pull.Number), "-R", repo.FullName, "--cwd", gtClone, "--no-input", "--json"}))
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName, "--cwd", gtClone, "--no-input", "--json"}))
require.NoError(t, json.Unmarshal(out.Bytes(), &checkout))
require.False(t, checkout.Detached)
require.Equal(t, "feature", checkout.Branch)
@@ -115,10 +117,10 @@ func TestGiteaGitCredentialHelperClonesPrivateRepository(t *testing.T) {
deps.Streams.In = strings.NewReader(`{"branch":"feature","content":"bmV4dAo=","message":"Disposable fast-forward fixture"}`)
require.NoError(t, Execute(context.Background(), deps, []string{"api", "repos/" + repo.FullName + "/contents/next.txt", "--input", "-"}))
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "view", fmt.Sprint(pull.Number), "-R", repo.FullName, "--json"}))
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "view", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName, "--json"}))
require.NoError(t, json.Unmarshal(out.Bytes(), &pull))
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", fmt.Sprint(pull.Number), "-R", repo.FullName, "--cwd", gtClone, "--update", "--no-input", "--json"}))
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", strconv.FormatInt(pull.Number, 10), "-R", repo.FullName, "--cwd", gtClone, "--update", "--no-input", "--json"}))
require.NoError(t, json.Unmarshal(out.Bytes(), &checkout))
require.Equal(t, pull.HeadSHA, checkout.Commit)
localHead, err := runner.Output(context.Background(), gtClone, false, "rev-parse", "HEAD")
@@ -159,9 +161,9 @@ func TestGiteaGitCredentialHelperClonesPrivateRepository(t *testing.T) {
remote, err := runner.Output(context.Background(), destination, false, "remote", "get-url", "origin")
require.NoError(t, err)
require.Equal(t, repo.CloneURL, remote)
require.False(t, strings.Contains(remote, gitea.token), "remote contains credentials")
require.NotContains(t, remote, gitea.token, "remote contains credentials")
helper, err := runner.Output(context.Background(), "", false, "config", "--global", "--get-all", "credential."+gitea.url+".helper")
require.NoError(t, err)
require.Len(t, strings.Split(helper, "\n"), 1)
require.False(t, strings.Contains(helper, gitea.token), "helper command contains credentials")
require.NotContains(t, helper, gitea.token, "helper command contains credentials")
}
+1
View File
@@ -15,6 +15,7 @@ import (
"gitea.dev/cli/internal/git"
"gitea.dev/cli/internal/git/gittest"
"gitea.dev/cli/internal/settings"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -11,6 +11,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/extensions"
"gitea.dev/cli/internal/services"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
+1
View File
@@ -11,6 +11,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/extensions"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+3 -2
View File
@@ -14,9 +14,10 @@ import (
"testing"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/openpgp" //nolint:staticcheck // frozen but enough to make a throwaway key and sign with it, with no new dependency
"golang.org/x/crypto/openpgp/armor" //nolint:staticcheck // see above
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
)
// integrationGPGKey makes a key with one email address and returns it, with its armored public key.
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -259,7 +260,7 @@ func flagUsages(flags []*pflag.Flag) string {
func wrap(text string, width int) string {
var lines []string
line := ""
for _, word := range strings.Fields(text) {
for word := range strings.FieldsSeq(text) {
if line != "" && len(line)+1+len(word) > width {
lines, line = append(lines, line), ""
}
+1
View File
@@ -27,6 +27,7 @@ import (
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -10,6 +10,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -18,6 +18,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
)
+7 -5
View File
@@ -17,6 +17,7 @@ import (
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"testing"
@@ -24,6 +25,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/kballard/go-shellquote"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
@@ -123,9 +125,9 @@ func verifyEditorSubmission(t *testing.T, deps Dependencies, repository, number
require.Equal(t, "Editor integration body", result.Body)
require.Positive(t, result.ID)
defer func() {
args := []string{"issue", "comment", "delete", fmt.Sprint(result.ID)}
args := []string{"issue", "comment", "delete", strconv.FormatInt(result.ID, 10)}
if review {
args = []string{"pr", "review", "delete", number, fmt.Sprint(result.ID)}
args = []string{"pr", "review", "delete", number, strconv.FormatInt(result.ID, 10)}
}
if err := Execute(context.Background(), deps, append(args, "--repo", repository, "--yes")); err != nil {
t.Errorf("editor submission cleanup: %v", err)
@@ -190,7 +192,7 @@ func verifyIssueAttachmentLifecycle(t *testing.T, deps Dependencies, group, repo
require.Positive(t, item.ID)
require.Equal(t, "attachment.txt", item.Name)
require.EqualValues(t, 30, item.Size)
id := fmt.Sprint(item.ID)
id := strconv.FormatInt(item.ID, 10)
downloaded := filepath.Join(t.TempDir(), "downloaded.txt")
require.NoError(t, Execute(context.Background(), deps, []string{group, "attachment", "download", number, id, "--repo", repository, "--no-input", "--output", downloaded}))
content, err := os.ReadFile(downloaded)
@@ -241,7 +243,7 @@ func verifySSHCloneAndCheckout(t *testing.T, deps Dependencies, repo services.Re
var registered services.SSHKey
require.NoError(t, json.Unmarshal(out.Bytes(), &registered))
t.Cleanup(func() {
if err := Execute(context.Background(), deps, []string{"ssh-key", "delete", fmt.Sprint(registered.ID), "--yes"}); err != nil {
if err := Execute(context.Background(), deps, []string{"ssh-key", "delete", strconv.FormatInt(registered.ID, 10), "--yes"}); err != nil {
t.Errorf("SSH key cleanup: %v", err)
}
})
@@ -281,7 +283,7 @@ func verifySSHCloneAndCheckout(t *testing.T, deps Dependencies, repo services.Re
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "clone", repo.FullName, clone, "--no-input", "--json=id"}))
require.JSONEq(t, fmt.Sprintf(`{"id":%d}`, repo.ID), out.String())
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", fmt.Sprint(pull.Number), "--repo", repo.FullName, "--cwd", clone, "--detach", "--no-input", "--json"}))
require.NoError(t, Execute(context.Background(), deps, []string{"pr", "checkout", strconv.FormatInt(pull.Number, 10), "--repo", repo.FullName, "--cwd", clone, "--detach", "--no-input", "--json"}))
var checkout git.CheckoutResult
require.NoError(t, json.Unmarshal(out.Bytes(), &checkout))
require.Equal(t, pull.HeadSHA, checkout.Commit)
@@ -14,6 +14,7 @@ import (
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -20,6 +20,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/transport"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
)
+1
View File
@@ -11,6 +11,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -17,6 +17,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+1
View File
@@ -14,6 +14,7 @@ import (
"time"
"gitea.dev/cli/internal/clierr"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -15,6 +15,7 @@ import (
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/settings"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
+6 -4
View File
@@ -18,8 +18,8 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"gitea.dev/cli/internal/terminal"
"github.com/stretchr/testify/require"
)
@@ -77,7 +77,7 @@ func TestIssueEditImplicitInteractiveForm(t *testing.T) {
require.Equal(t, "Edited", patchPayload["title"])
require.Equal(t, "New body", patchPayload["body"])
require.Equal(t, []any{"bob"}, patchPayload["assignees"])
require.Equal(t, float64(4), patchPayload["milestone"])
require.InDelta(t, float64(4), patchPayload["milestone"], 0)
require.Equal(t, "2028-02-01T23:59:59Z", patchPayload["due_date"], "a date is the end of that day, as with --deadline")
require.Equal(t, []any{float64(3)}, labelPayload["labels"])
require.JSONEq(t, `{"number":5,"title":"Edited"}`, out.String())
@@ -170,7 +170,7 @@ func TestIssueEditFormOffersMetadataWithoutPushAndNamesWhatGiteaLeftOut(t *testi
require.Equal(t, clierr.Failure, clierr.ExitCode(err))
require.Len(t, patches, 1)
require.Equal(t, []any{"bob"}, patches[0]["assignees"])
require.Equal(t, float64(4), patches[0]["milestone"])
require.InDelta(t, float64(4), patches[0]["milestone"], 0)
require.JSONEq(t, `{"number":5,"title":"Edited"}`, out.String(), "the edited issue is still reported")
}
@@ -306,7 +306,9 @@ func TestIssueEditMergesAssigneesWithOneRead(t *testing.T) {
}
var body map[string]any
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
patched = body["assignees"].([]any)
var ok bool
patched, ok = body["assignees"].([]any)
require.True(t, ok)
_, _ = w.Write([]byte(`{"number":7,"assignees":[{"login":"alice"},{"login":"carol"}]}`))
}))
defer server.Close()
+1
View File
@@ -15,6 +15,7 @@ import (
"time"
"gitea.dev/cli/internal/services"
"github.com/stretchr/testify/require"
)
+1
View File
@@ -10,6 +10,7 @@ import (
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/services"
"github.com/spf13/cobra"
)

Some files were not shown because too many files have changed in this diff Show More