GeezerVison is showing github.com — feat(platform): spec alignment, internal/common, structured output, e… · ucloud/ucloud-cli@0a3f8d7
File treeExpand file treeCollapse file tree Open diff view settings examples/product_onboarding products/udb/internal/mysql
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: .github/workflows/pr-gate.yml +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 40 | 40 | echo "Changed files:"; echo "$FILES" | 41 | 41 |
| 42 | 42 | # 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$)' | 44 | 44 | touches_protected=$(echo "$FILES" | grep -E "$PROTECTED" || true) | 45 | 45 |
| 46 | 46 | # Product scope: all changed files under a single products/<name>/ ? | |
Collapse file Copy file name to clipboardExpand all lines: cmd/output_format_test.go +57Lines changed: 57 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,6 +2,7 @@ package cmd | 2 | 2 |
| 3 | 3 | import ( | 4 | 4 | "bytes" | | 5 | + "os" | 5 | 6 | "testing" | 6 | 7 |
| 7 | 8 | "github.com/ucloud/ucloud-cli/pkg/cli" | @@ -80,3 +81,59 @@ func TestDecideOutputFormat(t *testing.T) { | 80 | 81 | }) | 81 | 82 | } | 82 | 83 | } | | 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 Copy file name to clipboardExpand all lines: cmd/root.go +33-2Lines changed: 33 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -22,6 +22,7 @@ import ( | 22 | 22 | "strings" | 23 | 23 |
| 24 | 24 | "github.com/spf13/cobra" | | 25 | + "github.com/spf13/pflag" | 25 | 26 |
| 26 | 27 | "github.com/ucloud/ucloud-cli/base" | 27 | 28 | "github.com/ucloud/ucloud-cli/pkg/cli" | @@ -115,7 +116,7 @@ Use "{{.CommandPath}} [command] --help" for more information about a command.{{e | 115 | 116 | const usageTmpl = `Usage:{{if .Runnable}} | 116 | 117 | {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} [command] {{if $size:=len .Commands}} | 117 | 118 | {{"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}} | 119 | 120 |
| 120 | 121 | Use "{{.CommandPath}} --help" for details.{{end}} | 121 | 122 | ` | @@ -136,9 +137,16 @@ func newSchemaCmd() *cobra.Command { | 136 | 137 | } | 137 | 138 | } | 138 | 139 |
| | 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 | + | 139 | 146 | func addChildren(root *cobra.Command) { | 140 | 147 | addPlatformCommands(root) | 141 | | - addProductCommands(root, registeredProducts(), buildContext()) | | 148 | + productCtx = buildContext() | | 149 | + addProductCommands(root, registeredProducts(), productCtx) | 142 | 150 | applyGlobalOverrideFlags(root) | 143 | 151 | } | 144 | 152 |
| @@ -258,6 +266,21 @@ func Execute() { | 258 | 266 | } | 259 | 267 |
| 260 | 268 | 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 | + | 261 | 284 | //-1表示不覆盖配置文件中的MaxRetryTimes参数 | 262 | 285 | global.MaxRetryTimes = -1 | 263 | 286 | for idx, arg := range os.Args { | @@ -302,6 +325,14 @@ func resetHelpFunc(cmd *cobra.Command) { | 302 | 325 | } | 303 | 326 |
| 304 | 327 | 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 | + | 305 | 336 | flags := cmd.Flags() | 306 | 337 | project, err := flags.GetString("project-id") | 307 | 338 | if err == nil { | |
Collapse file Copy file name to clipboard +56Lines changed: 56 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 | +} |
|