libs/cli: clean up package (#7806)

This commit is contained in:
Sam Kleinman
2022-02-11 11:30:16 -05:00
committed by GitHub
parent 662c0aac9e
commit 9e59fc6924
6 changed files with 188 additions and 197 deletions
+46
View File
@@ -0,0 +1,46 @@
package commands
import (
"fmt"
"github.com/spf13/cobra"
)
// NewCompletionCmd returns a cobra.Command that generates bash and zsh
// completion scripts for the given root command. If hidden is true, the
// command will not show up in the root command's list of available commands.
func NewCompletionCmd(rootCmd *cobra.Command, hidden bool) *cobra.Command {
flagZsh := "zsh"
cmd := &cobra.Command{
Use: "completion",
Short: "Generate shell completion scripts",
Long: fmt.Sprintf(`Generate Bash and Zsh completion scripts and print them to STDOUT.
Once saved to file, a completion script can be loaded in the shell's
current session as shown:
$ . <(%s completion)
To configure your bash shell to load completions for each session add to
your $HOME/.bashrc or $HOME/.profile the following instruction:
. <(%s completion)
`, rootCmd.Use, rootCmd.Use),
RunE: func(cmd *cobra.Command, _ []string) error {
zsh, err := cmd.Flags().GetBool(flagZsh)
if err != nil {
return err
}
if zsh {
return rootCmd.GenZshCompletion(cmd.OutOrStdout())
}
return rootCmd.GenBashCompletion(cmd.OutOrStdout())
},
Hidden: hidden,
Args: cobra.NoArgs,
}
cmd.Flags().Bool(flagZsh, false, "Generate Zsh completion script")
return cmd
}
+27 -6
View File
@@ -1,6 +1,7 @@
package commands
import (
"context"
"fmt"
"os"
"path/filepath"
@@ -17,6 +18,17 @@ import (
tmos "github.com/tendermint/tendermint/libs/os"
)
// writeConfigVals writes a toml file with the given values.
// It returns an error if writing was impossible.
func writeConfigVals(dir string, vals map[string]string) error {
data := ""
for k, v := range vals {
data += fmt.Sprintf("%s = \"%s\"\n", k, v)
}
cfile := filepath.Join(dir, "config.toml")
return os.WriteFile(cfile, []byte(data), 0600)
}
// clearConfig clears env vars, the given root dir, and resets viper.
func clearConfig(t *testing.T, dir string) *cfg.Config {
t.Helper()
@@ -41,7 +53,7 @@ func testRootCmd(conf *cfg.Config) *cobra.Command {
return cmd
}
func testSetup(t *testing.T, conf *cfg.Config, args []string, env map[string]string) error {
func testSetup(ctx context.Context, t *testing.T, conf *cfg.Config, args []string, env map[string]string) error {
t.Helper()
cmd := testRootCmd(conf)
@@ -49,7 +61,7 @@ func testSetup(t *testing.T, conf *cfg.Config, args []string, env map[string]str
// run with the args and env
args = append([]string{cmd.Use}, args...)
return cli.RunWithArgs(cmd, args, env)
return cli.RunWithArgs(ctx, cmd, args, env)
}
func TestRootHome(t *testing.T) {
@@ -65,11 +77,14 @@ func TestRootHome(t *testing.T) {
{nil, map[string]string{"TMHOME": newRoot}, newRoot},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for i, tc := range cases {
t.Run(fmt.Sprint(i), func(t *testing.T) {
conf := clearConfig(t, tc.root)
err := testSetup(t, conf, tc.args, tc.env)
err := testSetup(ctx, t, conf, tc.args, tc.env)
require.NoError(t, err)
require.Equal(t, tc.root, conf.RootDir)
@@ -99,11 +114,14 @@ func TestRootFlagsEnv(t *testing.T) {
{nil, map[string]string{"TM_LOG_LEVEL": "debug"}, "debug"}, // right env
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for i, tc := range cases {
t.Run(fmt.Sprint(i), func(t *testing.T) {
conf := clearConfig(t, defaultDir)
err := testSetup(t, conf, tc.args, tc.env)
err := testSetup(ctx, t, conf, tc.args, tc.env)
require.NoError(t, err)
assert.Equal(t, tc.logLevel, conf.LogLevel)
@@ -113,6 +131,9 @@ func TestRootFlagsEnv(t *testing.T) {
}
func TestRootConfig(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// write non-default config
nonDefaultLogLvl := "debug"
cvals := map[string]string{
@@ -142,14 +163,14 @@ func TestRootConfig(t *testing.T) {
// write the non-defaults to a different path
// TODO: support writing sub configs so we can test that too
err = WriteConfigVals(configFilePath, cvals)
err = writeConfigVals(configFilePath, cvals)
require.NoError(t, err)
cmd := testRootCmd(conf)
// run with the args and env
tc.args = append([]string{cmd.Use}, tc.args...)
err = cli.RunWithArgs(cmd, tc.args, tc.env)
err = cli.RunWithArgs(ctx, cmd, tc.args, tc.env)
require.NoError(t, err)
require.Equal(t, tc.logLvl, conf.LogLevel)
+2 -2
View File
@@ -44,7 +44,7 @@ func main() {
commands.MakeRollbackStateCommand(conf),
commands.MakeKeyMigrateCommand(conf, logger),
debug.DebugCmd,
cli.NewCompletionCmd(rcmd, true),
commands.NewCompletionCmd(rcmd, true),
)
// NOTE:
@@ -60,7 +60,7 @@ func main() {
// Create & start node
rcmd.AddCommand(commands.NewRunNodeCmd(nodeFunc, conf, logger))
if err := rcmd.ExecuteContext(ctx); err != nil {
if err := cli.RunWithTrace(ctx, rcmd); err != nil {
panic(err)
}
}