feat: print list and view output as CSV with --csv (#50)

Adds a global `--csv [FIELDS]` flag on every command that supports `--json`: a header row, then one row per item, with nested values as compact JSON. It reuses the JSON field list, validation and completion, and cannot be combined with `--json` or `--jq`. CSV was only possible through `--jq '@csv'`, which needs the fields spelled out twice.

A PDF report is left out: it needs a heavy dependency for a rare need.

Closes https://gitea.com/gitea/cli/issues/49

Reviewed-on: https://gitea.com/gitea/cli/pulls/50
Reviewed-by: Lunny Xiao <[email protected]>
This commit is contained in:
bircni
2026-10-30 06:26:03 +00:00
parent fad1332849
commit 60b8c4ca71
24 changed files with 221 additions and 56 deletions
+3 -3
View File
@@ -2,8 +2,8 @@
gt replaces [tea](https://gitea.com/gitea/tea). Commands are singular and grouped by resource
(`gt pr`, not `tea pulls`), every `list` also answers to `ls` and every `delete` to `rm`, and
`--json` with `--jq` replaces `--output`. gt reads its own configuration, so log in again with
`gt auth login`.
`--json` with `--jq`, or `--csv`, replaces `--output`. gt reads its own configuration, so log in
again with `gt auth login`.
## Global flags
@@ -12,7 +12,7 @@ gt replaces [tea](https://gitea.com/gitea/tea). Commands are singular and groupe
| `--login`, `-l` | `--host` and `--user` |
| `--repo`, `-r` | `--repo`, `-R` |
| `--remote`, `-R` | `--remote` |
| `--output`, `-o` | `--json`, `--jq` |
| `--output`, `-o` | `--json`, `--jq`, `--csv` |
## Commands
+1 -1
View File
@@ -253,7 +253,7 @@ $ gt run view 34 --json jobs --jq '.jobs[] | {name, conclusion}'`,
Annotations: map[string]string{"gt.arguments": runArguments},
RunE: func(cmd *cobra.Command, args []string) error {
if log && (web || a.options.json != "") {
return clierr.Wrap(clierr.Usage, errors.New("--log cannot be combined with --web, --json or --jq"))
return clierr.Wrap(clierr.Usage, errors.New("--log cannot be combined with --web, --json, --jq or --csv"))
}
t, id, err := a.runArg(cmd, args, false)
if err != nil {
+2 -2
View File
@@ -90,7 +90,7 @@ $ gt workflow view ci --web`,
return clierr.Wrap(clierr.Usage, errors.New("--ref requires --yaml"))
}
if showYAML && (web || a.options.json != "") {
return clierr.Wrap(clierr.Usage, errors.New("--yaml cannot be combined with --web, --json or --jq"))
return clierr.Wrap(clierr.Usage, errors.New("--yaml cannot be combined with --web, --json, --jq or --csv"))
}
t, err := a.resolve(cmd.Context(), true)
if err != nil {
@@ -188,7 +188,7 @@ $ gt workflow run nightly --follow`,
Annotations: map[string]string{"gt.arguments": workflowArguments},
RunE: func(cmd *cobra.Command, args []string) error {
if follow && a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--follow cannot be combined with --json or --jq"))
return clierr.Wrap(clierr.Usage, errors.New("--follow cannot be combined with --json, --jq or --csv"))
}
if interval <= 0 || timeout <= 0 {
return clierr.Wrap(clierr.Usage, errors.New("--interval and --timeout must be positive"))
+36 -11
View File
@@ -80,8 +80,10 @@ type options struct {
host, user, repo, cwd, remote string
sudo string
json, jq string
noInput, interactive, yes bool
debug bool
// csv holds the --csv fields; checkOutputFlags copies them to json, which selects them.
csv string
noInput, interactive, yes bool
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.
@@ -190,6 +192,8 @@ func newRoot(deps Dependencies) (*cobra.Command, *application) {
flags.StringVar(&a.options.json, "json", "", "Output JSON with the specified comma-separated `fields`, or all fields")
flags.Lookup("json").NoOptDefVal = "*"
flags.StringVarP(&a.options.jq, "jq", "q", "", "Filter JSON output using a jq `expression`; implies --json")
flags.StringVar(&a.options.csv, "csv", "", "Output CSV with the specified comma-separated `fields`, or all fields")
flags.Lookup("csv").NoOptDefVal = "*"
flags.BoolVar(&a.options.noInput, "no-input", false, "Disable prompts and implicit editor/browser interactions")
flags.BoolVar(&a.options.interactive, "interactive", false, "Allow prompts with machine output")
flags.BoolVarP(&a.options.yes, "yes", "y", false, "Accept confirmations without prompting")
@@ -200,6 +204,7 @@ func newRoot(deps Dependencies) (*cobra.Command, *application) {
_ = root.RegisterFlagCompletionFunc("remote", a.completeRemotes)
_ = root.RegisterFlagCompletionFunc("cwd", completeDirectories)
_ = root.RegisterFlagCompletionFunc("json", completeJSONFields)
_ = root.RegisterFlagCompletionFunc("csv", completeJSONFields)
root.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
if err := a.checkOutputFlags(cmd); err != nil {
return err
@@ -342,11 +347,22 @@ func editDistance(a, b string) int {
return row[len(b)]
}
// checkOutputFlags validates --json and --jq before a command runs. --jq alone selects every field,
// except on commands that filter their raw JSON themselves (annotation gt.rawjson).
// checkOutputFlags validates --json, --jq and --csv before a command runs. --jq alone selects every
// field, except on commands that filter their raw JSON themselves (annotation gt.rawjson). --csv
// selects its fields like --json, so that every JSON output path writes CSV instead.
func (a *application) checkOutputFlags(cmd *cobra.Command) error {
selected := ""
switch {
case cmd.Flags().Changed("csv"):
for _, other := range []string{"json", "jq"} {
if cmd.Flags().Changed(other) {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--csv cannot be combined with --%s", other))
}
}
if slices.ContainsFunc(strings.Split(a.options.csv, ","), func(name string) bool { return strings.TrimSpace(name) == "" }) {
return clierr.Wrap(clierr.Usage, errors.New("--csv field names cannot be empty; use --csv alone for every field"))
}
selected, a.options.json = "--csv", a.options.csv
case cmd.Flags().Changed("json"):
if a.options.json == "" {
return clierr.Wrap(clierr.Usage, errors.New("--json= requires field names; use --json alone for every field"))
@@ -359,7 +375,7 @@ func (a *application) checkOutputFlags(cmd *cobra.Command) error {
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s; %s is not supported", reason, selected))
}
if flag := cmd.Flags().Lookup("web"); flag != nil && flag.Value.String() == "true" && (a.options.json != "" || a.options.jq != "") {
return clierr.Wrap(clierr.Usage, errors.New("--web cannot be combined with --json or --jq"))
return clierr.Wrap(clierr.Usage, errors.New("--web cannot be combined with --json, --jq or --csv"))
}
return clierr.Wrap(clierr.Usage, terminal.ValidateOutput(a.options.json, a.options.jq, commandOutputFields(cmd)))
}
@@ -500,16 +516,25 @@ 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 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.
// outputFlag names the flag that selected machine output, for usage errors about its fields.
func (a *application) outputFlag() string {
if a.options.csv != "" {
return "--csv"
}
return "--json"
}
// joinJSONFields accepts `--json number,title` like `--json=number,title`, and --csv likewise. The word
// stays a positional 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] == "--" {
break
}
if args[i] != "--json" || i+1 >= len(args) || !jsonFieldList.MatchString(args[i+1]) {
if (args[i] != "--json" && args[i] != "--csv") || i+1 >= len(args) || !jsonFieldList.MatchString(args[i+1]) {
continue
}
// A word that names a subcommand at this position is the command, as in `gt --json repo view`.
@@ -520,7 +545,7 @@ func joinJSONFields(root *cobra.Command, args []string) []string {
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:])
args = slices.Concat(args[:i], []string{args[i] + "=" + args[i+1]}, args[i+2:])
}
return args
}
+10
View File
@@ -131,6 +131,8 @@ func TestJoinJSONFields(t *testing.T) {
{[]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"}},
{[]string{"issue", "list", "--csv", "number,title"}, []string{"issue", "list", "--csv=number,title"}},
{[]string{"release", "view", "--csv", "v1"}, []string{"release", "view", "--csv", "v1"}},
} {
deps, _, _ := testDeps(t)
require.Equal(t, tc.want, joinJSONFields(NewRoot(deps), tc.args), tc.args)
@@ -165,6 +167,14 @@ func TestJSONFieldsAcceptSpaceSeparatedValue(t *testing.T) {
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"search", "repo", "--json", "foo"}))
require.Contains(t, out.String(), `"full_name":"alice/foo"`)
for _, args := range [][]string{{"org", "list", "--csv", "id,name"}, {"--csv=id,name", "org", "list"}} {
out.Reset()
require.NoError(t, Execute(context.Background(), deps, args), args)
require.Equal(t, "id,name\n1,team\n", out.String(), args)
}
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"org", "list", "--csv"}))
require.Contains(t, out.String(), ",Team,")
}
func TestSudoSendsHeaderAfterIdentityCheck(t *testing.T) {
+1 -1
View File
@@ -332,7 +332,7 @@ $ gt %[1]s comment list %[2]s`, words.group, words.example), Annotations: map[st
return clierr.Wrap(clierr.Usage, fmt.Errorf("--attachment cannot be combined with %s", last[0]))
}
if deleteLast && a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--delete-last cannot be combined with --json or --jq"))
return clierr.Wrap(clierr.Usage, errors.New("--delete-last cannot be combined with --json, --jq or --csv"))
}
if err := a.validateComment(cmd, &flags, !deleteLast); err != nil {
return err
+1 -1
View File
@@ -227,7 +227,7 @@ func TestCommentGroupCommentsLikeGh(t *testing.T) {
{[]string{"issue", "comment", "craete", "1"}, `unknown command "craete" for "gt issue comment"; did you mean create?`},
{[]string{"issue", "comment", "-b", "x"}, "missing issue number"},
{[]string{"issue", "comment", "1", "--edit-last", "--delete-last"}, "--edit-last cannot be combined with --delete-last"},
{[]string{"issue", "comment", "1", "--delete-last", "--json"}, "--delete-last cannot be combined with --json or --jq"},
{[]string{"issue", "comment", "1", "--delete-last", "--json"}, "--delete-last cannot be combined with --json, --jq or --csv"},
{[]string{"issue", "comment", "1", "--delete-last", "--body-file", "x"}, "--delete-last cannot be combined with --body-file"},
{[]string{"issue", "comment", "1"}, "issue comment requires --body, --body-file or --editor"},
{[]string{"pr", "comment", "1", "-b", "x"}, "#1 in alice/project is an issue, not a pull request; use gt issue comment 1"},
+5 -5
View File
@@ -131,7 +131,7 @@ func mergeCompletions(completers ...cobra.CompletionFunc) cobra.CompletionFunc {
}
}
// completeJSONFields completes the comma-separated fields that --json can select for the command.
// completeJSONFields completes the comma-separated fields that --json and --csv can select for the command.
var completeJSONFields = commaSeparated(func(cmd *cobra.Command, _ []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
if cmd.Annotations["gt.text"] != "" || cmd.Annotations["gt.group"] != "" {
return nil, cobra.ShellCompDirectiveNoFileComp
@@ -139,11 +139,11 @@ var completeJSONFields = commaSeparated(func(cmd *cobra.Command, _ []string, toC
return matching(commandOutputFields(cmd), toComplete), cobra.ShellCompDirectiveNoFileComp
})
// completeJSONValue completes the word after a bare --json as its fields. Without this, cobra completes
// that word as a positional argument, because the value of --json is optional.
// completeJSONValue completes the word after a bare --json or --csv as its fields. Without this, cobra
// completes that word as a positional argument, because the value of these flags is optional.
func completeJSONValue(args []string) []string {
if n := len(args); n >= 2 && args[n-2] == "--json" && !strings.HasPrefix(args[n-1], "-") {
return slices.Concat(args[:n-2], []string{"--json=" + args[n-1]})
if n := len(args); n >= 2 && (args[n-2] == "--json" || args[n-2] == "--csv") && !strings.HasPrefix(args[n-1], "-") {
return slices.Concat(args[:n-2], []string{args[n-2] + "=" + args[n-1]})
}
return args
}
+1
View File
@@ -115,6 +115,7 @@ func TestJSONFieldCompletion(t *testing.T) {
for args, want := range map[string][]string{
"issue list --json number,ti": {"number,title"},
"issue list --json=num": {"number"},
"issue list --csv number,ti": {"number,title"},
"issue list --json=state,ti": {"state,title"},
"pr view --json head_r": {"head_remote_deleted", "head_repo"},
"version --json ": {},
+2 -2
View File
@@ -254,7 +254,7 @@ $ gt config get ssh_key --host https://gitea.com --user alice`,
if a.options.json != "*" {
for field := range strings.SplitSeq(a.options.json, ",") {
if field = strings.TrimSpace(field); field != "" && field != args[0] {
return clierr.Wrap(clierr.Usage, fmt.Errorf("--json field %s cannot be combined with key %s", field, args[0]))
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s field %s cannot be combined with key %s", a.outputFlag(), field, args[0]))
}
}
}
@@ -749,7 +749,7 @@ $ gt alias set il "issue list --assignee @me" --clobber`,
if a.options.json != "" {
names := slices.Sorted(maps.Keys(s.Preferences.Aliases))
if len(names) == 0 && a.options.json != "*" {
return clierr.Wrap(clierr.Usage, errors.New("--json with field names requires aliases; none are defined"))
return clierr.Wrap(clierr.Usage, fmt.Errorf("%s with field names requires aliases; none are defined", a.outputFlag()))
}
if err := terminal.ValidateOutput(a.options.json, "", names); err != nil {
return clierr.Wrap(clierr.Usage, err)
+3
View File
@@ -30,6 +30,9 @@ func TestConfigReportsEffectivePreferenceSourcesWithoutAuthentication(t *testing
require.NoError(t, Execute(context.Background(), deps, []string{"config", "get", "git_protocol", "--show-source", "--json"}))
require.JSONEq(t, `{"git_protocol":{"value":"ssh","source":"hosts.yml https://env.example.org/base"}}`, out.String())
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"config", "get", "git_protocol", "--csv"}))
require.Equal(t, "git_protocol\nssh\n", out.String())
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"config", "get", "default_host", "--host", "https://flag.example.org", "--show-source", "--json"}))
require.JSONEq(t, `{"default_host":{"value":"https://flag.example.org","source":"--host"}}`, out.String())
snapshot, err := deps.Settings.Load()
+23 -15
View File
@@ -96,7 +96,7 @@ func (a *application) writeHelp(cmd *cobra.Command, _ []string) {
}
section("LEARN MORE", "Use `gt <command> <subcommand> --help` for more information about a command.\n"+
"Read `gt help environment` for global flags and environment variables.\n"+
"Read `gt help formatting` for --json and --jq, and `gt help exit-codes` for exit codes.")
"Read `gt help formatting` for --json, --jq and --csv, and `gt help exit-codes` for exit codes.")
_, _ = io.WriteString(cmd.OutOrStdout(), strings.TrimRight(page.String(), "\n")+"\n")
}
@@ -161,7 +161,7 @@ func availableCommands(cmd *cobra.Command) []commandList {
}
// helpFlags renders the flags of cmd, counting parents' persistent flags such as --org as its own, and
// the global flags that apply to it: --repo, --remote and --cwd, --json and --jq, and --yes.
// the global flags that apply to it: --repo, --remote and --cwd, --json, --jq and --csv, and --yes.
func helpFlags(cmd *cobra.Command) (local, inherited string) {
globals := cmd.Root().PersistentFlags()
var own []*pflag.Flag
@@ -187,7 +187,7 @@ func helpFlags(cmd *cobra.Command) (local, inherited string) {
}
// sharedFlagNames are the global flags that help and the manual list only where they apply.
var sharedFlagNames = []string{"repo", "remote", "cwd", "json", "jq", "yes"}
var sharedFlagNames = []string{"repo", "remote", "cwd", "json", "jq", "csv", "yes"}
// sharedFlags reports which of sharedFlagNames apply to cmd.
func sharedFlags(cmd *cobra.Command) map[string]bool {
@@ -196,7 +196,7 @@ func sharedFlags(cmd *cobra.Command) map[string]bool {
// 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"] != ""}
return map[string]bool{"repo": selects, "remote": selects && !runsExtension(cmd), "cwd": repo, "json": outputsJSON(cmd), "jq": outputsJSON(cmd) || cmd.Annotations["gt.rawjson"] != "", "csv": outputsJSON(cmd), "yes": cmd.Annotations["gt.confirm"] != ""}
}
// helpSection is a titled section of a help page.
@@ -219,20 +219,20 @@ func runsExtension(cmd *cobra.Command) bool {
return cmd.Annotations["gt.extension"] == "true" || cmd.CommandPath() == "gt extension exec"
}
// outputsJSON reports whether the --json flag applies to cmd.
// outputsJSON reports whether the --json and --csv flags apply to cmd.
func outputsJSON(cmd *cobra.Command) bool {
return cmd.Annotations["gt.text"] == "" && cmd.Annotations["gt.group"] == "" && (commandOutputFields(cmd) != nil || cmd.Annotations["gt.jsonfields"] != "")
}
// flagUsages renders flags in order as aligned usage lines without their common indentation. The
// optional --json value and the help flag read as in gh: "--json fields", "Show help for command".
// optional --json and --csv values and the help flag read as in gh: "--json fields", "Show help for command".
func flagUsages(flags []*pflag.Flag) string {
set := pflag.NewFlagSet("help", pflag.ContinueOnError)
set.SortFlags = false
for _, flag := range flags {
shown := *flag
switch flag.Name {
case "json":
case "json", "csv":
shown.NoOptDefVal = ""
case "help":
shown.Usage = "Show help for command"
@@ -434,17 +434,25 @@ Policy: extensions (enabled or disabled), extension_hosts and extension_owners i
restrict extensions for you. An administrator sets the same, and extension_credentials: denied,
in /etc/gitea-cli/policy.yml (%ProgramData%\gitea-cli\policy.yml on Windows), which you
cannot loosen.`},
{Use: "formatting", Short: "JSON output with --json and --jq", Long: `gt prints text for people by default. Scripts should use JSON: the columns and
wording of text output may change between releases.
{Use: "formatting", Short: "JSON and CSV output with --json, --jq and --csv", Long: `gt prints text for people by default. Scripts should use JSON or CSV: the columns
and wording of text output may change between releases.
--json print every field
--json FIELDS print only the comma-separated FIELDS, such as --json number,title
-q, --jq EXPR filter the JSON with a jq expression; implies --json
--csv print every field as CSV
--csv FIELDS print only the comma-separated FIELDS as CSV, such as --csv number,title
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. 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.
The JSON FIELDS section of a command's help lists its fields, which --csv selects too,
and shell completion offers them after --json and --csv. An unknown field reports the
available ones. A word after --json or --csv 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.
--csv prints a header row of the field names, then one row per item; a command that
returns one item prints one row. Strings print as they are, null as an empty cell,
and numbers, booleans, objects and arrays as compact JSON. --csv cannot be combined
with --json or --jq.
--jq runs inside gt, so jq does not need to be installed. String results print
without quotes:
@@ -453,7 +461,7 @@ without quotes:
Some fields cost extra requests, such as the reviewers of pr list, the blocked_by and blocks
of issue view and issue edit, and the visibility of org member list. gt makes them only when
the output includes the field: --json names it, or --json selects every field and the --jq
the output includes the field: --json or --csv names it, or selects every field and the --jq
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.
@@ -463,7 +471,7 @@ needs one shape passes one argument per call, or several and reads the array, su
--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.`},
Commands that return no resource, such as deletes, reject --json and --csv.`},
}
for _, topic := range topics {
topic.Hidden, topic.Annotations = true, map[string]string{topicAnnotation: "true"}
+7 -3
View File
@@ -71,10 +71,14 @@ func (a *application) writeHuman(cmd *cobra.Command, text string) error {
return fmt.Errorf("pager failed; check %s: %w", source, pagerErr.Err)
}
// writeJSON writes v as JSON, filtered by --json fields and --jq.
// writeJSON writes v as JSON, filtered by --json fields and --jq, or as CSV with --csv.
func (a *application) writeJSON(cmd *cobra.Command, v any) error {
pretty := a.deps.Streams.OutTTY
return terminal.JSONOutput{Fields: a.options.json, Allowed: commandOutputFields(cmd), Query: a.options.jq, Pretty: pretty, Color: pretty && a.colorEnabled()}.Write(cmd.OutOrStdout(), v)
pretty, csv := a.deps.Streams.OutTTY, a.options.csv != ""
allowed := commandOutputFields(cmd)
if csv && cmd.Annotations["gt.jsonfields"] != "" {
allowed = nil // Fields that vary, such as config get's key, make the result's keys the columns.
}
return terminal.JSONOutput{Fields: a.options.json, Allowed: allowed, Query: a.options.jq, Pretty: pretty, Color: pretty && a.colorEnabled(), CSV: csv}.Write(cmd.OutOrStdout(), v)
}
// listSpec describes how a list command shows its items to people.
+1 -1
View File
@@ -181,7 +181,7 @@ only when the output includes them (see gt help formatting).`, Example: `$ gt is
$ gt issue view 12 --comments
$ gt issue view https://gitea.com/OWNER/REPO/issues/12 --web`, Annotations: map[string]string{"gt.arguments": issueArguments}, Args: argsExact(1), RunE: func(cmd *cobra.Command, args []string) error {
if comments && a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--comments cannot be combined with --json or --jq; use gt issue comment list <number> --json"))
return clierr.Wrap(clierr.Usage, errors.New("--comments cannot be combined with --json, --jq or --csv; use gt issue comment list <number> --json"))
}
target, n, err := a.resolveRef(cmd, args[0], issueRef)
if err != nil {
+1 -1
View File
@@ -34,7 +34,7 @@ $ gt label export -R alice/old | gt label import - -R alice/new`, Args: argsExac
}
if a.options.json != "" {
toStdout := output == "" || output == "-"
return terminal.JSONOutput{Fields: a.options.json, Allowed: commandOutputFields(cmd), Query: a.options.jq, Safe: toStdout && a.deps.Streams.OutTTY}.Write(destination, items)
return terminal.JSONOutput{Fields: a.options.json, Allowed: commandOutputFields(cmd), Query: a.options.jq, Safe: toStdout && a.deps.Streams.OutTTY, CSV: a.options.csv != ""}.Write(destination, items)
}
var text strings.Builder
for _, item := range items {
+1 -1
View File
@@ -91,6 +91,6 @@ func TestManIncludesHelpTopicsButNotHelpCommands(t *testing.T) {
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.Contains(t, out.String(), ".EX\n --csv fields", "the flags render as one block")
require.NotContains(t, out.String(), ".PP\n-q, --jq")
}
+4 -1
View File
@@ -239,12 +239,15 @@ of up to 5 minutes.`,
fmt.Fprintf(cmd.ErrOrStderr(), "Watching %s %s; press Ctrl-C to stop\n", notificationsWith(opts.Statuses), s.where)
}
out := terminal.SafeWriter(cmd.OutOrStdout(), d.TTY, d.Color)
headed := false
err = s.Watch(ctx, listed, interval, func(items []services.Notification) error {
if a.options.json != "" {
for _, item := range items {
if err := (terminal.JSONOutput{Fields: a.options.json, Allowed: commandOutputFields(cmd), Query: a.options.jq, Safe: d.TTY}).Write(cmd.OutOrStdout(), item); err != nil {
csv := a.options.csv != ""
if err := (terminal.JSONOutput{Fields: a.options.json, Allowed: commandOutputFields(cmd), Query: a.options.jq, Safe: d.TTY, CSV: csv, NoHeader: headed}).Write(cmd.OutOrStdout(), item); err != nil {
return err
}
headed = csv
}
return nil
}
+4
View File
@@ -118,6 +118,10 @@ func TestNotificationWatchStreamsOneJSONObjectPerLine(t *testing.T) {
deps, out, _ := serverDeps(t, server.URL)
require.NoError(t, Execute(context.Background(), deps, []string{"notification", "watch", "--json", "id,title", "--interval", "20ms", "--timeout", "500ms"}))
require.Equal(t, "{\"id\":1,\"title\":\"First\"}\n{\"id\":2,\"title\":\"Second\"}\n", out.String())
polls.Store(0)
out.Reset()
require.NoError(t, Execute(context.Background(), deps, []string{"notification", "watch", "--csv", "id,title", "--interval", "20ms", "--timeout", "500ms"}))
require.Equal(t, "id,title\n1,First\n2,Second\n", out.String())
}
func TestNotificationWatchFailsWhenTheInstanceDoesNotAnswer(t *testing.T) {
+2 -2
View File
@@ -98,7 +98,7 @@ func (a *application) runPullCreate(cmd *cobra.Command, f *pullCreateFlags) (run
}
if f.agit {
if a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--json/--jq cannot be combined with --agit; AGit creates the pull request through git push"))
return clierr.Wrap(clierr.Usage, errors.New("--json, --jq or --csv cannot be combined with --agit; AGit creates the pull request through git push"))
}
if f.web {
return clierr.Wrap(clierr.Usage, errors.New("--web cannot be combined with --agit; AGit creates the pull request through git push, without a branch to compare"))
@@ -545,7 +545,7 @@ func (a *application) createPullInteractively(cmd *cobra.Command, snapshot setti
return clierr.Wrap(clierr.Usage, errors.New("pr create requires a target branch: the repository has no default branch"))
}
if values.Agit && a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--json/--jq cannot be combined with AGit create; AGit creates the pull request through git push"))
return clierr.Wrap(clierr.Usage, errors.New("--json, --jq or --csv cannot be combined with AGit create; AGit creates the pull request through git push"))
}
base := &pullBase{branch: values.Base, repo: &loaded.Base}
if values.AsDraft {
+1 -1
View File
@@ -188,7 +188,7 @@ func (a *application) pullViewCommand() *cobra.Command {
var web, comments bool
cmd := &cobra.Command{Use: "view [<number> | <url> | <branch>]", Short: "View a pull request", Annotations: pullArgumentsAnnotation(nil), Args: usageArgs(cobra.MaximumNArgs(1)), RunE: func(cmd *cobra.Command, args []string) error {
if comments && a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--comments cannot be combined with --json or --jq; use gt pr comment list <number> --json or gt pr review list <number> --json"))
return clierr.Wrap(clierr.Usage, errors.New("--comments cannot be combined with --json, --jq or --csv; use gt pr comment list <number> --json or gt pr review list <number> --json"))
}
t, n, err := a.pullSelectorAny(cmd, args)
if err != nil {
+1 -1
View File
@@ -77,7 +77,7 @@ $ gt time list --mine --since 168h`, Args: argsExact(0), RunE: func(cmd *cobra.C
return clierr.Wrap(clierr.Usage, fmt.Errorf("--mine cannot be combined with %s", sources[0]))
}
if total && a.options.json != "" {
return clierr.Wrap(clierr.Usage, errors.New("--total cannot be combined with --json or --jq; sum JSON with --jq 'map(.seconds) | add // 0'"))
return clierr.Wrap(clierr.Usage, errors.New("--total cannot be combined with --json, --jq or --csv; sum JSON with --jq 'map(.seconds) | add // 0'"))
}
var err error
if opts.Since, opts.Before, err = tracked.parse(a.deps.Now()); err != nil {
+10 -3
View File
@@ -52,6 +52,13 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"api", "user", "-X", "invalid/method"}, "invalid HTTP method"},
{[]string{"alias", "delete", "co", "--json"}, "alias deletion does not return a resource"},
{[]string{"alias", "list", "--json", "foo"}, "--json with field names requires aliases; none are defined"},
{[]string{"alias", "delete", "co", "--csv"}, "alias deletion does not return a resource; --csv is not supported"},
{[]string{"alias", "list", "--csv", "foo"}, "--csv with field names requires aliases; none are defined"},
{[]string{"issue", "list", "--csv", "--json"}, "--csv cannot be combined with --json"},
{[]string{"issue", "list", "--csv=number", "--jq", "."}, "--csv cannot be combined with --jq"},
{[]string{"issue", "list", "--csv="}, "--csv field names cannot be empty; use --csv alone for every field"},
{[]string{"issue", "list", "--csv=number, "}, "--csv field names cannot be empty; use --csv alone for every field"},
{[]string{"issue", "list", "--csv", "titel"}, "unknown JSON field \"titel\""},
{[]string{"auth", "status", "--json=token"}, "unknown JSON field \"token\""},
{[]string{"auth", "logout", "", "--yes"}, "account cannot be empty"},
{[]string{"auth", "switch", " "}, "account cannot be empty"},
@@ -202,7 +209,7 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]string{"pr", "create", "--milestone=-1"}, "--milestone must be a milestone title or a positive ID"},
{[]string{"pr", "create", "--assignee", "alice, "}, "assignee names cannot be empty"},
{[]string{"pr", "create", "--label", "bug, "}, "label names cannot be empty"},
{[]string{"pr", "create", "--agit", "--json", "--title", "x", "--no-input"}, "--json/--jq cannot be combined with --agit"},
{[]string{"pr", "create", "--agit", "--json", "--title", "x", "--no-input"}, "--json, --jq or --csv cannot be combined with --agit"},
{[]string{"pr", "create", "--topic", "x", "--title", "x", "--no-input"}, "--topic requires --agit"},
{[]string{"pr", "create", "--agit", "--topic", "main", "--base", "main", "--title", "x", "--no-input"}, "the AGit topic main must differ from the base branch"},
{[]string{"pr", "checks", "1", "--interval", "1s"}, "--interval requires --watch"},
@@ -374,7 +381,7 @@ func TestUsageErrorsPrecedeRequests(t *testing.T) {
{[]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 cannot be combined with --json or --jq"},
{[]string{"time", "list", "--total", "--json"}, "--total cannot be combined with --json, --jq or --csv"},
{[]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"},
@@ -417,7 +424,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", "run", "ci.yml", "--follow", "--json"}, "--follow cannot be combined with --json, --jq or --csv"},
{[]string{"workflow", "view", ""}, "workflow cannot be empty"},
{[]string{"workflow", "view", "ci", "--ref", "main"}, "--ref requires --yaml"},
} {
+83 -1
View File
@@ -5,6 +5,7 @@ package terminal
import (
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
@@ -33,6 +34,10 @@ type JSONOutput struct {
Safe bool
// Color highlights pretty JSON keys and values.
Color bool
// CSV writes the selected objects as CSV instead of JSON; Query must be empty.
CSV bool
// NoHeader leaves out the CSV header row, for rows that continue earlier output.
NoHeader bool
}
// Write projects explicit result fields of value, applies the jq filter, and writes the results.
@@ -45,7 +50,8 @@ func (o JSONOutput) Write(w io.Writer, value any) error {
if err := json.Unmarshal(data, &normalized); err != nil {
return err
}
if names := fieldNames(o.Fields); names != nil {
names := fieldNames(o.Fields)
if names != nil {
selectFields := func(item any) (any, error) {
object, ok := item.(map[string]any)
if !ok {
@@ -79,6 +85,9 @@ func (o JSONOutput) Write(w io.Writer, value any) error {
}
}
}
if o.CSV {
return o.writeCSV(w, normalized, names)
}
if o.Query == "" {
return o.encode(w, normalized)
}
@@ -133,6 +142,79 @@ func (o JSONOutput) encode(w io.Writer, value any) error {
return err
}
// writeCSV writes a header row of the field names, then one row per object of value. Without selected
// names, the columns are the allowed fields followed by any other keys of the objects.
func (o JSONOutput) writeCSV(w io.Writer, value any, names []string) error {
items, ok := value.([]any)
if !ok {
items = []any{value}
}
objects := make([]map[string]any, len(items))
for i, item := range items {
if objects[i], ok = item.(map[string]any); !ok {
return errors.New("CSV output requires resource objects")
}
}
if names == nil {
var extra []string
for _, object := range objects {
for key := range object {
if !slices.Contains(o.Allowed, key) && !slices.Contains(extra, key) {
extra = append(extra, key)
}
}
}
slices.Sort(extra)
names = slices.Concat(o.Allowed, extra)
}
writer := csv.NewWriter(w)
if !o.NoHeader {
if err := writer.Write(names); err != nil {
return err
}
}
for _, object := range objects {
record := make([]string, len(names))
for i, name := range names {
cell, err := o.csvCell(object[name])
if err != nil {
return err
}
record[i] = cell
}
if err := writer.Write(record); err != nil {
return err
}
}
writer.Flush()
return writer.Error()
}
// csvCell writes a string as it is, null as an empty cell and any other value as compact JSON.
func (o JSONOutput) csvCell(value any) (string, error) {
safe := o.Pretty || o.Safe
switch value := value.(type) {
case nil:
return "", nil
case string:
if safe {
return SafeText(value), nil
}
return value, nil
}
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(value); err != nil {
return "", err
}
text := strings.TrimSuffix(buf.String(), "\n")
if safe {
text = escapeJSONText(text)
}
return text, nil
}
// IndentJSON formats JSON text for a terminal like Write with Pretty, but keeps the key order of the
// text: indented, sanitized, ending with a newline and, with color, highlighted.
func IndentJSON(data []byte, color bool) (string, error) {
+18
View File
@@ -82,3 +82,21 @@ func TestJSONOutputIsIndentedAndColoredForTerminals(t *testing.T) {
require.NoError(t, JSONOutput{Query: ".title"}.Write(&out, value[0]))
require.Equal(t, "a \u202e\x1b[31mb\n", out.String())
}
func TestCSVOutput(t *testing.T) {
var out bytes.Buffer
value := []map[string]any{
{"number": 1, "title": "a, \"b\"\nc", "done": true, "due": nil, "labels": []any{map[string]any{"name": "<bug>"}}},
{"number": 2, "title": "\x1b[31mred\u202e", "done": false, "labels": []any{}},
}
require.NoError(t, JSONOutput{Fields: "number,title,due,labels,done", Allowed: []string{"done", "due", "labels", "number", "title"}, CSV: true}.Write(&out, value))
require.Equal(t, "number,title,due,labels,done\n1,\"a, \"\"b\"\"\nc\",,\"[{\"\"name\"\":\"\"<bug>\"\"}]\",true\n2,\x1b[31mred\u202e,,[],false\n", out.String())
out.Reset()
// Every field: the documented ones, then any others, a single object as one row, sanitized for a terminal.
require.NoError(t, JSONOutput{Allowed: []string{"title", "milestone"}, CSV: true, Pretty: true}.Write(&out, map[string]any{"title": value[1]["title"], "zz": []any{"\u009b"}}))
require.Equal(t, "title,milestone,zz\n[31mred,,\"[\"\"\\u009b\"\"]\"\n", out.String())
out.Reset()
require.NoError(t, JSONOutput{Fields: "number", CSV: true, NoHeader: true}.Write(&out, value))
require.Equal(t, "1\n2\n", out.String())
require.EqualError(t, JSONOutput{CSV: true}.Write(&out, []string{"x"}), "CSV output requires resource objects")
}