fix: correct shared CLI behavior, help and generated docs

Extensions, aliases and completion behave like built-in commands, a word after --json is read as a
field, paging keeps the server's positions, usage errors read "X requires Y", and man pages match --help.
This commit is contained in:
bircni
2026-10-29 11:07:53 +00:00
parent 0d6739d5f4
commit e1ec39ddfb
35 changed files with 691 additions and 198 deletions
+2 -3
View File
@@ -1,4 +1,5 @@
/gt
/gt.exe
/gitea-vet
/gitea-vet.exe
@@ -11,8 +12,6 @@ vendor/
coverage.out
dist/
# Generated by `make docs`; shipped in the release docs archive, never committed
docs/generated/
@@ -25,4 +24,4 @@ gitea-cli-*-docs.tar.xz.sha256
result
result-*
.DS_Store
.DS_Store
-1
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: MIT
//go:build vendor
// +build vendor
package main
+3 -1
View File
@@ -212,6 +212,8 @@ func TestRunDropsTerminalControlsFromErrors(t *testing.T) {
_, _ = w.Write([]byte(`{"full_name":"alice/project","has_issues":true}`))
case "/api/v1/repos/alice/project/actions/workflows":
_, _ = w.Write([]byte(`{"workflows":[{"id":"ci.yml","name":"CI\u001b]0;PWNED\u0007","path":".gitea/workflows/ci.yml","state":"active"}]}`))
case "/api/v1/repos/alice/project/contents/.gitea/workflows":
_, _ = w.Write([]byte(`[{"name":"ci.yml","path":".gitea/workflows/ci.yml","type":"file"}]`))
case "/api/v1/repos/alice/project/contents/.gitea/workflows/ci.yml":
_, _ = w.Write([]byte(`{"type":"file","encoding":"base64","content":"` + definition + `"}`))
default:
@@ -229,7 +231,7 @@ func TestRunDropsTerminalControlsFromErrors(t *testing.T) {
},
}
require.Equal(t, 2, run(context.Background(), deps, []string{"workflow", "run", "ci.yml", "--ref", "main", "-R", "alice/project", "--no-input"}, app.Execute))
require.Contains(t, stderr.String(), "missing required input target for CI")
require.Contains(t, stderr.String(), "(ci.yml) requires input target; pass -f target=<value>")
require.NotContains(t, stderr.String(), "\x1b")
require.NotContains(t, stderr.String(), "\x07")
}
+22 -6
View File
@@ -84,6 +84,10 @@ type options struct {
debug bool
// editor is the command's --editor, which needs a configured editor before any request.
editor bool
// repoArgument is set when repo holds a command's repository argument rather than --repo.
repoArgument bool
// ignoresRemote is set by commands whose repository never comes from --remote.
ignoresRemote bool
}
type application struct {
@@ -215,9 +219,12 @@ func newRoot(deps Dependencies) (*cobra.Command, *application) {
return clierr.Wrap(clierr.Usage, errors.New("--user cannot be empty"))
}
if cmd.Flags().Changed("sudo") {
if a.options.sudo == "" || strings.IndexFunc(a.options.sudo, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 {
if strings.TrimSpace(a.options.sudo) == "" {
return clierr.Wrap(clierr.Usage, errors.New("--sudo requires a username"))
}
if strings.IndexFunc(a.options.sudo, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 {
return clierr.Wrap(clierr.Usage, fmt.Errorf("invalid --sudo username %q", a.options.sudo))
}
for c := cmd; c.HasParent(); c = c.Parent() {
if c.Name() == "auth" && !c.Parent().HasParent() {
return clierr.Wrap(clierr.Usage, errors.New("--sudo cannot be combined with auth commands"))
@@ -342,7 +349,7 @@ func (a *application) checkOutputFlags(cmd *cobra.Command) error {
switch {
case cmd.Flags().Changed("json"):
if a.options.json == "" {
return clierr.Wrap(clierr.Usage, errors.New("--json= needs field names; use --json alone for every field"))
return clierr.Wrap(clierr.Usage, errors.New("--json= requires field names; use --json alone for every field"))
}
selected = "--json"
case a.options.jq != "" && cmd.Annotations["gt.rawjson"] == "":
@@ -494,9 +501,9 @@ func Execute(ctx context.Context, deps Dependencies, args []string) error {
var jsonFieldList = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]*(,[A-Za-z][A-Za-z0-9_]*)*$`)
// joinJSONFields accepts `--json number,title` like `--json=number,title`. The word stays a positional
// argument only when the command neither outputs any of those fields, nor one they resemble, nor
// rejects the argument, so a misspelled field lists the available fields. Unknown commands, such as
// unexpanded aliases, are joined.
// argument only when it is the only one and the command neither outputs any of those fields, nor one
// they resemble, nor rejects the argument, so a misspelled field lists the available fields rather
// than naming one more tag or label to change. Unknown commands, such as unexpanded aliases, are joined.
func joinJSONFields(root *cobra.Command, args []string) []string {
for i := 0; i < len(args); i++ {
if args[i] == "--" {
@@ -510,7 +517,7 @@ func joinJSONFields(root *cobra.Command, args []string) []string {
continue
}
cmd, _, err := root.Find(slices.Concat(args[:i+1], args[i+2:]))
if fields := commandOutputFields(cmd); err == nil && terminal.ValidateOutput(args[i+1], "", fields) != nil && !namesField(args[i+1], fields) && !resemblesField(args[i+1], fields) && acceptsArgs(args) {
if fields := commandOutputFields(cmd); err == nil && terminal.ValidateOutput(args[i+1], "", fields) != nil && !namesField(args[i+1], fields) && !resemblesField(args[i+1], fields) && acceptsArgs(args) && len(positionalArgs(slices.Concat(args[:i+1], args[i+2:]))) == 0 {
continue
}
args = slices.Concat(args[:i], []string{"--json=" + args[i+1]}, args[i+2:])
@@ -540,6 +547,15 @@ func acceptsArgs(args []string) bool {
return err == nil && cmd.ParseFlags(rest) == nil && cmd.ValidateArgs(cmd.Flags().Args()) == nil
}
// positionalArgs returns the positional arguments of the command that args select, parsed like acceptsArgs.
func positionalArgs(args []string) []string {
cmd, rest, err := NewRoot(Dependencies{}).Find(args)
if err != nil || cmd.ParseFlags(rest) != nil {
return nil
}
return cmd.Flags().Args()
}
func (a *application) policy(snapshot settings.Snapshot) terminal.Policy {
return terminal.Policy{Enabled: snapshot.Preferences.Prompt == "enabled", NoInput: a.options.noInput, Machine: a.options.json != "", Interactive: a.options.interactive}
}
+9 -2
View File
@@ -126,6 +126,11 @@ func TestJoinJSONFields(t *testing.T) {
// command takes an argument.
{[]string{"issue", "view", "--json", "number,titel"}, []string{"issue", "view", "--json=number,titel"}},
{[]string{"search", "repo", "--json", "name,urll"}, []string{"search", "repo", "--json=name,urll"}},
// Next to another argument, the word is a misspelled field rather than one more tag to change.
{[]string{"release", "publish", "v11", "--json", "tag_name"}, []string{"release", "publish", "v11", "--json=tag_name"}},
{[]string{"release", "view", "--json", "tag_name", "v3"}, []string{"release", "view", "--json=tag_name", "v3"}},
{[]string{"search", "repo", "foo", "--json", "bar"}, []string{"search", "repo", "foo", "--json=bar"}},
{[]string{"release", "view", "--json", "v1"}, []string{"release", "view", "--json", "v1"}},
} {
deps, _, _ := testDeps(t)
require.Equal(t, tc.want, joinJSONFields(NewRoot(deps), tc.args), tc.args)
@@ -198,12 +203,13 @@ func TestSudoSendsHeaderAfterIdentityCheck(t *testing.T) {
require.EqualError(t, err, "repository alice/project not found")
requireUsageBeforeRequests(t, "--sudo cannot be combined with auth commands", "auth", "status", "--sudo", "bob")
requireUsageBeforeRequests(t, "--sudo requires a username", "repo", "view", "--sudo", "")
requireUsageBeforeRequests(t, `invalid --sudo username "a b"`, "repo", "view", "--sudo", "a b")
}
func TestJSONFieldErrorsListAvailableFields(t *testing.T) {
requireUsageBeforeRequests(t, "unknown JSON field \"titel\"\navailable fields: assignees, author, body", "issue", "list", "--json", "number,titel")
requireUsageBeforeRequests(t, "unknown JSON field \"workflw\"\navailable fields: actor, attempt, branch", "run", "list", "--json", "workflw")
requireUsageBeforeRequests(t, "--json= needs field names; use --json alone for every field", "pr", "list", "--json=")
requireUsageBeforeRequests(t, "--json= requires field names; use --json alone for every field", "pr", "list", "--json=")
requireUsageBeforeRequests(t, "version prints text; --jq is not supported", "version", "--jq", ".")
}
@@ -324,7 +330,8 @@ func TestCommandHelpShowsRelevantFlagsOnly(t *testing.T) {
require.NotContains(t, out.String(), "Without an argument")
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"repo", "fork", "--help"}))
require.Equal(t, 1, strings.Count(out.String(), "\n --remote "), "a local --remote hides the global one")
require.Contains(t, out.String(), "\n --add-remote ")
require.Contains(t, out.String(), "\n --remote remote ")
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"issue", "--help"}))
require.Contains(t, out.String(), "\nUSAGE\n gt issue <command> [flags]\n\nAVAILABLE COMMANDS\n attachment: ")
+19
View File
@@ -176,6 +176,25 @@ func (r *timeRange) parse(now time.Time) (since, until *time.Time, err error) {
return bounds[0], bounds[1], nil
}
// renameFlag adds old as a hidden alias of the string flag name, for scripts written before the rename.
func renameFlag(cmd *cobra.Command, old, name string) {
cmd.Flags().String(old, "", "Deprecated: use --"+name)
_ = cmd.Flags().MarkHidden(old)
}
// renamedFlag moves a value given under the old name of a flag renamed by renameFlag to its new name.
func (a *application) renamedFlag(cmd *cobra.Command, old, name string) error {
flags := cmd.Flags()
if !flags.Changed(old) {
return nil
}
if flags.Changed(name) {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--%s cannot be combined with --%s", name, old))
}
a.warn(cmd, "--%s is deprecated; use --%s", old, name)
return flags.Set(name, flags.Lookup(old).Value.String())
}
// openRegularFiles opens upload sources, rejecting anything but regular files.
// Callers close the returned files even on error.
func openRegularFiles(paths []string) ([]*os.File, error) {
+36 -28
View File
@@ -485,26 +485,24 @@ func (a *application) completeRuns() cobra.CompletionFunc {
// completeSecrets completes Actions secret names in the selected scope.
func (a *application) completeSecrets(scope func() services.ActionScope) cobra.CompletionFunc {
return a.apiCompletion(false, func(ctx context.Context, t target, _ string) ([]cobra.Completion, error) {
selected := actionScope(scope, t)
if selected.Repository == "" && selected.Organization == "" && !selected.Account {
return nil, nil
}
items, err := services.ActionSecrets{Client: t.client, Scope: selected}.ListPage(ctx, completionLimit, 1)
list := func(ctx context.Context, t target, _ string) ([]cobra.Completion, error) {
items, err := services.ActionSecrets{Client: t.client, Scope: actionScope(scope, t)}.ListPage(ctx, completionLimit, 1)
return describe(items.Items, func(item services.ActionSecret) (string, string) { return item.Name, item.Description }), err
})
}
return func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
return a.apiCompletion(inRepository(scope()), list)(cmd, args, toComplete)
}
}
// completeVariables completes Actions variable names in the selected scope.
func (a *application) completeVariables(scope func() services.ActionScope) cobra.CompletionFunc {
return a.apiCompletion(false, func(ctx context.Context, t target, _ string) ([]cobra.Completion, error) {
selected := actionScope(scope, t)
if selected.Repository == "" && selected.Organization == "" && !selected.Account {
return nil, nil
}
items, err := services.ActionVariables{Client: t.client, Scope: selected}.ListPage(ctx, completionLimit, 1)
list := func(ctx context.Context, t target, _ string) ([]cobra.Completion, error) {
items, err := services.ActionVariables{Client: t.client, Scope: actionScope(scope, t)}.ListPage(ctx, completionLimit, 1)
return describe(items.Items, func(item services.ActionVariable) (string, string) { return item.Name, item.Description }), err
})
}
return func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
return a.apiCompletion(inRepository(scope()), list)(cmd, args, toComplete)
}
}
// actionScope applies the target's repository to a scope without organization or account.
@@ -596,23 +594,38 @@ func pathArgs(n int, variadic bool, path, complete cobra.CompletionFunc) cobra.C
}
}
// completionInstallHelp explains how to load the bash script with macOS's bash 3.2, which cannot
// source <(gt completion bash); cobra's help covers the other shells.
// completionInstallHelp replaces cobra's help for the completion scripts, whose Markdown headings
// and tabs do not read like gt's; bash 3.2, macOS's default, cannot source <(gt completion bash).
func completionInstallHelp(root *cobra.Command) {
completion, _, err := root.Find([]string{"completion"})
if err != nil || completion == root {
return
}
completion.Short = "Generate shell completion scripts"
examples := map[string]string{
"bash": `$ eval "$(gt completion bash)"`,
"zsh": `$ source <(gt completion zsh)`,
"fish": `$ gt completion fish > ~/.config/fish/completions/gt.fish`,
"powershell": `$ gt completion powershell | Out-String | Invoke-Expression`,
completion.Long = "Generate the completion script of gt for bash, zsh, fish or powershell.\nRun gt completion <shell> --help to see how to load it."
help := map[string]struct{ long, example string }{
"bash": {`Generate the completion script for bash. It needs the bash-completion package.
To load completions in every new shell, add the eval line below to ~/.bashrc (on macOS,
~/.bash_profile); bash 3.2, the default on macOS, cannot source <(gt completion bash).`, `$ eval "$(gt completion bash)"`},
"zsh": {`Generate the completion script for zsh. It needs compinit; enable it
with the line autoload -U compinit; compinit in ~/.zshrc.
To load completions in every new shell, add the source line below to ~/.zshrc, or write
the script to a directory of $fpath as _gt.`, `$ source <(gt completion zsh)
$ gt completion zsh > "${fpath[1]}/_gt"`},
"fish": {`Generate the completion script for fish.
To load completions in every new shell, write the script to ~/.config/fish/completions;
to load them in the current shell only, pipe it to source.`, `$ gt completion fish > ~/.config/fish/completions/gt.fish
$ gt completion fish | source`},
"powershell": {`Generate the completion script for PowerShell.
To load completions in every new shell, add the line below to your PowerShell profile.`, `$ gt completion powershell | Out-String | Invoke-Expression`},
}
for _, shell := range completion.Commands() {
shell.Example = examples[shell.Name()]
shell.Args = argsExact(0)
shell.Long, shell.Example = help[shell.Name()].long, help[shell.Name()].example
shell.Args, shell.DisableFlagsInUseLine = argsExact(0), false
if shell.Annotations == nil {
shell.Annotations = map[string]string{}
}
@@ -621,9 +634,4 @@ func completionInstallHelp(root *cobra.Command) {
flag.Usage = "Disable completion descriptions"
}
}
bash, _, _ := completion.Find([]string{"bash"})
bash.Long = `Generate the completion script for bash. It needs the bash-completion package.
To load completions in every new shell, add the eval line below to ~/.bashrc (on macOS,
~/.bash_profile); bash 3.2, the default on macOS, cannot source <(gt completion bash).`
}
+18 -2
View File
@@ -456,6 +456,13 @@ func TestCompletionInstallHelp(t *testing.T) {
deps, out, _ := testDeps(t)
require.NoError(t, Execute(context.Background(), deps, []string{"completion", "bash", "--help"}))
require.Contains(t, out.String(), "$ eval \"$(gt completion bash)\"\n")
for _, shell := range []string{"bash", "zsh", "fish", "powershell"} {
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"completion", shell, "--help"}))
require.Contains(t, out.String(), "USAGE\n gt completion "+shell+" [flags]\n", shell)
require.NotContains(t, out.String(), "####", shell)
require.NotContains(t, out.String(), "\t", shell)
}
}
func TestCompletionTargetAcceptsABareTokenHost(t *testing.T) {
@@ -481,20 +488,24 @@ func TestAccountCompletionUsesInstanceOfRepository(t *testing.T) {
}
}
func TestActionValueCompletionOutsideARepository(t *testing.T) {
func TestActionValueCompletionFollowsTheScope(t *testing.T) {
server := newAuthenticatedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/orgs/acme/actions/variables":
_, _ = w.Write([]byte(`[{"name":"REGION","data":"eu"}]`))
case "/api/v1/user/actions/variables":
_, _ = w.Write([]byte(`[{"name":"HOME_REGION","data":"eu"}]`))
case "/api/v1/repos/alice/project/actions/variables":
_, _ = w.Write([]byte(`[{"name":"REPO_REGION","data":"eu"}]`))
case "/api/v1/repos/alice/project/actions/secrets":
_, _ = w.Write([]byte(`[{"name":"REPO_TOKEN"}]`))
default:
t.Errorf("unexpected request %s", r.URL.Path)
w.WriteHeader(http.StatusTeapot)
}
}))
defer server.Close()
deps, _, _ := serverDeps(t, server.URL)
deps, out, _ := serverDeps(t, server.URL)
a := &application{deps: deps}
cmd := &cobra.Command{}
cmd.SetContext(context.Background())
@@ -509,6 +520,11 @@ func TestActionValueCompletionOutsideARepository(t *testing.T) {
values, _ := a.completeVariables(func() services.ActionScope { return tc.scope })(cmd, nil, "")
require.ElementsMatch(t, tc.want, values, name)
}
deps.Git = doctorGit(server.URL)
values, _ := complete(t, deps, out, "variable", "get", "")
require.Equal(t, []string{"REPO_REGION"}, values)
values, _ = complete(t, deps, out, "secret", "delete", "")
require.Equal(t, []string{"REPO_TOKEN"}, values)
}
func TestMilestoneCompletionOffersTheMilestonesTheCommandAccepts(t *testing.T) {
+4 -2
View File
@@ -75,8 +75,10 @@ func (a *application) editDraft(cmd *cobra.Command, body string) (terminal.Draft
return editor.Edit(cmd.Context(), command, body)
}
// errMissingBody names the flags that supply a body when there is no terminal to ask for one.
var errMissingBody = clierr.Wrap(clierr.Usage, errors.New("missing required input: supply --body, --body-file or --editor"))
// missingBody names the flags that supply a body when there is no terminal to ask for one.
func missingBody(cmd *cobra.Command) error {
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s requires --body, --body-file or --editor", commandName(cmd)))
}
// bodyEditor collects a body, such as that of an interactive form after the form ran. The editor
// is resolved first: without one, the body is typed into an inline multi-line field with title
+1 -1
View File
@@ -322,7 +322,7 @@ func TestReviewLifecycleEditorRejectsEmptyRequiredText(t *testing.T) {
}
err := Execute(context.Background(), deps, args)
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
require.ErrorContains(t, err, "needs a")
require.ErrorContains(t, err, "requires a")
require.NotContains(t, err.Error(), "draft saved", "an empty draft holds nothing to keep")
if verb == "submit" {
require.Equal(t, "Saved draft", editor.initial)
+4 -3
View File
@@ -26,9 +26,10 @@ from github.com; gt runs the gh extensions that do not depend on GitHub's own AP
commands always win over an extension of the same name; gt extension exec runs it anyway.
gt passes the global flags --host, --repo and --user before the extension's name on as
GITEA_CLI_HOST, GITEA_CLI_REPO and GITEA_CLI_USER, runs it in --cwd, and passes everything
after its name on unchanged. Extensions do not get your Gitea token unless you allowed it at
install. See gt help extensions for the security model.`}
GITEA_CLI_HOST, GITEA_CLI_REPO and GITEA_CLI_USER, runs it in --cwd, accepts --no-input and
--yes, refuses other global flags, and passes everything after its name on unchanged.
Extensions do not get your Gitea token unless you allowed it at install. See gt help
extensions for the security model.`}
group.AddCommand(a.extensionInstallCommand(), a.extensionListCommand(), a.extensionRemoveCommand(), a.extensionUpgradeCommand(), a.extensionExecCommand(), a.extensionCreateCommand(), a.extensionSearchCommand(), a.extensionBrowseCommand())
return group
}
+25 -8
View File
@@ -266,11 +266,8 @@ func (a *application) resolveExtension(ctx context.Context, source extensionSour
return c, err
}
}
if minimum := c.manifest.Metadata.MinVersion; extensions.Older(version.Current(), minimum) {
return c, fmt.Errorf("extension %s requires gt %s or newer; this is gt %s", name, minimum, version.Current())
}
if !c.manifest.Metadata.Supports(runtime.GOOS, runtime.GOARCH) {
return c, fmt.Errorf("extension %s does not support %s/%s (platforms: %s)", name, runtime.GOOS, runtime.GOARCH, strings.Join(c.manifest.Metadata.Platforms, ", "))
if err := checkExtensionMetadata(name, c.manifest.Metadata); err != nil {
return c, err
}
c.manifest.Kind = extensions.KindScript
if found {
@@ -288,6 +285,17 @@ func (a *application) resolveExtension(ctx context.Context, source extensionSour
return c, nil
}
// checkExtensionMetadata refuses an extension whose gt-extension.yml rules out this gt or platform.
func checkExtensionMetadata(name string, metadata extensions.Metadata) error {
if minimum := metadata.MinVersion; extensions.Older(version.Current(), minimum) {
return fmt.Errorf("extension %s requires gt %s or newer; this is gt %s", name, minimum, version.Current())
}
if !metadata.Supports(runtime.GOOS, runtime.GOARCH) {
return fmt.Errorf("extension %s does not support %s/%s (platforms: %s)", name, runtime.GOOS, runtime.GOARCH, strings.Join(metadata.Platforms, ", "))
}
return nil
}
// publishedDigest finds the digest the source publishes for the candidate's asset: the one it
// recorded at upload, else the one checksums.txt lists. Without either, only the digest gt records
// at install protects the executable from then on.
@@ -529,7 +537,7 @@ func (a *application) installExtension(cmd *cobra.Command, raw string, opts exte
return err
}
if !a.options.yes && !a.canPrompt() {
return clierr.Wrap(clierr.Usage, errors.New("extension install requires --yes when gt cannot prompt"))
return clierr.Wrap(clierr.Usage, fmt.Errorf("confirmation required to install extension %s; rerun with --yes", name))
}
policy, err := a.extensionPolicy()
if err != nil {
@@ -610,6 +618,9 @@ func (a *application) checkExtensionName(cmd *cobra.Command, name string, force
return clierr.Wrap(clierr.Usage, fmt.Errorf("extension %s cannot be installed: the alias %s has that name; delete it with gt alias delete %s", name, name, name))
}
if installed, err := a.extensionStore().Lookup(name); err == nil && !force {
if installed.Kind == extensions.KindLocal || installed.Pinned {
return fmt.Errorf("extension %s is already installed from %s; reinstall it with --force, or remove it with gt extension remove %s", name, extensionOrigin(installed.Manifest), name)
}
return fmt.Errorf("extension %s is already installed from %s; upgrade it with gt extension upgrade %s, or reinstall it with --force", name, extensionOrigin(installed.Manifest), name)
}
return nil
@@ -658,6 +669,12 @@ func (a *application) installLocalExtension(cmd *cobra.Command, raw string, opts
return err
}
}
if err := checkExtensionMetadata(name, manifest.Metadata); err != nil {
return err
}
if manifest.Credentials, err = a.grantCredentials(cmd, manifest, opts.allowCredentials, policy); err != nil {
return err
}
stage, err := a.extensionStore().Stage()
if err != nil {
return err
@@ -694,7 +711,7 @@ $ gt extension upgrade --all --yes`,
return clierr.Wrap(clierr.Usage, errors.New("--all cannot be combined with extension names"))
}
if all && !dryRun && !a.options.yes && !a.canPrompt() {
return clierr.Wrap(clierr.Usage, errors.New("extension upgrade --all requires --yes when gt cannot prompt"))
return clierr.Wrap(clierr.Usage, errors.New("confirmation required to upgrade all extensions; rerun with --yes"))
}
return nil
},
@@ -785,7 +802,7 @@ func (a *application) upgradeExtension(cmd *cobra.Command, installed extensions.
return err
}
if (!current || force) && !dryRun && !a.options.yes && !a.canPrompt() {
return clierr.Wrap(clierr.Usage, errors.New("extension upgrade requires --yes when gt cannot prompt"))
return clierr.Wrap(clierr.Usage, fmt.Errorf("confirmation required to upgrade extension %s; rerun with --yes", m.Name))
}
stage, err := a.stageExtension(ctx, &c)
if err != nil {
+10 -6
View File
@@ -25,9 +25,10 @@ import (
"github.com/spf13/pflag"
)
// extensionFlags are the global flags an extension receives, as the environment variables gt
// itself reads them from; --cwd becomes its working directory.
var extensionFlags = map[string]string{"host": "GITEA_CLI_HOST", "repo": "GITEA_CLI_REPO", "user": "GITEA_CLI_USER", "cwd": ""}
// extensionFlags are the global flags an extension accepts, with the environment variables gt
// itself reads them from; --cwd becomes its working directory, and --no-input and --yes, which
// every gt command accepts, have no variable to pass.
var extensionFlags = map[string]string{"host": "GITEA_CLI_HOST", "repo": "GITEA_CLI_REPO", "user": "GITEA_CLI_USER", "cwd": "", "no-input": "", "yes": ""}
// defaultExtensionIndex lists the officially supported extensions.
const defaultExtensionIndex = "https://gitea.com/gitea/cli-extensions"
@@ -255,7 +256,7 @@ func (a *application) extensionFlagEnv(root *cobra.Command, name string, leading
unsupported = append(unsupported, "--"+flag.Name)
case flag.Name == "cwd":
dir = flag.Value.String()
default:
case variable != "":
set[variable] = flag.Value.String()
}
})
@@ -323,14 +324,17 @@ func (a *application) extensionCredentials(ctx context.Context, extension extens
// GITEA_TOKEN belongs to the instance in GITEA_CLI_HOST or GITEA_INSTANCE_URL and to an account
// gt cannot check without a request; pass it on only when --host selects that instance and
// no account is named.
host, _ := a.envHost()
host, key := a.envHost()
if host == "" {
return set, errors.New("GITEA_TOKEN requires GITEA_CLI_HOST or GITEA_INSTANCE_URL naming its instance")
}
snapshot, err := a.settings()
if err != nil {
return set, err
}
instance, err := settings.ResolveHost(host, snapshot.Hosts.Hosts)
if err != nil {
return set, err
return set, fmt.Errorf("invalid %s: %w", key, err)
}
if a.options.host != "" {
if selected, err := settings.ResolveHost(a.options.host, snapshot.Hosts.Hosts); err != nil || selected != instance {
+33 -3
View File
@@ -196,6 +196,8 @@ func TestExtensionInstallRunAndRemove(t *testing.T) {
err = Execute(context.Background(), deps, []string{"--json", "hello"})
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
require.EqualError(t, err, "extension hello cannot be combined with --json")
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()
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "list", "--json", "name,tag,credentials,shadowed"}))
@@ -204,7 +206,7 @@ func TestExtensionInstallRunAndRemove(t *testing.T) {
require.NoError(t, os.WriteFile(extension.Path(), []byte("replaced"), 0o755))
err = Execute(context.Background(), deps, []string{"hello"})
require.ErrorContains(t, err, "extension hello changed since it was installed")
require.Len(t, runs.commands, 2, "a changed executable must not run")
require.Len(t, runs.commands, 3, "a changed executable must not run")
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "remove", "hello", "--yes"}))
err = Execute(context.Background(), deps, []string{"hello"})
@@ -368,7 +370,7 @@ func TestExtensionUpgradeRefusesChangedSources(t *testing.T) {
downloads := repo.downloads
err := Execute(context.Background(), deps, []string{"extension", "upgrade", "hello", "--no-input"})
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
require.EqualError(t, err, "extension upgrade requires --yes when gt cannot prompt")
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()
@@ -482,16 +484,40 @@ func TestLocalExtensionRunsInPlace(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(dir, "gt-dev"), []byte("#!/bin/sh\necho changed\n"), 0o755))
require.NoError(t, Execute(context.Background(), deps, []string{"dev"}))
assert.Equal(t, filepath.Join(dir, "gt-dev"), runs.commands[0].Path)
// There is nothing to upgrade it to.
require.EqualError(t, Execute(context.Background(), deps, []string{"extension", "install", dir}), "extension dev is already installed from "+dir+"; reinstall it with --force, or remove it with gt extension remove dev")
// gt-extension.yml applies as to a remote install.
require.NoError(t, os.WriteFile(filepath.Join(dir, "gt-extension.yml"), []byte("platforms: [plan9/mips]\n"), 0o644))
require.ErrorContains(t, Execute(context.Background(), deps, []string{"extension", "install", dir, "--force"}), "extension dev does not support "+runtime.GOOS+"/"+runtime.GOARCH)
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)
prompt := &scriptedPrompter{accept: true}
deps.Prompter = prompt
deps.Streams.InTTY, deps.Streams.ErrTTY = true, true
require.NoError(t, Execute(context.Background(), deps, []string{"extension", "install", dir, "--force"}))
assert.True(t, installedExtension(t, deps, "dev").Credentials)
assert.Equal(t, []string{"Give extension dev your Gitea token?"}, prompt.confirmations)
deps.Streams.InTTY, deps.Streams.ErrTTY = false, false
require.NoError(t, os.Remove(filepath.Join(dir, "gt-extension.yml")))
// Help lists only the global flags an extension accepts.
for _, args := range [][]string{{"help", "dev"}, {"extension", "exec", "--help"}} {
out.Reset()
require.NoError(t, Execute(context.Background(), deps, args))
assert.Contains(t, out.String(), "--cwd directory", args)
assert.Contains(t, out.String(), "Global flags: --host, --user; global flags go before the extension's name", args)
assert.Contains(t, out.String(), "Global flags: --host, --user, --no-input, --yes; global flags go before the extension's name", args)
assert.NotContains(t, out.String(), "--remote", args)
assert.NotContains(t, out.String(), "--sudo", args)
}
// Managing extensions selects no repository.
for _, args := range [][]string{{"extension", "--help"}, {"extension", "list", "--help"}} {
out.Reset()
require.NoError(t, Execute(context.Background(), deps, args))
assert.NotContains(t, out.String(), "-R, --repo", args)
assert.NotContains(t, out.String(), "--remote", args)
}
}
func TestBrokenExtensionManifestCanBeRemoved(t *testing.T) {
@@ -729,6 +755,10 @@ func TestExtensionGetsNoTokenOfAnotherInstance(t *testing.T) {
require.NoError(t, Execute(context.Background(), deps, []string{"--user", "bob", "hello"}))
_, set = runs.env("GITEA_TOKEN")
assert.False(t, set, "the GITEA_TOKEN of an unknown account must not reach an extension running as bob")
// 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")
}
func TestExtensionGetsARefreshedOAuthToken(t *testing.T) {
+53 -16
View File
@@ -33,7 +33,7 @@ const (
globalFlagsLine = "Global flags: --host, --user, --sudo, --no-input, --interactive, --debug (see gt help environment)"
// extensionFlagsLine replaces globalFlagsLine for commands that run an extension, which take
// only the global flags of extensionFlags.
extensionFlagsLine = "Global flags: --host, --user; global flags go before the extension's name (see gt help extensions)"
extensionFlagsLine = "Global flags: --host, --user, --no-input, --yes; global flags go before the extension's name (see gt help extensions)"
)
// noRepoCommands are command paths, with their subcommands, that never select a repository, so their
@@ -86,9 +86,8 @@ func (a *application) writeHelp(cmd *cobra.Command, _ []string) {
}
section("INHERITED FLAGS", inherited+"\n\n"+globals)
}
section("ARGUMENTS", cmd.Annotations["gt.arguments"])
if outputsJSON(cmd) {
section("JSON FIELDS", cmp.Or(cmd.Annotations["gt.jsonfields"], wrap(strings.Join(commandOutputFields(cmd), ", "), 78)))
for _, extra := range extraSections(cmd) {
section(extra.title, extra.body)
}
if !cmd.HasParent() {
section("EXAMPLES", "$ gt issue create\n$ gt issue list --label bug\n$ gt pr checkout 13\n$ gt repo clone owner/name")
@@ -174,14 +173,9 @@ func helpFlags(cmd *cobra.Command) (local, inherited string) {
})
}
slices.SortFunc(own, func(x, y *pflag.Flag) int { return strings.Compare(x.Name, y.Name) })
path := cmd.CommandPath()
repo := !slices.ContainsFunc(noRepoCommands, func(prefix string) bool { return path == prefix || strings.HasPrefix(path, prefix+" ") })
// A command's own --remote, as in repo fork, hides the global flag of that name.
// repo clone takes its repository as an argument only, so --repo and --remote do nothing there.
selects := repo && path != "gt repo clone"
shown := map[string]bool{"repo": selects, "remote": selects && cmd.LocalFlags().Lookup("remote") == nil && !runsExtension(cmd), "cwd": repo, "json": outputsJSON(cmd), "jq": outputsJSON(cmd) || cmd.Annotations["gt.rawjson"] != "", "yes": cmd.Annotations["gt.confirm"] != ""}
shown := sharedFlags(cmd)
var shared []*pflag.Flag
for _, name := range []string{"repo", "remote", "cwd", "json", "jq", "yes"} {
for _, name := range sharedFlagNames {
if shown[name] {
shared = append(shared, globals.Lookup(name))
}
@@ -192,6 +186,34 @@ func helpFlags(cmd *cobra.Command) (local, inherited string) {
return flagUsages(own), flagUsages(shared)
}
// sharedFlagNames are the global flags that help and the manual list only where they apply.
var sharedFlagNames = []string{"repo", "remote", "cwd", "json", "jq", "yes"}
// sharedFlags reports which of sharedFlagNames apply to cmd.
func sharedFlags(cmd *cobra.Command) map[string]bool {
path := cmd.CommandPath()
repo := !slices.ContainsFunc(noRepoCommands, func(prefix string) bool { return path == prefix || strings.HasPrefix(path, prefix+" ") })
// repo clone takes its repository as an argument only, so --repo and --remote do nothing there.
// Among gt extension's commands, only those running an extension take a repository.
selects := repo && path != "gt repo clone" && (!strings.HasPrefix(path, "gt extension") || runsExtension(cmd))
return map[string]bool{"repo": selects, "remote": selects && !runsExtension(cmd), "cwd": repo, "json": outputsJSON(cmd), "jq": outputsJSON(cmd) || cmd.Annotations["gt.rawjson"] != "", "yes": cmd.Annotations["gt.confirm"] != ""}
}
// helpSection is a titled section of a help page.
type helpSection struct{ title, body string }
// extraSections are the ARGUMENTS and JSON FIELDS sections of cmd, which the manual shows too.
func extraSections(cmd *cobra.Command) []helpSection {
var sections []helpSection
if arguments := cmd.Annotations["gt.arguments"]; arguments != "" {
sections = append(sections, helpSection{"ARGUMENTS", arguments})
}
if outputsJSON(cmd) {
sections = append(sections, helpSection{"JSON FIELDS", cmp.Or(cmd.Annotations["gt.jsonfields"], wrap(strings.Join(commandOutputFields(cmd), ", "), 78))})
}
return sections
}
// runsExtension reports whether cmd runs an extension.
func runsExtension(cmd *cobra.Command) bool {
return cmd.Annotations["gt.extension"] == "true" || cmd.CommandPath() == "gt extension exec"
@@ -301,7 +323,9 @@ func helpTopics(globals *pflag.FlagSet) []*cobra.Command {
var flags []*pflag.Flag
globals.VisitAll(func(flag *pflag.Flag) { flags = append(flags, flag) })
topics := []*cobra.Command{
{Use: "environment", Short: "Environment variables and global flags", Long: `Global flags work with every command, before or after the command name:
{Use: "environment", Short: "Environment variables and global flags", Long: `Global flags work with every built-in command, before or after the command name. An
extension takes only --host, --repo, --user, --cwd, --no-input and --yes, before its name
(see gt help extensions):
` + indent(flagUsages(flags)) + `
@@ -346,10 +370,11 @@ Preferences in config.yml are described in gt config --help.`},
{Use: "exit-codes", Short: "Exit codes used by gt", Long: `gt exits with one of these codes:
0 success, including an empty list
1 the command failed
1 the command failed, also when the instance did not respond within http_timeout
2 usage error: an unknown command or flag, or a missing or invalid argument
3 canceled: a declined confirmation, a prompt left with Esc (or Ctrl-D with TERM=dumb),
or a timeout
a wait that ran out of its --timeout, such as gt run watch or gt pr checks --watch,
or a browser authorization of gt auth login not completed within 2 minutes
4 authentication is missing or was rejected
5 gt run watch and gt workflow run --follow: the run completed without success
6 gt run watch --expect-head: the run is for another commit
@@ -383,7 +408,12 @@ GH_HOST. It gets:
GITEA_CLI_EXECUTABLE the path of gt, to call gt commands such as gt api
GITEA_CLI_HOST, _REPO, _USER from --host, --repo and --user before its name
GITEA_TOKEN, GITEA_INSTANCE_URL your token and its instance, only when you allowed it at
install; gh extensions also get GH_HOST and GH_TOKEN
install; gh extensions also get GH_HOST, GH_TOKEN and
GH_ENTERPRISE_TOKEN
Global flags go before the extension's name; everything after it is the extension's own.
--cwd sets its working directory, and --no-input and --yes are accepted but not passed on;
other global flags, such as --json, are refused.
gt itself refuses your stored credentials to an extension that was not given them. This is
hygiene, not a sandbox: an extension runs with your privileges, can read gt's configuration
@@ -412,7 +442,9 @@ wording of text output may change between releases.
-q, --jq EXPR filter the JSON with a jq expression; implies --json
The JSON FIELDS section of a command's help lists its fields, and shell completion
offers them after --json. An unknown field reports the available ones.
offers them after --json. An unknown field reports the available ones. A word after
--json is read as an argument only when the command takes no other, as in
gt release view --json v1; write --json=FIELDS to make it a field list.
--jq runs inside gt, so jq does not need to be installed. String results print
without quotes:
@@ -425,6 +457,11 @@ the output includes the field: --json names it, or --json selects every field an
expression names it. An expression that reaches such a field without naming it, as
to_entries does, sees it empty; name the field in --json instead.
Commands that take several arguments, such as issue close or milestone issue add, print an
object for one argument and an array of the successful results for several. A script that
needs one shape passes one argument per call, or several and reads the array, such as with
--jq '.[]'.
On a terminal, JSON is indented and colored; otherwise each value prints on one line.
Commands that return no resource, such as deletes, reject --json.`},
}
+8 -3
View File
@@ -131,9 +131,11 @@ func (testNoKeyring) Delete(string, string) error { return errNoTestKeyri
type fakeGit struct {
results map[string]string
calls []string
dirs []string
prompt bool
// errs are the failures of commands, such as a *git.CommandError.
errs map[string]error
calls []string
dirs []string
prompt bool
}
func (f *fakeGit) Output(_ context.Context, dir string, prompt bool, args ...string) (string, error) {
@@ -141,6 +143,9 @@ func (f *fakeGit) Output(_ context.Context, dir string, prompt bool, args ...str
f.calls = append(f.calls, key)
f.dirs = append(f.dirs, dir)
f.prompt = prompt
if err, ok := f.errs[key]; ok {
return "", err
}
value, ok := f.results[key]
if !ok {
return "", errors.New("missing fake Git result")
+4
View File
@@ -147,6 +147,10 @@ func TestInvalidColorEnvironmentIsAUsageError(t *testing.T) {
require.EqualError(t, err, `invalid GITEA_CLI_COLOR "bogus": color must be auto, always, or never`, "%v", args)
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
}
deps, _, _, _ = pagedDeps(t, server.URL, map[string]string{"GITEA_CLI_HTTP_TIMEOUT": "bogus"})
err := Execute(context.Background(), deps, []string{"config", "get", "http_timeout"})
require.EqualError(t, err, `invalid GITEA_CLI_HTTP_TIMEOUT "bogus": http_timeout must be a duration such as 30s or 5m, or 0 for none`)
require.Equal(t, clierr.Usage, clierr.ExitCode(err))
}
func TestTeaPagerAndColorEnvironmentOverrides(t *testing.T) {
+1 -1
View File
@@ -285,7 +285,7 @@ func TestGiteaMetadataLifecycle(t *testing.T) {
}
require.NotEmpty(t, notifications)
var boundedNotifications []services.Notification
require.NoError(t, json.Unmarshal(scoped("notification", "list", "--type", "issue", "--since=24h", "--before=0s"), &boundedNotifications))
require.NoError(t, json.Unmarshal(scoped("notification", "list", "--type", "issue", "--since=24h", "--until=0s"), &boundedNotifications))
require.NotEmpty(t, boundedNotifications)
notificationID := strconv.FormatInt(notifications[0].ID, 10)
var notification services.Notification
+118 -6
View File
@@ -4,7 +4,10 @@
package app
import (
"bytes"
"cmp"
"errors"
"fmt"
"io"
"regexp"
"strconv"
@@ -14,6 +17,7 @@ import (
"gitea.dev/cli/internal/clierr"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/spf13/pflag"
)
func (a *application) manCommand() *cobra.Command {
@@ -38,7 +42,7 @@ func (a *application) manCommand() *cobra.Command {
}
// GenMan fills an empty Title from the command path by mutating the header, so each page needs its own.
header := &doc.GenManHeader{Section: "1", Date: &date, Source: "gitea-cli", Manual: "gitea-cli Manual"}
if err := doc.GenMan(page, header, writer); err != nil {
if err := GenMan(page, header, writer); err != nil {
return err
}
if len(args) == 0 {
@@ -62,6 +66,92 @@ func (a *application) manCommand() *cobra.Command {
return command
}
// GenMan writes the man page of command. A help topic takes no flags, so its page lists none,
// and the root page refers to the topics, which Cobra skips as hidden.
func GenMan(command *cobra.Command, header *doc.GenManHeader, w io.Writer) error {
if command.HasParent() {
return genTopicPage(command, w, ".SH OPTIONS\n", ".SH SEE ALSO\n", func(w io.Writer) error { return doc.GenMan(command, header, w) })
}
var page bytes.Buffer
if err := doc.GenMan(command, header, &page); err != nil {
return err
}
var topics strings.Builder
for _, child := range ManualCommands(command) {
if child.Annotations[topicAnnotation] != "" {
fmt.Fprintf(&topics, `, \fB%s-%s(1)\fP`, command.Name(), child.Name())
}
}
before, seeAlso, _ := strings.Cut(page.String(), ".SH SEE ALSO\n")
references, after, _ := strings.Cut(seeAlso, "\n")
_, err := io.WriteString(w, before+".SH SEE ALSO\n"+strings.TrimPrefix(references+topics.String(), ", ")+"\n"+after)
return err
}
// GenMarkdown writes the reference page of command like GenMan.
func GenMarkdown(command *cobra.Command, w io.Writer) error {
return genTopicPage(command, w, "### Options\n", "### SEE ALSO\n", func(w io.Writer) error {
return doc.GenMarkdownCustom(command, w, func(name string) string { return name })
})
}
// genTopicPage writes the page that gen renders, dropping a help topic's flags and option
// sections, which run from options up to next. The topic's indented tables become code blocks.
func genTopicPage(command *cobra.Command, w io.Writer, options, next string, gen func(io.Writer) error) error {
if command.Annotations[topicAnnotation] == "" {
return genCommandPage(command, w, gen)
}
long, flagsInUseLine := command.Long, command.DisableFlagsInUseLine
defer func() { command.Long, command.DisableFlagsInUseLine = long, flagsInUseLine }()
lines := strings.Split(long, "\n")
for i, line := range lines {
if strings.HasPrefix(line, " ") {
lines[i] = " " + line
}
}
command.Long, command.DisableFlagsInUseLine = strings.Join(lines, "\n"), true
var page bytes.Buffer
if err := gen(&page); err != nil {
return err
}
before, rest, _ := strings.Cut(page.String(), options)
if _, after, found := strings.Cut(rest, next); found {
before += next + after
}
_, err := io.WriteString(w, before)
return err
}
// genCommandPage writes the page that gen renders with the flags and sections of the command's
// help page: without the global flags that do not apply, and with ARGUMENTS and JSON FIELDS.
func genCommandPage(command *cobra.Command, w io.Writer, gen func(io.Writer) error) error {
if !command.HasParent() {
return gen(w)
}
globals := command.Root().PersistentFlags()
applies := sharedFlags(command)
if runsExtension(command) {
applies = map[string]bool{}
globals.VisitAll(func(flag *pflag.Flag) { _, applies[flag.Name] = extensionFlags[flag.Name] })
}
for name, shown := range applies {
if flag := globals.Lookup(name); flag != nil && !shown && !flag.Hidden {
flag.Hidden = true
defer func() { flag.Hidden = false }()
}
}
var sections strings.Builder
for _, extra := range extraSections(command) {
fmt.Fprintf(&sections, "\n\n### %s\n\n%s", extra.title, indent(indent(extra.body)))
}
if sections.Len() > 0 {
long := command.Long
defer func() { command.Long = long }()
command.Long = cmp.Or(long, command.Short) + sections.String()
}
return gen(w)
}
// ManualDate dates man pages from SOURCE_DATE_EPOCH, falling back to a fixed date so the
// manual stays reproducible when the variable is unset.
func ManualDate(getenv func(string) string) time.Time {
@@ -74,14 +164,29 @@ func ManualDate(getenv func(string) string) time.Time {
var manualPlaceholder = regexp.MustCompile(`<([A-Za-z])`)
// ManualRoot returns the built-in command tree prepared for man pages. md2man drops a
// <placeholder> as inline HTML, so it is escaped outside indented code blocks.
// <placeholder> as inline HTML and reads _WORD_ as emphasis, so both are escaped outside
// indented code blocks.
func ManualRoot() *cobra.Command {
return docsRoot(true, func(line string) string {
return strings.ReplaceAll(manualPlaceholder.ReplaceAllString(line, `\<$1`), "_", `\_`)
})
}
// ReferenceRoot returns the built-in command tree prepared for the Markdown reference, which
// drops a <placeholder> outside code as inline HTML too. Its usage line is a code block.
func ReferenceRoot() *cobra.Command {
return docsRoot(false, func(line string) string { return manualPlaceholder.ReplaceAllString(line, `\<$1`) })
}
// docsRoot returns the built-in command tree without auto-generated tags, with escapeLine applied
// to the prose lines of every short and long description, and of the usage line when use is set.
func docsRoot(use bool, escapeLine func(string) string) *cobra.Command {
root := NewRoot(Dependencies{})
escape := func(text string) string {
escape := func(text, code string) string {
lines := strings.Split(text, "\n")
for i, line := range lines {
if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, " ") {
lines[i] = manualPlaceholder.ReplaceAllString(line, `\<$1`)
if !strings.HasPrefix(line, "\t") && !strings.HasPrefix(line, code) {
lines[i] = escapeLine(line)
}
}
return strings.Join(lines, "\n")
@@ -89,7 +194,14 @@ func ManualRoot() *cobra.Command {
var prepare func(*cobra.Command)
prepare = func(command *cobra.Command) {
command.DisableAutoGenTag = true
command.Use, command.Short, command.Long = escape(command.Use), escape(command.Short), escape(command.Long)
code := " "
if command.Annotations[topicAnnotation] != "" {
code = " " // genTopicPage turns every indented line of a topic into code
}
if use {
command.Use = escape(command.Use, " ")
}
command.Short, command.Long = escape(command.Short, " "), escape(command.Long, code)
for _, child := range command.Commands() {
prepare(child)
}
+10
View File
@@ -83,4 +83,14 @@ func TestManIncludesHelpTopicsButNotHelpCommands(t *testing.T) {
require.Contains(t, manual, `.TH "GT-ENVIRONMENT"`)
require.Contains(t, manual, `.TH "GT-EXIT-CODES"`)
require.NotContains(t, manual, `.TH "GT-PR-HELP"`)
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"man", "exit-codes"}))
require.NotContains(t, out.String(), ".SH OPTIONS", "a topic takes no flags")
require.Contains(t, out.String(), `\fBgt exit-codes\fP`)
require.Contains(t, out.String(), ".EX\n 0 success", "the table renders as code")
require.Contains(t, out.String(), ".SH SEE ALSO")
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"man", "environment"}))
require.Contains(t, out.String(), ".EX\n --cwd directory", "the flags render as one block")
require.NotContains(t, out.String(), ".PP\n-q, --jq")
}
+18 -6
View File
@@ -5,8 +5,8 @@ package app
import (
"fmt"
"strings"
"gitea.dev/cli/internal/clierr"
"gitea.dev/cli/internal/terminal"
"github.com/spf13/cobra"
)
@@ -49,15 +49,27 @@ func (a *application) deleteConfirmed(cmd *cobra.Command, subject string, del fu
// requireInput fills a missing value from a prompt titled label, such as "Label name", re-prompting
// until the answer is non-empty and validate, when set, accepts it. Without prompts it returns a
// usage error naming --flag. It reports whether it prompted.
// usage error naming --flag, or the argument when flag is not a listed flag. It reports whether it
// prompted.
func (a *application) requireInput(cmd *cobra.Command, value *string, flag, label string, validate func(string) error) (bool, error) {
s, err := a.settings()
if err != nil {
return false, err
}
if named := cmd.Flags().Lookup(flag); *value == "" && (named == nil || named.Hidden) && !a.policy(s).CanPrompt(a.deps.Streams) {
// The input is an argument, not a listed flag, so point at the argument.
return false, clierr.Wrap(clierr.Usage, fmt.Errorf("missing required input: %s (pass it as an argument)", label))
missing := fmt.Errorf("%s requires --%s", commandName(cmd), flag)
if named := cmd.Flags().Lookup(flag); named == nil || named.Hidden {
missing = fmt.Errorf("%s requires a %s argument", commandName(cmd), lowerWords(label))
}
return terminal.RequireInput(cmd.Context(), value, flag, label, validate, a.deps.Streams, a.policy(s), a.deps.Prompter)
return terminal.RequireInput(cmd.Context(), value, label, validate, missing, a.deps.Streams, a.policy(s), a.deps.Prompter)
}
// lowerWords lowercases label for use mid-sentence, keeping acronyms such as URL.
func lowerWords(label string) string {
words := strings.Fields(label)
for i, word := range words {
if word != strings.ToUpper(word) {
words[i] = strings.ToLower(word)
}
}
return strings.Join(words, " ")
}
+3 -1
View File
@@ -42,7 +42,9 @@ func TestRequireInputPromptsWithTheLabel(t *testing.T) {
name := ""
cmd.Flags().StringVar(&name, "name", "", "")
_, err := a.requireInput(cmd, &name, "name", "Label name", nil)
require.EqualError(t, err, "missing required input: supply --name")
require.EqualError(t, err, "list requires --name")
_, err = a.requireInput(cmd, &name, "url", "Payload URL", nil)
require.EqualError(t, err, "list requires a payload URL argument")
deps.Streams.InTTY, deps.Streams.ErrTTY = true, true
a, cmd = outputApplication(deps, "")
+70 -35
View File
@@ -37,13 +37,13 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"extension", "install", "https://github.com/owner"}, "invalid GitHub repository"},
{[]string{"extension", "install", ".", "--pin", "v1"}, "--pin cannot be combined with a local extension"},
{[]string{"extension", "upgrade"}, "extension upgrade requires extension names or --all"},
{[]string{"extension", "upgrade", "--all", "--no-input"}, "extension upgrade --all requires --yes when gt cannot prompt"},
{[]string{"extension", "upgrade", "--all", "--no-input"}, "confirmation required to upgrade all extensions; rerun with --yes"},
{[]string{"extension", "remove", "missing"}, `no extension named "missing"`},
{[]string{"extension", "exec"}, "extension exec requires an extension name"},
{[]string{"extension", "create", "Bad_Name"}, `invalid extension name "Bad_Name"`},
{[]string{"extension", "create", "repo"}, "extension repo cannot be created: gt repo is a built-in command"},
{[]string{"extension", "install", "alice/gt-pr"}, "extension pr cannot be installed: gt pr is a built-in command"},
{[]string{"extension", "install", "alice/gt-hello", "--no-input"}, "extension install requires --yes when gt cannot prompt"},
{[]string{"extension", "install", "alice/gt-hello", "--no-input"}, "confirmation required to install extension hello; rerun with --yes"},
{[]string{"api", "user", "--input", "-", "-f", "x=y"}, "--input cannot be combined with API fields"},
{[]string{"api", "user", "-f", "x=y", "-F", "x=2"}, "API field names must be unique"},
{[]string{"api", "user", "-f", "missing-equals"}, "API fields require name=value"},
@@ -80,14 +80,17 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"issue", "attachment", "download", "https://example.test/alice/project/issues/1", "1", "--output", "-", "--skip-existing"}, "--skip-existing cannot be combined with --output -"},
{[]string{"issue", "close", "1", "bad"}, `invalid issue "bad": use a number, #number, OWNER/REPO#number or URL`},
{[]string{"issue", "close", "1", "#1", "--no-input"}, "#1 is selected more than once"},
{[]string{"issue", "close", "bob/tool#1", "2"}, "2 cannot be combined with bob/tool#1; qualify it as bob/tool#2, or run a separate command for alice/project#2"},
{[]string{"issue", "reopen", "1", "01", "--no-input"}, "#1 is selected more than once"},
{[]string{"issue", "comment", "create", "1", "--body="}, "comment body cannot be empty"},
{[]string{"issue", "comment", "create", "1", "--no-input"}, "missing required input: supply --body, --body-file or --editor"},
{[]string{"issue", "comment", "1", "--edit-last", "--no-input"}, "missing required input: supply --body, --body-file or --editor"},
{[]string{"issue", "comment", "edit", "1", "--no-input"}, "missing required input: supply --body, --body-file or --editor"},
{[]string{"issue", "comment", "create", "1", "--no-input"}, "issue comment create requires --body, --body-file or --editor"},
{[]string{"issue", "comment", "1", "--edit-last", "--no-input"}, "issue comment requires --body, --body-file or --editor"},
{[]string{"issue", "comment", "edit", "1", "--no-input"}, "issue comment edit requires --body, --body-file or --editor"},
{[]string{"issue", "comment", "1", "--body-file", "-"}, "comment body cannot be empty"},
{[]string{"issue", "comment", "create", "1", "--body", "text", "--json=title"}, "unknown JSON field \"title\""},
{[]string{"issue", "create", "--no-input"}, "missing required input: supply --title"},
{[]string{"issue", "create", "--no-input"}, "issue create requires --title"},
{[]string{"issue", "create", "--template", "bug", "--no-input"}, "issue create requires --title"},
{[]string{"issue", "create", "--template", "bug", "--body-file", "-"}, "--body-file - requires --title"},
{[]string{"issue", "create", "--title", " "}, "issue title cannot be empty"},
{[]string{"label", "import", ""}, "file cannot be empty"},
{[]string{"ssh-key", "create", ""}, "file cannot be empty"},
@@ -98,14 +101,14 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"repo", "edit", "--add-topic", "go", "--remove-topic", "Go"}, `--add-topic "go" cannot be combined with --remove-topic "Go"`},
{[]string{"issue", "create", "--title", "safe", "--json=unknown"}, "unknown JSON field \"unknown\""},
{[]string{"issue", "create", "--title", "safe", "--json", "--jq", "["}, "invalid --jq expression"},
{[]string{"issue", "create", "--milestone="}, "--milestone needs a title or ID; omit --milestone for none"},
{[]string{"issue", "edit", "1", "--milestone="}, "--milestone needs a title or ID; use --remove-milestone to clear it"},
{[]string{"issue", "create", "--milestone="}, "--milestone requires a title or ID; omit --milestone for none"},
{[]string{"issue", "edit", "1", "--milestone="}, "--milestone requires a title or ID; use --remove-milestone to clear it"},
{[]string{"issue", "create", "--web", "--label", "bug"}, "--label cannot be combined with --web"},
{[]string{"issue", "create", "--web", "--deadline", "2026-12-24"}, "--deadline cannot be combined with --web"},
{[]string{"issue", "create", "--assignee", "alice, "}, "assignee names cannot be empty"},
{[]string{"issue", "create", "--template="}, "--template cannot be empty"},
{[]string{"issue", "create", "--title", "x", "--attachment", "."}, ". is not a regular file"},
{[]string{"issue", "create", "--milestone="}, "--milestone needs a title or ID"},
{[]string{"issue", "create", "--milestone="}, "--milestone requires a title or ID"},
{[]string{"issue", "edit", "1", "--milestone", "v1", "--remove-milestone"}, "--milestone cannot be combined with --remove-milestone"},
{[]string{"issue", "edit", "1"}, "nothing to edit; pass a flag such as --title (see --help)"},
{[]string{"issue", "edit", "1", "--editor=false"}, "nothing to edit"},
@@ -114,7 +117,7 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"issue", "edit", "1", "--set-assignees", "alice", "--add-assignee", "bob"}, "--set-assignees cannot be combined with --add-assignee or --remove-assignee"},
{[]string{"issue", "edit", "1", "--set-labels", "bug", "--add-label", "help"}, "--set-labels cannot be combined with --add-label or --remove-label"},
{[]string{"issue", "edit", "1", "--add-assignee", " "}, "assignee names cannot be empty"},
{[]string{"pr", "checkout", "feature"}, "pr checkout must run inside a Git clone"},
{[]string{"pr", "checkout", "feature"}, "pr checkout requires a Git clone"},
{[]string{"pr", "backport", "7"}, "pr backport requires --to"},
{[]string{"pr", "backport", "7", "--to", " "}, "branch names cannot be empty"},
{[]string{"pr", "backport", "7", "--to", "a", "--to", "b", "--branch", "x"}, "--branch cannot be combined with more than one --to"},
@@ -125,9 +128,9 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"pr", "backport", "7", "--to", "a", "--milestone", "-1"}, "--milestone must be a milestone title or a positive ID"},
{[]string{"pr", "backport", "7", "--to", "bad..x"}, "invalid branch name"},
{[]string{"pr", "backport", "7", "--to", "a", "--branch", "bad..x"}, "invalid branch name"},
{[]string{"pr", "backport", "7", "--to", "a"}, "pr backport must run inside a Git clone"},
{[]string{"pr", "backport", "7", "--to", "a"}, "pr backport requires a Git clone"},
{[]string{"pr", "checkout", "7", "--branch", "bad..x"}, "invalid branch name"},
{[]string{"pr", "clean", "feature", "--yes"}, "pr clean must run inside a Git clone"},
{[]string{"pr", "clean", "feature", "--yes"}, "pr clean requires a Git clone"},
{[]string{"issue", "edit", "1", "--add-project", "Board", "--remove-project", "Board"}, `--add-project "Board" cannot be combined with --remove-project "Board"`},
{[]string{"pr", "edit", "1", "--add-project", " Board", "--remove-project", "Board"}, `--add-project "Board" cannot be combined with --remove-project "Board"`},
{[]string{"issue", "edit", "1", "invalid", "--title", "Updated"}, `invalid issue "invalid"`},
@@ -148,6 +151,7 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"milestone", "view", ""}, "milestone title or ID cannot be empty"},
{[]string{"milestone", "issue", "add", "", "1"}, "milestone title or ID cannot be empty"},
{[]string{"milestone", "close", " ", "--by-name"}, "milestone title or ID cannot be empty"},
{[]string{"milestone", "close", "m1", "--by-name", "--json", "titel"}, `unknown JSON field "titel"`},
{[]string{"milestone", "create", "", "--title", "v1"}, "milestone title cannot be empty"},
{[]string{"milestone", "create", "--title", "v1", "--deadline", "invalid"}, "invalid --deadline"},
{[]string{"milestone", "create", "--title", "x", "--state", "merged", "--no-input"}, "--state must be open or closed"},
@@ -162,15 +166,17 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"notification", "list", "--type", "invalid"}, "--type must be issue, pull, commit, or repository"},
{[]string{"notification", "list", "--limit", "many"}, `"-L, --limit" flag: must be 1..1000`},
{[]string{"notification", "list", "--since="}, "invalid --since: use a date, RFC3339 timestamp, or duration such as 24h"},
{[]string{"notification", "list", "--since=1h", "--before=2h"}, "--since must not be later than --before"},
{[]string{"notification", "mark-read"}, "supply notification IDs or --all"},
{[]string{"notification", "list", "--since=1h", "--until=2h"}, "--since must not be later than --until"},
{[]string{"notification", "watch", "--until=1h", "--before=2h"}, "--until cannot be combined with --before"},
{[]string{"notification", "mark-read", "--all", "--until=1h", "--before=2h"}, "--until cannot be combined with --before"},
{[]string{"notification", "mark-read"}, "notification mark-read requires notification IDs or --all"},
{[]string{"notification", "mark-read", "1", "--all"}, "--all cannot be combined with notification IDs"},
{[]string{"notification", "mark-read", "1", "--status", "unread"}, "--status and --before require --all"},
{[]string{"notification", "mark-read", "--all", "--before="}, "invalid --before: use a date, RFC3339 timestamp, or duration such as 24h"},
{[]string{"notification", "mark-read", "1", "--status", "unread"}, "--status and --until require --all"},
{[]string{"notification", "mark-read", "--all", "--until="}, "invalid --until: use a date, RFC3339 timestamp, or duration such as 24h"},
{[]string{"notification", "mark-read", "9", "09"}, "resource 9 is selected more than once"},
{[]string{"notification", "watch", "--interval", "0s"}, "--interval must be positive and --timeout not negative"},
{[]string{"notification", "watch", "--timeout", "-1s"}, "--interval must be positive and --timeout not negative"},
{[]string{"notification", "watch", "--before=-1h"}, "invalid --before: relative duration cannot be negative"},
{[]string{"notification", "watch", "--interval", "0s"}, "--interval must be positive"},
{[]string{"notification", "watch", "--timeout", "-1s"}, "--timeout cannot be negative"},
{[]string{"notification", "watch", "--until=-1h"}, "invalid --until: relative duration cannot be negative"},
{[]string{"org", "create", "team", "--visibility", "unknown"}, "--visibility must be public, limited, or private"},
{[]string{"org", "edit", "team"}, "supply organization fields to edit"},
{[]string{"org", "list", "--all", "--username", "alice"}, "--all cannot be combined with --username"},
@@ -204,6 +210,7 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"pr", "create", "--agit", "--remote", "origin", "--reviewer", "bob"}, "--reviewer cannot be combined with --agit"},
{[]string{"pr", "create", "--agit", "--remote", "origin", "--reviewer-team", "core"}, "--reviewer-team cannot be combined with --agit"},
{[]string{"pr", "create", "--agit", "--remote", "origin", "--attachment", "log.txt"}, "--attachment cannot be combined with --agit"},
{[]string{"pr", "create", "--agit", "--remote", "origin", "--allow-maintainer-edits=false"}, "--allow-maintainer-edits cannot be combined with --agit"},
{[]string{"pr", "create", "--attachment", "."}, ". is not a regular file"},
{[]string{"pr", "edit", "7"}, "nothing to edit; pass a flag such as --title (see gt pr edit --help)"},
{[]string{"pr", "edit", "7", "--remove-assignee="}, "nothing to edit"},
@@ -217,13 +224,14 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"pr", "list", "--milestone", "-1"}, "--milestone must be a milestone title or a positive ID"},
{[]string{"pr", "list", "--state", "unknown"}, "--state must be open, closed, merged, or all"},
{[]string{"pr", "list", "--limit", "0"}, `"-L, --limit" flag: must be 1..1000`},
{[]string{"pr", "review", "1", "--no-input"}, "choose a review type: --approve, --request-changes, or --comment"},
{[]string{"pr", "review", "1", "--request-changes", "--no-input"}, "a change request needs a body"},
{[]string{"pr", "review", "1", "--no-input"}, "choose one review type: --approve, --request-changes, --comment or --pending"},
{[]string{"pr", "review", "1", "--request-changes", "--no-input"}, "--request-changes requires a body"},
{[]string{"pr", "review", "reply", "1", "7", "--no-input"}, "pr review reply requires --body, --body-file or --editor"},
{[]string{"pr", "review", "request", "1", "--team", " "}, "team names cannot be empty"},
{[]string{"pr", "review", "1", "--comments-file=-"}, "--comments-file requires a file"},
{[]string{"pr", "review", "submit", "1", "2", "--request-changes", "--body="}, "a change request needs a body"},
{[]string{"pr", "review", "dismiss", "1", "2", "--body="}, "a dismissal needs a reason"},
{[]string{"pr", "review", "dismiss", "1", "2", "--no-input", "--yes"}, "missing required input: supply --body"},
{[]string{"pr", "review", "submit", "1", "2", "--request-changes", "--body="}, "--request-changes requires a body"},
{[]string{"pr", "review", "dismiss", "1", "2", "--body="}, "pr review dismiss requires a reason; pass --body, --body-file or --editor"},
{[]string{"pr", "review", "dismiss", "1", "2", "--no-input", "--yes"}, "pr review dismiss requires a reason; pass --body, --body-file or --editor"},
{[]string{"pr", "review", "delete", "1", "2", "--json"}, "review deletion does not return a resource"},
{[]string{"pr", "status", "--limit=101"}, `"--limit" flag: must be 1..100`},
{[]string{"pr", "status", "--json=title"}, "unknown JSON field \"title\""},
@@ -239,21 +247,34 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"release", "download", "v1", "--archive", "zip", "--output", "-", "--skip-existing"}, "--skip-existing cannot be combined with --output -"},
{[]string{"release", "download", "v1", "--clobber", "--skip-existing"}, "--clobber cannot be combined with --skip-existing"},
{[]string{"release", "create", "--notes-file", "-"}, "--notes-file - requires a tag"},
{[]string{"release", "edit", "v1"}, "supply release fields to edit"},
{[]string{"release", "edit", "v1"}, "nothing to edit; pass a flag such as --title or --notes (see --help)"},
{[]string{"release", "edit", "v1", "--notes", ""}, "release notes cannot be cleared"},
{[]string{"release", "edit", "v1", "v2", "--tag", "v3"}, "--tag requires one release and a nonempty new tag"},
{[]string{"release", "edit", "v3", "--tag", "v3.0", "--json", "tag_name"}, `unknown JSON field "tag_name"`},
{[]string{"release", "publish", "v11", "--json", "tag_name"}, `unknown JSON field "tag_name"`},
{[]string{"release", "view", "--json", "tag_name", "v3"}, `unknown JSON field "tag_name"`},
{[]string{"release", "edit", "v1", "--draft", "false"}, "--draft takes no value; use --draft or --draft=false"},
{[]string{"release", "edit", "v1", "-d", "false", "-p", "False"}, "--draft takes no value; use --draft or --draft=false"},
{[]string{"release", "edit", "v1", "v2", "--prerelease", "TRUE"}, "--prerelease takes no value; use --prerelease or --prerelease=false"},
{[]string{"repo", "clone", ""}, "repository cannot be empty"},
{[]string{"repo", "clone", "alice/project", " "}, "directory cannot be empty"},
{[]string{"repo", "clone", "alice/project", "-u", ""}, "--upstream-remote-name requires a name; use --no-upstream"},
{[]string{"repo", "clone", "alice/project", "-u", "bad name"}, "--upstream-remote-name requires a valid Git remote name"},
{[]string{"repo", "clone", "alice/project", "-u", "origin"}, "--upstream-remote-name cannot be the fork's remote name origin"},
{[]string{"repo", "clone", "alice/project", "-u", "fork", "--", "--origin", "fork"}, "--upstream-remote-name cannot be the fork's remote name fork"},
{[]string{"repo", "clone", "alice/project", "-u", "fork", "--", "-ofork"}, "--upstream-remote-name cannot be the fork's remote name fork"},
{[]string{"repo", "fork", "alice/project", "--clone", "--", "-o", "upstream"}, "repo fork --clone requires a Git remote name for the fork other than upstream, the name of its parent's remote"},
{[]string{"repo", "fork", "alice/project", "--clone", "--", "--config=clone.defaultRemoteName=upstream"}, "repo fork --clone requires a Git remote name for the fork other than upstream, the name of its parent's remote"},
{[]string{"repo", "delete", "", "-y"}, "repository cannot be empty"},
{[]string{"repo", "view", " "}, "repository cannot be empty"},
{[]string{"repo", "list", ""}, "owner cannot be empty"},
{[]string{"repo", "create"}, "missing required input: Repository name (pass it as an argument)"},
{[]string{"repo", "create"}, "repo create requires a repository name argument"},
{[]string{"repo", "create", "acme/bad/name"}, "repository name must be nonempty, at most 100 bytes, and contain no path separators or whitespace"},
{[]string{"repo", "create", "name", "--default-branch", "bad..branch", "--auto-init"}, "invalid branch name"},
{[]string{"repo", "create", "name", "--license", "MIT"}, "initial content and default branch options require --auto-init"},
{[]string{"repo", "create", "name", "--license", "MIT"}, "--license requires --auto-init"},
{[]string{"repo", "create", "name", "--default-branch", "trunk"}, "--default-branch requires --auto-init"},
{[]string{"repo", "create", "name", "--push"}, "--push requires --source"},
{[]string{"repo", "create", "name", "--push", "--remote-name", "up"}, "--push and --remote-name require --source"},
{[]string{"repo", "create", "name", "--trust-model", "unknown"}, "--trust-model must be default, collaborator, committer, or collaboratorcommitter"},
{[]string{"repo", "create", "name", "--object-format", "unknown"}, "--object-format must be sha1 or sha256"},
{[]string{"repo", "create", "name", "--team", "developers"}, "--team requires --org and a team name"},
@@ -263,8 +284,9 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"repo", "create", "name", "--template", "owner/source", "--auto-init"}, "repository initialization options cannot be combined with --template"},
{[]string{"repo", "create", "name", "--template", "owner/source", "-R", "owner/other"}, "--repo is not used by repo create; did you mean: gt repo create owner/name"},
{[]string{"repo", "edit", "--default-branch="}, "--default-branch cannot be empty"},
{[]string{"repo", "edit"}, "nothing to edit; pass a flag such as --description (see --help)"},
{[]string{"repo", "edit", "-d", strings.Repeat("x", 2049)}, "description cannot exceed 2048 characters"},
{[]string{"repo", "fork", "alice/project", "--remote", "--remote-name", "-x"}, "--remote-name requires a valid Git remote name"},
{[]string{"repo", "fork", "alice/project", "--add-remote", "--remote-name", "-x"}, "--remote-name requires a valid Git remote name"},
{[]string{"repo", "fork", "alice/project", "--fork-name", "a b"}, "repository name must be nonempty, at most 100 bytes, and contain no path separators or whitespace"},
{[]string{"repo", "transfer", "acme", "--team", "", "--yes"}, "--team requires a team name"},
{[]string{"repo", "archive", "alice/project", "-R", "alice/other", "--yes"}, "a repository argument cannot be combined with --repo"},
@@ -273,12 +295,18 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"repo", "list", "account", "--starred"}, "an owner argument cannot be combined with --starred"},
{[]string{"repo", "list", "--starred", "--watched"}, "--starred cannot be combined with --watched"},
{[]string{"repo", "set-default", "alice/project", "--view"}, "--view cannot be combined with a repository argument"},
{[]string{"repo", "set-default", "alice/project", "--remote", "origin"}, "--remote cannot be combined with a repository argument or --repo"},
{[]string{"repo", "set-default", "--unset", "--remote", "upstream"}, "--remote cannot be combined with --unset"},
{[]string{"repo", "set-default", "--view", "--remote", "upstream"}, "--remote cannot be combined with --view"},
{[]string{"repo", "set-default", "--remote", "upstream"}, "--remote cannot be combined with GITEA_CLI_REPO"},
{[]string{"repo", "list", "--type", "invalid"}, "--type must be fork, source, or mirror"},
{[]string{"repo", "set-default", "--json"}, "set-default configures Git"},
{[]string{"repo", "sync", "--branch="}, "--branch cannot be empty"},
{[]string{"repo", "sync", "--branch", "bad..x"}, "invalid branch name"},
{[]string{"repo", "migrate", "--name", "new"}, "missing required input: Clone URL (pass it as an argument)"},
{[]string{"repo", "migrate", "--name", "new"}, "repo migrate requires a clone URL argument"},
{[]string{"repo", "migrate", "https://user:[email protected]/repo", "--name", "new"}, "clone URL must be an HTTP(S) or git URL without embedded credentials"},
{[]string{"repo", "migrate", "/srv/git/project.git", "--name", "new"}, "for a path on the Gitea server, use --server-path"},
{[]string{"repo", "migrate", "https://source.test/repo", "--lfs", "--lfs-endpoint", "file:///lfs"}, "--lfs-endpoint must be an HTTP(S) or git URL"},
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--service", "unknown"}, "--service must be git, gitea, gitlab, gogs, or github"},
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--issues"}, "plain Git migration cannot copy forge metadata"},
{[]string{"repo", "migrate", "https://source.test/repo", "--name", "new", "--mirror-interval", "8h"}, "--mirror-interval requires --mirror and a duration of 0 or more"},
@@ -312,7 +340,8 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"search", "repo", "query", "--order", "desc"}, "--order requires --sort"},
{[]string{"secret", "set", "BUILD_TOKEN", "--body", "text", "--body-file", "-"}, "--body cannot be combined with --body-file"},
{[]string{"secret", "set", "BUILD_TOKEN", "--body= ", "--json=value"}, "unknown JSON field \"value\""},
{[]string{"secret", "set", "BUILD_TOKEN", "--no-input"}, "missing value: pass --body, --body-file or standard input"},
{[]string{"secret", "set", "BUILD_TOKEN", "--no-input"}, "secret set requires --body, --body-file or standard input"},
{[]string{"secret", "set"}, "secret set requires a name argument or --env-file"},
{[]string{"secret", "set", "CI", "--body", "text"}, "CI and names starting with GITEA_ or GITHUB_ are reserved"},
{[]string{"secret", "set", "TOKEN", "--env-file", "secrets.env"}, "--env-file cannot be combined with a secret name"},
{[]string{"secret", "delete", "", "-y"}, `invalid name ""`},
@@ -331,16 +360,21 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"team", "edit", "1", "--unit="}, "must be formatted as key=value"},
{[]string{"team", "member", "add", "invalid", "alice"}, `invalid team "invalid": use ORG/TEAM, such as acme/developers, or a team ID`},
{[]string{"team", "view", "acme/"}, `invalid team "acme/"`},
{[]string{"team", "repo", "add", "2", "service", "-R", "acme/service"}, "--repo is not used by gt team repo add"},
{[]string{"team", "repo", "add", "2", "service", "-R", "acme/service"}, "--repo is not used by team repo add"},
{[]string{"time", "create", "1", "0s"}, `invalid duration "0s": time spent must be positive`},
{[]string{"time", "create", "1", "1ms"}, `invalid duration "1ms": use whole seconds`},
{[]string{"time", "list", "--issue", "0"}, `invalid issue "0"`},
{[]string{"time", "list", "--mine", "--issue", "1"}, "--mine cannot be combined with --issue"},
{[]string{"time", "list", "--since", "2026-10-02", "--until", "2026-10-01"}, "--since must not be later than --until"},
{[]string{"time", "list", "--since", "1h", "--until", "2h"}, "--since must not be later than --until"},
{[]string{"time", "list", "--total", "--json"}, "--total is a human-output summary"},
{[]string{"time", "list", "--total", "--json"}, "--total cannot be combined with --json or --jq"},
{[]string{"time", "list", "--mine", "-R", "alice/project"}, "--mine cannot be combined with --repo"},
{[]string{"time", "list", "--mine"}, "--mine cannot be combined with GITEA_CLI_REPO"},
{[]string{"time", "list", "--mine", "--remote", "origin"}, "--mine cannot be combined with --remote"},
{[]string{"variable", "set", "BUILD_MODE", "--body="}, "the value of BUILD_MODE is empty"},
{[]string{"secret", "set", "DEPLOY_KEY", "--body= "}, "the value of DEPLOY_KEY is empty"},
{[]string{"secret", "set", "DEPLOY_KEY", "--body= "}, "the value of DEPLOY_KEY contains only whitespace"},
{[]string{"secret", "set", "DEPLOY_KEY", "--body", "x", "--json=created_at"}, "unknown JSON field \"created_at\""},
{[]string{"secret", "list", "--account"}, "secret list cannot be combined with --account: Gitea cannot list account secrets"},
{[]string{"secret", "set", "DEPLOY_KEY", "--body=" + strings.Repeat("é", 32769)}, "the value of DEPLOY_KEY exceeds 65536 bytes"},
{[]string{"variable", "set", "GITEA_RESERVED", "--body", "text"}, "CI and names starting with GITEA_ or GITHUB_ are reserved"},
{[]string{"variable", "view", "", "--org", "o"}, `invalid name ""`},
@@ -358,9 +392,9 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"webhook", "create", " ", "--url", "http://x"}, "URL cannot be empty"},
{[]string{"webhook", "create", "https://host/path", "--secret", "one", "--secret-file", "-"}, "--secret cannot be combined with --secret-file"},
{[]string{"webhook", "create", "https://host/path", "--secret-file", "-", "--authorization-header-file", "-"}, "stdin can supply only one webhook credential"},
{[]string{"webhook", "create", "https://host/path", "--authorization-header", "one", "--clear-authorization"}, "choose one authorization header source or --clear-authorization"},
{[]string{"webhook", "create", "https://host/path", "--authorization-header", "one", "--clear-authorization"}, "--authorization-header, --authorization-header-file and --clear-authorization cannot be combined"},
{[]string{"webhook", "create", "https://host/path", "--authorization-header", "first\nsecond"}, "authorization header must be a single line"},
{[]string{"webhook", "create", "https://host/path", "--events", ""}, "--events needs at least one trigger"},
{[]string{"webhook", "create", "https://host/path", "--events", ""}, "--events requires at least one trigger"},
{[]string{"webhook", "create", "https://host/path", "--config", "secret=private"}, "--config cannot override the URL, secret, or webhook scope"},
{[]string{"webhook", "edit", "1"}, "nothing to edit; pass a flag such as --events or --active (see --help)"},
{[]string{"webhook", "edit", "1", "--active=false"}, "editing a webhook drops its stored authorization header unless it is sent again, and Gitea never returns it: pass --authorization-header-file or --authorization-header (use --clear-authorization only for a hook without one)"},
@@ -376,6 +410,7 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"wiki", "revisions", "Home", "--page", "0"}, `"--page" flag: must be a positive integer`},
{[]string{"workflow", "run", "ci.yml", "-r", "main", "-f", "a=1", "-f", "a=2"}, "input a is given more than once"},
{[]string{"workflow", "run", "ci.yml", "--interval", "1s"}, "--interval requires --follow"},
{[]string{"workflow", "run", "ci.yml", "--follow", "--json"}, "--follow cannot be combined with --json or --jq"},
{[]string{"workflow", "view", ""}, "workflow cannot be empty"},
{[]string{"workflow", "view", "ci", "--ref", "main"}, "--ref requires --yaml"},
} {
+13
View File
@@ -278,3 +278,16 @@ func refusal(apiErr *transport.APIError) string {
}
return ""
}
// emptyRepository returns a *RefusedError naming repo when err is Gitea's refusal to work on a
// repository without commits, such as "Git Repository is empty." or "repo is empty", and nil otherwise.
func emptyRepository(err error, repo, next string) error {
apiErr, ok := errors.AsType[*transport.APIError](err)
if !ok {
return nil
}
if message := strings.ToLower(apiErr.Message); !strings.Contains(message, "repository is empty") && !strings.Contains(message, "repo is empty") {
return nil
}
return &RefusedError{Text: repo + " is empty; push a commit " + next, Err: err}
}
+6
View File
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"net/http"
"strings"
"testing"
"gitea.dev/cli/internal/transport"
@@ -27,6 +28,7 @@ func TestCreatesAndListingsNameWhatIsMissingOrTaken(t *testing.T) {
"POST /api/v1/repos/alice/x/forks": {404, "not found"},
"GET /api/v1/repos/alice/x": {200, ""},
"POST /api/v1/repos/alice/x/branches": {409, "The branch already exists."},
"GET /api/v1/repos/alice/x/commits": {200, ""},
"GET /api/v1/repos/alice/missing/labels": {404, "not found"},
"POST /api/v1/repos/alice/missing/branch_protections": {404, "not found"},
}
@@ -34,6 +36,10 @@ func TestCreatesAndListingsNameWhatIsMissingOrTaken(t *testing.T) {
answer, ok := answers[r.Method+" "+r.URL.Path]
require.True(t, ok, "unexpected %s %s", r.Method, r.URL.Path)
w.WriteHeader(answer.status)
if strings.HasSuffix(r.URL.Path, "/commits") {
_, _ = w.Write([]byte(`[{"sha":"abc"}]`))
return
}
_, _ = w.Write([]byte(`{"message":"` + answer.message + `"}`))
}))
ctx := context.Background()
+47 -1
View File
@@ -184,6 +184,18 @@ func cappedPage[T any](limit, page int, maxSize func() int, fetch func(limit, pa
if !next && (!counted || total == (page-1)*limit+size && (page == 1 || linked || size != maxSize())) {
return Page[T]{Items: items, Total: total, Counted: counted}, nil
}
// A page shorter than the largest one the server answers is a filtered one: Gitea counts and
// pages over repositories the viewer cannot see. Pages then keep the server's positions, read
// in pages that start where the window does. A page of filterPageSize is taken as capped to
// spare the lookup on instances with Gitea's default maximum.
if size != filterPageSize {
if largest := maxSize(); largest > 0 && size < min(limit, largest) {
if limit <= largest {
return Page[T]{Items: items, More: next || (counted && total > page*limit), Total: total, Counted: counted}, nil
}
return positionedPage(limit, page, largest, items, headers, fetch)
}
}
offset := (page - 1) * limit
result := make([]T, 0, limit+size)
for serverPage := offset/size + 1; ; serverPage++ {
@@ -194,7 +206,7 @@ func cappedPage[T any](limit, page int, maxSize func() int, fetch func(limit, pa
}
}
result = append(result, batch[min(len(batch), max(0, offset-(serverPage-1)*size)):]...)
if len(batch) < size || len(result) >= limit {
if serverPage*size >= offset+limit || lastServerPage(headers, serverPage*size, len(batch), size) {
break
}
}
@@ -203,6 +215,40 @@ func cappedPage[T any](limit, page int, maxSize func() int, fetch func(limit, pa
return Page[T]{Items: result[:min(len(result), limit)], More: more, Total: total, Counted: counted}, nil
}
// positionedPage reads the window of limit items at page from server pages of at most largest
// that start and end inside it, so no server page straddles two windows; first and its headers
// are the server's page at page in pages of largest.
func positionedPage[T any](limit, page, largest int, first []T, headers http.Header, fetch func(limit, page int) ([]T, http.Header, error)) (Page[T], error) {
offset, end := (page-1)*limit, page*limit
result := []T{}
for at := offset; at < end; {
step := min(largest, end-at)
for at%step != 0 {
step--
}
batch := first
if step != largest || at/step+1 != page {
var err error
if batch, headers, err = fetch(step, at/step+1); err != nil {
return Page[T]{}, err
}
}
result = append(result, batch...)
if at += step; lastServerPage(headers, at, len(batch), step) {
break
}
}
next, total, counted := pageHints(headers)
return Page[T]{Items: result, More: next || (counted && total > end), Total: total, Counted: counted}, nil
}
// lastServerPage reports whether a server page of size that ends at position end and held got
// items is the last one: a short page is, unless the server links or counts more.
func lastServerPage(headers http.Header, end, got, size int) bool {
next, total, counted := pageHints(headers)
return got < size && !next && (!counted || total <= end)
}
// callPage is instancePage over an SDK list call.
func callPage[T any](ctx context.Context, client *transport.Client, limit, page int, list func(context.Context, *gitea.Client, gitea.ListOptions) ([]T, *gitea.Response, error)) (Page[T], error) {
return instancePage(ctx, client, limit, page, func(limit, page int) ([]T, http.Header, error) {
+47
View File
@@ -271,3 +271,50 @@ func TestShortLastPageWithLinksSkipsThePageSizeLookup(t *testing.T) {
require.Equal(t, []int{11, 12}, window.Items)
require.False(t, window.More)
}
func TestPagesOfAServerThatHidesCountedItemsHoldEachItemOnce(t *testing.T) {
for _, tc := range []struct {
total, maxItems int
hidden func(id int) bool
limits []int
}{
{100, 50, func(id int) bool { return id%2 == 0 }, []int{30, 100}},
{300, 100, func(id int) bool { return id%20 == 0 }, []int{30, 70, 100, 150, 200, 250}},
{200, 50, func(id int) bool { return id > 50 && id%10 == 0 }, []int{150}},
} {
fetch := func(limit, page int) ([]int, http.Header, error) {
size := min(limit, tc.maxItems)
var items []int
for id := (page-1)*size + 1; id <= min(page*size, tc.total); id++ {
if !tc.hidden(id) {
items = append(items, id)
}
}
headers := http.Header{"X-Total-Count": {strconv.Itoa(tc.total)}}
if page*size < tc.total {
headers.Set("Link", fmt.Sprintf(`<http://h/api/v1/o?limit=%d&page=%d>; rel="next"`, limit, page+1))
}
return items, headers, nil
}
var want []int
for id := 1; id <= tc.total; id++ {
if !tc.hidden(id) {
want = append(want, id)
}
}
for _, limit := range tc.limits {
t.Run(fmt.Sprintf("max %d limit %d of %d", tc.maxItems, limit, tc.total), func(t *testing.T) {
var seen []int
for page := 1; ; page++ {
window, err := cappedPage(limit, page, func() int { return tc.maxItems }, fetch)
require.NoError(t, err)
seen = append(seen, window.Items...)
if !window.More {
break
}
}
require.Equal(t, want, seen)
})
}
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ func (e SystemEditor) Edit(ctx context.Context, command, body string) (Draft, er
if ctx.Err() != nil {
return draft, ctx.Err()
}
return draft, fmt.Errorf("%w; draft has been preserved", runErr)
return draft, runErr // The caller reports where the draft is.
}
data, err := os.ReadFile(draft.Path)
if err != nil {
+1 -1
View File
@@ -33,7 +33,7 @@ func TestEditorRetainsPrivateDraftAfterSuccessAndFailure(t *testing.T) {
out, diagnostics := &bytes.Buffer{}, &bytes.Buffer{}
draft, err := (SystemEditor{Directory: directory, Streams: Streams{Out: out, ErrOut: diagnostics}}).Edit(context.Background(), shellquote.Join(program), "initial text")
if fail {
require.Error(t, err)
require.EqualError(t, err, "editor failed: exit status 7")
} else {
require.NoError(t, err)
require.Equal(t, "edited draft", draft.Body)
+3 -3
View File
@@ -353,14 +353,14 @@ func (p *FormPrompter) ConfirmDefault(ctx context.Context, title string, default
// RequireInput fills a missing value from a prompt titled label and marked "(required)" like the
// form fields, re-prompting inline until the answer is non-empty and validate, when set, accepts
// it. When prompts are unavailable it returns a usage error naming --flag. It reports whether it
// it. When prompts are unavailable it returns missing as a usage error. It reports whether it
// prompted.
func RequireInput(ctx context.Context, value *string, flag, label string, validate func(string) error, streams Streams, policy Policy, prompt Prompter) (bool, error) {
func RequireInput(ctx context.Context, value *string, label string, validate func(string) error, missing error, streams Streams, policy Policy, prompt Prompter) (bool, error) {
if *value != "" {
return false, nil
}
if !policy.CanPrompt(streams) {
return false, clierr.Wrap(clierr.Usage, fmt.Errorf("missing required input: supply --%s", flag))
return false, clierr.Wrap(clierr.Usage, missing)
}
entered, err := prompt.Ask(ctx, label+" (required):", func(s string) error {
if s == "" {
+4 -4
View File
@@ -140,19 +140,19 @@ func TestRequireInput(t *testing.T) {
asker := &askingPrompt{answers: []string{"", "red", "d73a4a"}}
value := ""
asked, err := RequireInput(context.Background(), &value, "color", "Color", hex, streams, policy, asker)
asked, err := RequireInput(context.Background(), &value, "Color", hex, errors.New("label create requires --color"), streams, policy, asker)
require.NoError(t, err)
require.True(t, asked)
require.Equal(t, "d73a4a", value)
require.Equal(t, []string{"", "red"}, asker.rejected)
require.Equal(t, []string{"Color (required):"}, asker.titles)
asked, err = RequireInput(context.Background(), &value, "color", "Color", hex, Streams{}, policy, asker)
asked, err = RequireInput(context.Background(), &value, "Color", hex, errors.New("label create requires --color"), Streams{}, policy, asker)
require.NoError(t, err, "a supplied value needs no prompt")
require.False(t, asked)
value = ""
_, err = RequireInput(context.Background(), &value, "color", "Color", hex, Streams{}, policy, asker)
require.EqualError(t, err, "missing required input: supply --color")
_, err = RequireInput(context.Background(), &value, "Color", hex, errors.New("label create requires --color"), Streams{}, policy, asker)
require.EqualError(t, err, "label create requires --color")
}
func TestFormPrompterConfirmDefault(t *testing.T) {
+8 -5
View File
@@ -57,7 +57,7 @@ gt run logs https://gitea.example.com/OWNER/REPO/actions/runs/34/jobs/71 --no-in
```
An Actions check's `url` is its job URL, and `gt run logs` accepts that URL to print just
that job. From a run ID instead, print the logs of every failed job:
that job. From a run ID instead, print the logs of every failed or canceled job:
```sh
gt run list --branch feature/login --status failure -L 5 --no-input --json id,workflow,title,conclusion
@@ -109,9 +109,9 @@ of the diff; gt refuses lines outside the diff. See [resources.md](references/re
| --- | --- | --- |
| Checks of a pull request | `gt pr checks 12` | [monitoring.md](references/monitoring.md) |
| Wait for checks | `gt pr checks 12 --watch` | [monitoring.md](references/monitoring.md) |
| Logs of failed jobs | `gt run logs 34 --failed` | [monitoring.md](references/monitoring.md) |
| Logs of failed or canceled jobs | `gt run logs 34 --failed` | [monitoring.md](references/monitoring.md) |
| Follow a running job | `gt run logs 34 --job build --follow` | [monitoring.md](references/monitoring.md) |
| Rerun failed jobs | `gt run rerun 34 --failed` | [monitoring.md](references/monitoring.md) |
| Rerun failed or canceled jobs | `gt run rerun 34 --failed` | [monitoring.md](references/monitoring.md) |
| Download artifacts | `gt run download 34 --name build` | [monitoring.md](references/monitoring.md) |
| Read an issue with comments | `gt issue view 17 --comments` | [resources.md](references/resources.md) |
| Open an issue | `gt issue create --title T --body-file -` | [resources.md](references/resources.md) |
@@ -149,11 +149,14 @@ of the diff; gt refuses lines outside the diff. See [resources.md](references/re
| Code | Meaning |
| --- | --- |
| 0 | Success, including an empty list |
| 1 | The command failed, or `gt pr checks` found a failed check |
| 1 | The command failed, `gt pr checks` found a failed check, or the instance did not respond within `http_timeout` |
| 2 | Usage error, or a confirmation that needs `--yes` |
| 3 | Canceled: declined confirmation or timeout |
| 3 | Canceled: a declined confirmation or prompt, or a wait's `--timeout` expired |
| 4 | Authentication missing or rejected |
| 5 | `gt run watch` and `gt workflow run --follow`: the run completed without success |
| 6 | `gt run watch --expect-head`: the run is for another commit |
| 8 | `gt pr checks`: checks still pending |
| 130 | Interrupted with Ctrl-C |
`gt help exit-codes` has the full list. Branch on the code instead of parsing messages.
+3 -2
View File
@@ -79,7 +79,7 @@ gt pr view --no-input --json number,url,state,draft
- A branch not on the remote yet is pushed first, which needs `--yes` without a terminal.
Ask the user before that push.
- Without push access, the branch goes to the user's fork when one is a remote. Otherwise ask
the user to run `gt repo fork --remote` first; gt does not fork without a terminal.
the user to run `gt repo fork --add-remote` first; gt does not fork without a terminal.
- `Closes #17` (or `fixes`, `resolves`) in the body closes the issue when the pull request is
merged.
- Follow the repository's own contribution rules (title style, sign-off, templates) when they
@@ -96,6 +96,7 @@ New description.
EOF
gt pr edit 18 --add-reviewer carol --add-label bug --no-input
gt pr ready 18 --no-input # draft to ready; --undo reverses it
gt pr update-branch 18 --no-input # merge the base branch in on Gitea; --rebase rewrites the head
```
Pushing new commits with `git push` updates the pull request; then re-check CI
@@ -186,7 +187,7 @@ so it also needs the user's request; on a conflict it changes nothing and fails.
```sh
gt repo view --no-input --json full_name,default_branch,private,actions_enabled
gt repo list OWNER -L 100 --no-input --json full_name,description,archived
gt repo fork --remote --no-input
gt repo fork --add-remote --no-input
gt repo edit --description "A short description" --add-topic cli --no-input
gt repo edit --enable-wiki=false --no-input
```
+41 -47
View File
@@ -34,65 +34,46 @@ func main() {
func generate(output string) error {
// Documentation describes built-ins, independently of personal settings,
// credentials, repository discovery, and environment-specific aliases.
root := app.NewRoot(app.Dependencies{})
var prepare func(*cobra.Command)
prepare = func(command *cobra.Command) {
command.DisableAutoGenTag = true
for _, child := range command.Commands() {
prepare(child)
}
}
prepare(root)
root := app.ReferenceRoot()
for _, directory := range []string{"reference", "man", "completion"} {
if err := os.MkdirAll(filepath.Join(output, directory), 0o755); err != nil {
return err
}
}
if err := doc.GenMarkdownTree(root, filepath.Join(output, "reference")); err != nil {
// Date the pages like gt man; make docs sets SOURCE_DATE_EPOCH to the last commit.
date := app.ManualDate(os.Getenv)
if err := walk(root, func(command *cobra.Command) error {
var page strings.Builder
if err := app.GenMarkdown(command, &page); err != nil {
return err
}
name := strings.ReplaceAll(command.CommandPath(), " ", "_") + ".md"
return os.WriteFile(filepath.Join(output, "reference", name), []byte(strings.TrimRight(page.String(), "\n")+"\n"), 0o644)
}); err != nil {
return err
}
pages, err := filepath.Glob(filepath.Join(output, "reference", "*.md"))
if err := walk(app.ManualRoot(), func(command *cobra.Command) error {
// GenMan fills an empty Title from the command path by mutating the header, so each page needs its own.
header := &doc.GenManHeader{Section: "1", Date: &date, Source: "gitea-cli", Manual: "gitea-cli Manual"}
name := strings.ReplaceAll(command.CommandPath(), " ", "-") + ".1"
return writeFile(filepath.Join(output, "man", name), func(w io.Writer) error { return app.GenMan(command, header, w) })
}); err != nil {
return err
}
var topics strings.Builder
for _, topic := range app.ManualCommands(root) {
if !topic.Runnable() && topic.Annotations["gt.topic"] != "" {
fmt.Fprintf(&topics, "* [gt help %s](gt_%s.md)\t - %s\n", topic.Name(), topic.Name(), topic.Short)
}
}
index := filepath.Join(output, "reference", "gt.md")
content, err := os.ReadFile(index)
if err != nil {
return err
}
for _, page := range pages {
content, err := os.ReadFile(page)
if err != nil {
return err
}
if err := os.WriteFile(page, []byte(strings.TrimRight(string(content), "\n")+"\n"), 0o644); err != nil {
return err
}
}
// Date the pages like gt man; make docs sets SOURCE_DATE_EPOCH to the last commit.
date := app.ManualDate(os.Getenv)
manual := app.ManualRoot()
header := &doc.GenManHeader{Section: "1", Date: &date, Source: "gitea-cli", Manual: "gitea-cli Manual"}
if err := doc.GenManTree(manual, header, filepath.Join(output, "man")); err != nil {
if err := os.WriteFile(index, []byte(string(content)+"\n### HELP TOPICS\n\n"+topics.String()), 0o644); err != nil {
return err
}
// Cobra skips the hidden help topics (environment, exit-codes, formatting); give them pages too.
for _, topic := range app.ManualCommands(root) {
if topic.Runnable() || topic.Annotations["gt.topic"] == "" {
continue
}
var page strings.Builder
if err := doc.GenMarkdownCustom(topic, &page, func(string) string { return "" }); err != nil {
return err
}
name := "gt_" + topic.Name() + ".md"
if err := os.WriteFile(filepath.Join(output, "reference", name), []byte(strings.TrimRight(page.String(), "\n")+"\n"), 0o644); err != nil {
return err
}
topicHeader := &doc.GenManHeader{Title: "GT-" + strings.ToUpper(topic.Name()), Section: "1", Date: &date, Source: "gitea-cli", Manual: "gitea-cli Manual"}
manualTopic, _, err := manual.Find([]string{topic.Name()})
if err != nil {
return err
}
if err := writeFile(filepath.Join(output, "man", "gt-"+topic.Name()+".1"), func(w io.Writer) error { return doc.GenMan(manualTopic, topicHeader, w) }); err != nil {
return err
}
}
completions := []struct {
name string
write func(io.Writer) error
@@ -123,6 +104,19 @@ Personal aliases are expanded dynamically by the installed shell completions.
`)+"\n"), 0o644)
}
// walk calls page for command and every command below it that has a page in the manual.
func walk(command *cobra.Command, page func(*cobra.Command) error) error {
if err := page(command); err != nil {
return err
}
for _, child := range app.ManualCommands(command) {
if err := walk(child, page); err != nil {
return err
}
}
return nil
}
func writeFile(path string, write func(io.Writer) error) error {
file, err := os.Create(path)
if err != nil {
+46
View File
@@ -41,6 +41,7 @@ func TestGeneratedReferenceIsCompleteAndReproducibleWithoutConfiguration(t *test
require.Equal(t, string(original), string(regenerated), relative)
require.NotContains(t, string(original), "Auto generated")
if filepath.Ext(path) == ".md" {
require.NotContains(t, string(original), "]()", relative)
for _, link := range links.FindAllStringSubmatch(string(original), -1) {
_, err := os.Stat(filepath.Join(filepath.Dir(path), link[1]))
require.NoError(t, err, "broken reference link in %s: %s", relative, link[1])
@@ -59,14 +60,59 @@ func TestGeneratedReferenceIsCompleteAndReproducibleWithoutConfiguration(t *test
require.NoError(t, err)
require.Contains(t, string(root), "--no-input")
require.Contains(t, string(root), "--repo")
for _, topic := range []string{"environment", "exit-codes", "extensions", "formatting"} {
require.Contains(t, string(root), "* [gt help "+topic+"](gt_"+topic+".md)", topic)
for _, page := range []string{"reference/gt_" + topic + ".md", "man/gt-" + topic + ".1"} {
content, err := os.ReadFile(filepath.Join(first, filepath.FromSlash(page)))
require.NoError(t, err)
require.NotRegexp(t, `(?i)(###|\.SH) options`, string(content), page)
require.Regexp(t, `(?i)(###|\.SH) see also`, string(content), page)
require.NotContains(t, string(content), "[flags]", page)
}
}
codes, err := os.ReadFile(filepath.Join(first, "reference", "gt_exit-codes.md"))
require.NoError(t, err)
require.Contains(t, string(codes), "\n\n 0 success", "the table renders as code")
man, err := os.ReadFile(filepath.Join(first, "man", "gt.1"))
require.NoError(t, err)
require.Contains(t, string(man), `"Aug 2026"`)
require.Contains(t, string(man), `\fBgt-workflow(1)\fP, \fBgt-environment(1)\fP, \fBgt-exit-codes(1)\fP`)
view, err := os.ReadFile(filepath.Join(first, "man", "gt-issue-view.1"))
require.NoError(t, err)
require.Contains(t, string(view), `.TH "GT-ISSUE-VIEW"`)
require.Contains(t, string(view), `\fBgt issue view {<number> | <url>} [flags]\fP`)
extensions, err := os.ReadFile(filepath.Join(first, "man", "gt-extensions.1"))
require.NoError(t, err)
require.Contains(t, string(extensions), "except for GITEA_TOKEN,\nGITEA_INSTANCE_*, GH_TOKEN,")
settings, err := os.ReadFile(filepath.Join(first, "reference", "gt_config.md"))
require.NoError(t, err)
require.Contains(t, string(settings), `Account settings (--host \<url> --user \<name>)`, "a placeholder in prose is not inline HTML")
reference, err := os.ReadFile(filepath.Join(first, "reference", "gt_issue_view.md"))
require.NoError(t, err)
require.Contains(t, string(reference), "```\ngt issue view {<number> | <url>} [flags]\n```", "the usage line is code")
milestone, err := os.ReadFile(filepath.Join(first, "reference", "gt_milestone_close.md"))
require.NoError(t, err)
require.Contains(t, string(milestone), "--by-name")
for _, page := range []string{"reference/gt_version.md", "reference/gt_run_logs.md", "man/gt-run-logs.1"} {
content, err := os.ReadFile(filepath.Join(first, filepath.FromSlash(page)))
require.NoError(t, err)
require.NotContains(t, string(content), "json", page)
}
logs, err := os.ReadFile(filepath.Join(first, "man", "gt-run-logs.1"))
require.NoError(t, err)
require.Contains(t, string(logs), ".SS ARGUMENTS\n.EX\nA run can be supplied")
require.Contains(t, string(logs), `\fB--repo\fP`)
issue, err := os.ReadFile(filepath.Join(first, "reference", "gt_issue_view.md"))
require.NoError(t, err)
require.Contains(t, string(issue), "### JSON FIELDS\n\n assignees, author,")
require.Contains(t, string(issue), "--jq")
require.NotContains(t, string(issue), "--yes")
exec, err := os.ReadFile(filepath.Join(first, "reference", "gt_extension_exec.md"))
require.NoError(t, err)
for _, flag := range []string{"--host", "--user", "--repo", "--cwd", "--no-input", "--yes"} {
require.Contains(t, string(exec), flag)
}
for _, flag := range []string{"--sudo", "--debug", "--interactive", "--remote", "--json"} {
require.NotContains(t, string(exec), flag)
}
}