GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(platform): spec alignment, internal/common, structured output, e… · ucloud/ucloud-cli@0a3f8d7

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .github/workflows
    • pr-gate.yml
  • cmd
    • output_format_test.go
    • root.go
    • usage_template_test.go
  • examples/product_onboarding
    • commands.go
    • completion.go
    • product.go
    • rows.go
  • hack/check-product
    • main.go
    • main_test.go
  • internal/common
    • common_test.go
    • format.go
    • fs.go
  • pkg
    • cli
      • context.go
      • describe.go
      • forward.go
      • forward_test.go
    • command
      • bind.go
      • bind_test.go
  • products/udb/internal/mysql
    • backup.go
    • cmd.go
    • conf.go
    • helpers.go
    • output.go
    • output_test.go
    • rows.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.github/workflows/pr-gate.yml‎

Copy file name to clipboardExpand all lines: .github/workflows/pr-gate.yml
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ jobs:
4040
echo "Changed files:"; echo "$FILES"
4141
4242
# Protected paths require platform review (cannot be auto-admitted).
43-
PROTECTED='^(\.github/workflows/|hack/|products\.yaml$|go\.mod$|go\.sum$|\.goreleaser\.yaml$|\.svu\.yaml$)'
43+
PROTECTED='^(\.github/workflows/|hack/|pkg/|products\.yaml$|go\.mod$|go\.sum$|\.goreleaser\.yaml$|\.svu\.yaml$)'
4444
touches_protected=$(echo "$FILES" | grep -E "$PROTECTED" || true)
4545
4646
# Product scope: all changed files under a single products/<name>/ ?
Collapse file

‎cmd/output_format_test.go‎

Copy file name to clipboardExpand all lines: cmd/output_format_test.go
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package cmd
22

33
import (
44
"bytes"
5+
"os"
56
"testing"
67

78
"github.com/ucloud/ucloud-cli/pkg/cli"
@@ -80,3 +81,59 @@ func TestDecideOutputFormat(t *testing.T) {
8081
})
8182
}
8283
}
84+
85+
// TestProductCtxFormatFinalize is a regression test for the bug where the
86+
// product cli.Context's output format was frozen at command-tree construction
87+
// time (buildContext, before cobra parses --output), so an explicit
88+
// `--output table` never took effect on product commands. The fix finalizes the
89+
// format in initialize() (PersistentPreRun) via productCtx.SetFormat after flag
90+
// parsing. This test mirrors that finalize step and asserts productCtx.Format()
91+
// tracks the PARSED --output value.
92+
//
93+
// buildContext() is used to populate productCtx directly instead of
94+
// addChildren(NewCmdRoot()): addChildren also constructs every platform command
95+
// and touches base globals as a side effect, none of which this test needs.
96+
// buildContext() only reads os.Stdin/Stdout/Stderr and base singletons; it
97+
// performs no API calls and runs offline.
98+
//
99+
// Without the fix (no SetFormat call after parsing), productCtx would stay at
100+
// the construction-time value (JSON, since test stdout is non-TTY) and the
101+
// table/yaml assertions below would fail.
102+
func TestProductCtxFormatFinalize(t *testing.T) {
103+
// Save and restore both the global flag and the package-level productCtx
104+
// so other tests are unaffected.
105+
origOutput := global.Output
106+
origCtx := productCtx
107+
t.Cleanup(func() {
108+
global.Output = origOutput
109+
productCtx = origCtx
110+
})
111+
112+
productCtx = buildContext()
113+
114+
tests := []struct {
115+
name string
116+
outputFlag string
117+
want cli.OutputFormat
118+
}{
119+
{name: "--output table", outputFlag: "table", want: cli.OutputTable},
120+
{name: "--output json", outputFlag: "json", want: cli.OutputJSON},
121+
{name: "--output yaml", outputFlag: "yaml", want: cli.OutputYAML},
122+
// Empty --output on a non-TTY stdout falls back to JSON.
123+
{name: "empty --output (non-TTY default)", outputFlag: "", want: cli.OutputJSON},
124+
}
125+
126+
for _, tc := range tests {
127+
t.Run(tc.name, func(t *testing.T) {
128+
global.Output = tc.outputFlag
129+
130+
// Mirror what initialize() (PersistentPreRun) now does after cobra
131+
// parses --output.
132+
productCtx.SetFormat(decideOutputFormat(os.Stdout))
133+
134+
if got := productCtx.Format(); got != tc.want {
135+
t.Errorf("productCtx.Format() = %v, want %v (--output=%q)", got, tc.want, tc.outputFlag)
136+
}
137+
})
138+
}
139+
}
Collapse file

‎cmd/root.go‎

Copy file name to clipboardExpand all lines: cmd/root.go
+33-2Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"strings"
2323

2424
"github.com/spf13/cobra"
25+
"github.com/spf13/pflag"
2526

2627
"github.com/ucloud/ucloud-cli/base"
2728
"github.com/ucloud/ucloud-cli/pkg/cli"
@@ -115,7 +116,7 @@ Use "{{.CommandPath}} [command] --help" for more information about a command.{{e
115116
const usageTmpl = `Usage:{{if .Runnable}}
116117
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} [command] {{if $size:=len .Commands}}
117118
{{"command may be" | printf "%-20s"}} {{range $index,$cmd:= .Commands}}{{if .IsAvailableCommand}}{{$cmd.Name}}{{if gt $size (add $index 1)}} | {{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableFlags}}
118-
{{"flags may be" | printf "%-20s"}} {{.Flags.FlagNames}}
119+
{{"flags may be" | printf "%-20s"}} {{flagNames .Flags}}
119120
120121
Use "{{.CommandPath}} --help" for details.{{end}}
121122
`
@@ -136,9 +137,16 @@ func newSchemaCmd() *cobra.Command {
136137
}
137138
}
138139

140+
// productCtx is the cli.Context shared by all product commands. Its output
141+
// format is finalized in initialize() (PersistentPreRun) after cobra parses
142+
// --output; buildContext() runs at tree-construction time, before flag parsing,
143+
// so the format it computes is provisional.
144+
var productCtx *cli.Context
145+
139146
func addChildren(root *cobra.Command) {
140147
addPlatformCommands(root)
141-
addProductCommands(root, registeredProducts(), buildContext())
148+
productCtx = buildContext()
149+
addProductCommands(root, registeredProducts(), productCtx)
142150
applyGlobalOverrideFlags(root)
143151
}
144152

@@ -258,6 +266,21 @@ func Execute() {
258266
}
259267

260268
func init() {
269+
// usageTmpl uses the `add` template function (the command-list separator).
270+
// The forked cobra registered it; upstream cobra (C2) does not, so without
271+
// this the usage template fails to parse ("function \"add\" not defined")
272+
// and panics whenever it renders — e.g. on any required-flag error. Register
273+
// it once here so usage rendering works for every command.
274+
cobra.AddTemplateFunc("add", func(a, b int) int { return a + b })
275+
// usageTmpl also used pflag's fork-only FlagSet.FlagNames; upstream pflag
276+
// has no such method, so the template errored at render time. Provide an
277+
// equivalent template func that lists the flag names.
278+
cobra.AddTemplateFunc("flagNames", func(fs *pflag.FlagSet) string {
279+
var names []string
280+
fs.VisitAll(func(f *pflag.Flag) { names = append(names, f.Name) })
281+
return strings.Join(names, ", ")
282+
})
283+
261284
//-1表示不覆盖配置文件中的MaxRetryTimes参数
262285
global.MaxRetryTimes = -1
263286
for idx, arg := range os.Args {
@@ -302,6 +325,14 @@ func resetHelpFunc(cmd *cobra.Command) {
302325
}
303326

304327
func initialize(cmd *cobra.Command) {
328+
// Finalize the product output format now that cobra has parsed --output.
329+
// buildContext() ran before flag parsing, so the format it set was
330+
// provisional (always JSON for non-TTY stdout, ignoring an explicit
331+
// --output). Recompute it here so `--output table` etc. take effect.
332+
if productCtx != nil {
333+
productCtx.SetFormat(decideOutputFormat(os.Stdout))
334+
}
335+
305336
flags := cmd.Flags()
306337
project, err := flags.GetString("project-id")
307338
if err == nil {
Collapse file

‎cmd/usage_template_test.go‎

Copy file name to clipboard
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package cmd
2+
3+
import (
4+
"strings"
5+
"testing"
6+
7+
"github.com/spf13/cobra"
8+
)
9+
10+
// TestUsageTemplateRenders is a regression test for the usageTmpl helper funcs.
11+
//
12+
// usageTmpl (cmd/root.go) uses two template functions that the forked
13+
// cobra/pflag provided but upstream does NOT:
14+
// - add: the command-list separator, `{{... (add $index 1)}}`
15+
// - flagNames: the flag-name list, which replaced the fork-only
16+
// `.Flags.FlagNames`
17+
//
18+
// Both are registered via cobra.AddTemplateFunc in init(). If either
19+
// registration is removed, rendering usageTmpl breaks: an unregistered `add`
20+
// makes the template fail to parse and panics; an unregistered `flagNames`
21+
// leaves a template-error string in the rendered output. This test renders the
22+
// usage template and fails on either symptom.
23+
func TestUsageTemplateRenders(t *testing.T) {
24+
root := NewCmdRoot()
25+
26+
// Two dummy subcommands with Run funcs so HasAvailableSubCommands is true:
27+
// the `add`/command-list block then renders, and the flags block calls
28+
// flagNames.
29+
root.AddCommand(&cobra.Command{
30+
Use: "dummyalpha",
31+
Run: func(c *cobra.Command, args []string) {},
32+
})
33+
root.AddCommand(&cobra.Command{
34+
Use: "dummybeta",
35+
Run: func(c *cobra.Command, args []string) {},
36+
})
37+
38+
// Renders usageTmpl. An unregistered `add` panics here (failing the test
39+
// naturally); an unregistered `flagNames` leaves a template-error string in
40+
// the output, caught by the assertions below.
41+
usage := root.UsageString()
42+
43+
// The command list rendered (proves the `add`/command-list block ran).
44+
for _, name := range []string{"dummyalpha", "dummybeta"} {
45+
if !strings.Contains(usage, name) {
46+
t.Errorf("usage output missing dummy command %q; command list did not render.\nusage:\n%s", name, usage)
47+
}
48+
}
49+
50+
// No template error leaked into the output (proves flagNames/add resolved).
51+
for _, bad := range []string{"template:", "not defined", "can't evaluate"} {
52+
if strings.Contains(usage, bad) {
53+
t.Errorf("usage output contains template error %q (a helper func is likely unregistered).\nusage:\n%s", bad, usage)
54+
}
55+
}
56+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.