Skip to content

Commit 4522742

Browse files
committed
etcdctl: hide global flags
Signed-off-by: hwdef <[email protected]>
1 parent 90653b3 commit 4522742

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package command
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/spf13/cobra"
7+
"github.com/spf13/pflag"
8+
)
9+
10+
func NewOptionsCommand(rootCmd *cobra.Command) *cobra.Command {
11+
cmd := &cobra.Command{
12+
Use: "options",
13+
Short: "Show the global command-line flags",
14+
Run: func(cmd *cobra.Command, args []string) {
15+
fs := unhideCopy(rootCmd.PersistentFlags())
16+
fmt.Fprintf(cmd.OutOrStdout(), "The following options can be passed to any command:\n\n")
17+
fmt.Fprint(cmd.OutOrStdout(), fs.FlagUsages())
18+
},
19+
GroupID: groupUtilityID,
20+
}
21+
return cmd
22+
}
23+
24+
func unhideCopy(src *pflag.FlagSet) *pflag.FlagSet {
25+
out := pflag.NewFlagSet("global", pflag.ContinueOnError)
26+
src.VisitAll(func(f *pflag.Flag) {
27+
nf := *f
28+
nf.Hidden = false
29+
out.AddFlag(&nf)
30+
})
31+
return out
32+
}

etcdctl/ctlv3/ctl.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,12 @@
1616
package ctlv3
1717

1818
import (
19+
"fmt"
1920
"os"
2021
"time"
2122

2223
"github.com/spf13/cobra"
24+
"github.com/spf13/pflag"
2325

2426
"go.etcd.io/etcd/etcdctl/v3/ctlv3/command"
2527
"go.etcd.io/etcd/pkg/v3/cobrautl"
@@ -106,9 +108,13 @@ func init() {
106108
command.NewCheckCommand(),
107109
command.NewCompletionCommand(),
108110
command.NewDowngradeCommand(),
111+
command.NewOptionsCommand(rootCmd),
109112
)
110-
111113
command.SetHelpCmdGroup(rootCmd)
114+
115+
hideAllPersistentFlags()
116+
hideHelpFlag()
117+
addOptionsPrompt()
112118
}
113119

114120
func Start() error {
@@ -124,6 +130,28 @@ func MustStart() {
124130
}
125131
}
126132

133+
func hideAllPersistentFlags() {
134+
rootCmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
135+
rootCmd.PersistentFlags().MarkHidden(f.Name)
136+
})
137+
rootCmd.Flags().MarkHidden("help")
138+
}
139+
140+
func hideHelpFlag() {
141+
if rootCmd.Flags().Lookup("help") == nil {
142+
rootCmd.Flags().BoolP("help", "h", false, "help for "+rootCmd.Name())
143+
}
144+
_ = rootCmd.Flags().MarkHidden("help")
145+
}
146+
147+
func addOptionsPrompt() {
148+
defaultHelpFunc := rootCmd.HelpFunc()
149+
rootCmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
150+
defaultHelpFunc(cmd, args)
151+
fmt.Fprintln(cmd.OutOrStdout(), `Use "etcdctl options" for a list of global command-line options (applies to all commands).`)
152+
})
153+
}
154+
127155
func init() {
128156
cobra.EnablePrefixMatching = true
129157
}

0 commit comments

Comments
 (0)