From 82c1162d2360ceb6505d95640f6c7239800b22a4 Mon Sep 17 00:00:00 2001 From: Gabe Cook Date: Wed, 25 Oct 2023 02:20:09 -0500 Subject: [PATCH] chore(consts): Add consts for flag and config keys --- cmd/cmd.go | 13 +++---- cmd/dump/dump.go | 9 ++--- cmd/exec/exec.go | 3 +- cmd/port_forward/port_forward.go | 17 +++++----- cmd/restore/restore.go | 13 +++---- internal/config/flags/database.go | 43 ++++++++++++------------ internal/config/flags/filesystem.go | 5 +-- internal/config/flags/generic.go | 7 ++-- internal/config/flags/kubernetes.go | 25 +++++++------- internal/config/flags/log.go | 21 ++++++------ internal/config/flags/network.go | 7 ++-- internal/config/namespace_filter.go | 9 ++--- internal/config/namespace_filter_test.go | 3 +- internal/consts/flags.go | 41 ++++++++++++++++++++++ internal/consts/viper.go | 17 ++++++++++ internal/kubernetes/client.go | 7 ++-- internal/util/cmd_setup.go | 25 +++++++------- 17 files changed, 169 insertions(+), 96 deletions(-) create mode 100644 internal/consts/flags.go create mode 100644 internal/consts/viper.go diff --git a/cmd/cmd.go b/cmd/cmd.go index 66da45dd..5922ccf9 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -12,6 +12,7 @@ import ( "github.com/clevyr/kubedb/cmd/port_forward" "github.com/clevyr/kubedb/cmd/restore" "github.com/clevyr/kubedb/internal/config/flags" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/util" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -69,14 +70,14 @@ func preRun(cmd *cobra.Command, args []string) error { cmd.PersistentPostRun = func(cmd *cobra.Command, args []string) { cancel() } cmd.SetContext(ctx) - kubeconfig := viper.GetString("kubernetes.kubeconfig") + kubeconfig := viper.GetString(consts.KubeconfigKey) if kubeconfig == "$HOME" || strings.HasPrefix(kubeconfig, "$HOME"+string(os.PathSeparator)) { home, err := os.UserHomeDir() if err != nil { return err } kubeconfig = home + kubeconfig[5:] - viper.Set("kubernetes.kubeconfig", kubeconfig) + viper.Set(consts.KubeconfigKey, kubeconfig) } initLog(cmd) @@ -88,16 +89,16 @@ func preRun(cmd *cobra.Command, args []string) error { } func initLog(cmd *cobra.Command) { - logLevel := viper.GetString("log.level") + logLevel := viper.GetString(consts.LogLevelKey) parsedLevel, err := log.ParseLevel(logLevel) if err != nil { log.WithField("log-level", logLevel).Warn("invalid log level. defaulting to info.") - viper.Set("log.level", "info") + viper.Set(consts.LogLevelKey, "info") parsedLevel = log.InfoLevel } log.SetLevel(parsedLevel) - logFormat := viper.GetString("log.format") + logFormat := viper.GetString(consts.LogFormatKey) switch logFormat { case "text", "txt", "t": log.SetFormatter(&log.TextFormatter{}) @@ -105,7 +106,7 @@ func initLog(cmd *cobra.Command) { log.SetFormatter(&log.JSONFormatter{}) default: log.WithField("log-format", logFormat).Warn("invalid log formatter. defaulting to text.") - viper.Set("log.format", "text") + viper.Set(consts.LogFormatKey, "text") } } diff --git a/cmd/dump/dump.go b/cmd/dump/dump.go index 8137a834..d7fede3c 100644 --- a/cmd/dump/dump.go +++ b/cmd/dump/dump.go @@ -7,6 +7,7 @@ import ( "github.com/clevyr/kubedb/internal/actions/dump" "github.com/clevyr/kubedb/internal/config" "github.com/clevyr/kubedb/internal/config/flags" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/util" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -64,7 +65,7 @@ func validArgs(cmd *cobra.Command, args []string, toComplete string) ([]string, return nil, cobra.ShellCompDirectiveNoFileComp } - viper.Set("kubernetes.no-job", true) + viper.Set(consts.NoJobKey, true) err := preRun(cmd, args) if err != nil { @@ -83,9 +84,9 @@ func preRun(cmd *cobra.Command, args []string) (err error) { flags.BindJobPodLabels(cmd) flags.BindNoJob(cmd) flags.BindRemoteGzip(cmd) - action.RemoteGzip = viper.GetBool("remote-gzip") + action.RemoteGzip = viper.GetBool(consts.RemoteGzipKey) flags.BindSpinner(cmd) - action.Spinner = viper.GetString("spinner.name") + action.Spinner = viper.GetString(consts.SpinnerKey) if len(args) > 0 { action.Filename = args[0] @@ -107,7 +108,7 @@ func preRun(cmd *cobra.Command, args []string) (err error) { return err } - if action.Filename != "" && !cmd.Flags().Lookup("format").Changed { + if action.Filename != "" && !cmd.Flags().Lookup(consts.FormatFlag).Changed { action.Format = action.Dialect.FormatFromFilename(action.Filename) } diff --git a/cmd/exec/exec.go b/cmd/exec/exec.go index b5be93b9..76c8fce2 100644 --- a/cmd/exec/exec.go +++ b/cmd/exec/exec.go @@ -3,6 +3,7 @@ package exec import ( "github.com/clevyr/kubedb/internal/actions/exec" "github.com/clevyr/kubedb/internal/config/flags" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/util" "github.com/spf13/cobra" _ "k8s.io/client-go/plugin/pkg/client/auth" @@ -26,7 +27,7 @@ func NewCommand() *cobra.Command { flags.Database(cmd) flags.Username(cmd) flags.Password(cmd) - cmd.Flags().StringVarP(&action.Command, "command", "c", "", "Run a single command and exit") + cmd.Flags().StringVarP(&action.Command, consts.CommandFlag, "c", "", "Run a single command and exit") return cmd } diff --git a/cmd/port_forward/port_forward.go b/cmd/port_forward/port_forward.go index 87901a18..5977e127 100644 --- a/cmd/port_forward/port_forward.go +++ b/cmd/port_forward/port_forward.go @@ -5,6 +5,7 @@ import ( "github.com/clevyr/kubedb/internal/actions/port_forward" "github.com/clevyr/kubedb/internal/config/flags" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/util" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -25,18 +26,18 @@ func NewCommand() *cobra.Command { flags.Port(cmd) - cmd.Flags().StringSlice("address", []string{"127.0.0.1", "::1"}, "Local listen address") + cmd.Flags().StringSlice(consts.AddrFlag, []string{"127.0.0.1", "::1"}, "Local listen address") if err := cmd.RegisterFlagCompletionFunc( - "address", + consts.AddrFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{"127.0.0.1\tprivate", "::1\tprivate", "0.0.0.0\tpublic", "::\tpublic"}, cobra.ShellCompDirectiveNoFileComp }); err != nil { panic(err) } - cmd.Flags().Uint16("listen-port", 0, "Local listen port (default discovered)") + cmd.Flags().Uint16(consts.ListenPortFlag, 0, "Local listen port (default discovered)") if err := cmd.RegisterFlagCompletionFunc( - "listen-port", + consts.ListenPortFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { err := preRun(cmd, args) if err != nil { @@ -58,10 +59,10 @@ func NewCommand() *cobra.Command { } func preRun(cmd *cobra.Command, args []string) error { - if err := viper.BindPFlag("port-forward.address", cmd.Flags().Lookup("address")); err != nil { + if err := viper.BindPFlag(consts.PortForwardAddrKey, cmd.Flags().Lookup(consts.AddrFlag)); err != nil { panic(err) } - action.Addresses = viper.GetStringSlice("port-forward.address") + action.Addresses = viper.GetStringSlice(consts.PortForwardAddrKey) err := util.DefaultSetup(cmd, &action.Global, util.SetupOptions{DisableAuthFlags: true}) if err != nil { @@ -69,11 +70,11 @@ func preRun(cmd *cobra.Command, args []string) error { } if len(args) != 0 { - if err := cmd.Flags().Set("listen-port", args[0]); err != nil { + if err := cmd.Flags().Set(consts.ListenPortFlag, args[0]); err != nil { return err } } - action.LocalPort, err = cmd.Flags().GetUint16("listen-port") + action.LocalPort, err = cmd.Flags().GetUint16(consts.ListenPortFlag) if err != nil { util.Teardown(cmd, &action.Global) panic(err) diff --git a/cmd/restore/restore.go b/cmd/restore/restore.go index 544eef9f..4be546ee 100644 --- a/cmd/restore/restore.go +++ b/cmd/restore/restore.go @@ -7,6 +7,7 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/clevyr/kubedb/internal/actions/restore" "github.com/clevyr/kubedb/internal/config/flags" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/util" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -50,7 +51,7 @@ Supported Input Filetypes: flags.RemoteGzip(cmd) flags.Analyze(cmd) flags.Spinner(cmd, &action.Spinner) - cmd.Flags().BoolVarP(&action.Force, "force", "f", false, "Do not prompt before restore") + cmd.Flags().BoolVarP(&action.Force, consts.ForceFlag, "f", false, "Do not prompt before restore") return cmd } @@ -60,7 +61,7 @@ func validArgs(cmd *cobra.Command, args []string, toComplete string) ([]string, return nil, cobra.ShellCompDirectiveNoFileComp } - viper.Set("kubernetes.no-job", true) + viper.Set(consts.NoJobKey, true) action.Force = true err := preRun(cmd, args) @@ -78,13 +79,13 @@ func validArgs(cmd *cobra.Command, args []string, toComplete string) ([]string, func preRun(cmd *cobra.Command, args []string) (err error) { flags.BindRemoteGzip(cmd) - action.RemoteGzip = viper.GetBool("remote-gzip") + action.RemoteGzip = viper.GetBool(consts.RemoteGzipKey) flags.BindAnalyze(cmd) - action.Analyze = viper.GetBool("restore.analyze") + action.Analyze = viper.GetBool(consts.AnalyzeKey) flags.BindJobPodLabels(cmd) flags.BindNoJob(cmd) flags.BindSpinner(cmd) - action.Spinner = viper.GetString("spinner.name") + action.Spinner = viper.GetString(consts.SpinnerKey) if len(args) > 0 { action.Filename = args[0] @@ -117,7 +118,7 @@ func preRun(cmd *cobra.Command, args []string) (err error) { return err } - if !cmd.Flags().Lookup("format").Changed { + if !cmd.Flags().Lookup(consts.FormatFlag).Changed { action.Format = action.Dialect.FormatFromFilename(action.Filename) } diff --git a/internal/config/flags/database.go b/internal/config/flags/database.go index 5a832d36..b2262bd8 100644 --- a/internal/config/flags/database.go +++ b/internal/config/flags/database.go @@ -6,6 +6,7 @@ import ( "time" "github.com/clevyr/kubedb/internal/config" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/database/dialect" "github.com/clevyr/kubedb/internal/database/sqlformat" "github.com/clevyr/kubedb/internal/util" @@ -14,9 +15,9 @@ import ( ) func Dialect(cmd *cobra.Command) { - cmd.PersistentFlags().String("dialect", "", "Database dialect. One of (postgres|mariadb|mongodb) (default discovered)") + cmd.PersistentFlags().String(consts.DialectFlag, "", "Database dialect. One of (postgres|mariadb|mongodb) (default discovered)") err := cmd.RegisterFlagCompletionFunc( - "dialect", + consts.DialectFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{ dialect.Postgres{}.Name(), @@ -31,9 +32,9 @@ func Dialect(cmd *cobra.Command) { func Format(cmd *cobra.Command, p *sqlformat.Format) { *p = sqlformat.Gzip - cmd.Flags().VarP(p, "format", "F", `Output file format One of (gzip|custom|plain)`) + cmd.Flags().VarP(p, consts.FormatFlag, "F", `Output file format One of (gzip|custom|plain)`) err := cmd.RegisterFlagCompletionFunc( - "format", + consts.FormatFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{ sqlformat.Gzip.String(), @@ -47,71 +48,71 @@ func Format(cmd *cobra.Command, p *sqlformat.Format) { } func Port(cmd *cobra.Command) { - cmd.PersistentFlags().Uint16("port", 0, "Database port (default discovered)") + cmd.PersistentFlags().Uint16(consts.PortFlag, 0, "Database port (default discovered)") } func Database(cmd *cobra.Command) { - cmd.Flags().StringP("dbname", "d", "", "Database name to use (default discovered)") - err := cmd.RegisterFlagCompletionFunc("dbname", listDatabases) + cmd.Flags().StringP(consts.DbnameFlag, "d", "", "Database name to use (default discovered)") + err := cmd.RegisterFlagCompletionFunc(consts.DbnameFlag, listDatabases) if err != nil { panic(err) } } func Username(cmd *cobra.Command) { - cmd.Flags().StringP("username", "U", "", "Database username (default discovered)") + cmd.Flags().StringP(consts.UsernameFlag, "U", "", "Database username (default discovered)") } func Password(cmd *cobra.Command) { - cmd.Flags().StringP("password", "p", "", "Database password (default discovered)") + cmd.Flags().StringP(consts.PasswordFlag, "p", "", "Database password (default discovered)") } func SingleTransaction(cmd *cobra.Command, p *bool) { - cmd.Flags().BoolVarP(p, "single-transaction", "1", true, "Restore as a single transaction") + cmd.Flags().BoolVarP(p, consts.SingleTransactionFlag, "1", true, "Restore as a single transaction") } func Clean(cmd *cobra.Command, p *bool) { - cmd.Flags().BoolVarP(p, "clean", "c", true, "Clean (drop) database objects before recreating") + cmd.Flags().BoolVarP(p, consts.CleanFlag, "c", true, "Clean (drop) database objects before recreating") } func IfExists(cmd *cobra.Command, p *bool) { - cmd.Flags().BoolVar(p, "if-exists", true, "Use IF EXISTS when dropping objects") + cmd.Flags().BoolVar(p, consts.IfExistsFlag, true, "Use IF EXISTS when dropping objects") } func NoOwner(cmd *cobra.Command, p *bool) { - cmd.Flags().BoolVarP(p, "no-owner", "O", true, "Skip restoration of object ownership in plain-text format") + cmd.Flags().BoolVarP(p, consts.NoOwnerFlag, "O", true, "Skip restoration of object ownership in plain-text format") } func Tables(cmd *cobra.Command, p *[]string) { - cmd.Flags().StringSliceVarP(p, "table", "t", []string{}, "Dump the specified table(s) only") - err := cmd.RegisterFlagCompletionFunc("table", listTables) + cmd.Flags().StringSliceVarP(p, consts.TableFlag, "t", []string{}, "Dump the specified table(s) only") + err := cmd.RegisterFlagCompletionFunc(consts.TableFlag, listTables) if err != nil { panic(err) } } func ExcludeTable(cmd *cobra.Command, p *[]string) { - cmd.Flags().StringSliceVarP(p, "exclude-table", "T", []string{}, "Do NOT dump the specified table(s)") - err := cmd.RegisterFlagCompletionFunc("exclude-table", listTables) + cmd.Flags().StringSliceVarP(p, consts.ExcludeTableFlag, "T", []string{}, "Do NOT dump the specified table(s)") + err := cmd.RegisterFlagCompletionFunc(consts.ExcludeTableFlag, listTables) if err != nil { panic(err) } } func ExcludeTableData(cmd *cobra.Command, p *[]string) { - cmd.Flags().StringSliceVarP(p, "exclude-table-data", "D", []string{}, "Do NOT dump data for the specified table(s)") - err := cmd.RegisterFlagCompletionFunc("exclude-table-data", listTables) + cmd.Flags().StringSliceVarP(p, consts.ExcludeTableDataFlag, "D", []string{}, "Do NOT dump data for the specified table(s)") + err := cmd.RegisterFlagCompletionFunc(consts.ExcludeTableDataFlag, listTables) if err != nil { panic(err) } } func Analyze(cmd *cobra.Command) { - cmd.Flags().Bool("analyze", true, "Run an analyze query after restore") + cmd.Flags().Bool(consts.AnalyzeFlag, true, "Run an analyze query after restore") } func BindAnalyze(cmd *cobra.Command) { - if err := viper.BindPFlag("restore.analyze", cmd.Flags().Lookup("analyze")); err != nil { + if err := viper.BindPFlag(consts.AnalyzeKey, cmd.Flags().Lookup(consts.AnalyzeFlag)); err != nil { panic(err) } } diff --git a/internal/config/flags/filesystem.go b/internal/config/flags/filesystem.go index 837fafe4..c5ec4dd4 100644 --- a/internal/config/flags/filesystem.go +++ b/internal/config/flags/filesystem.go @@ -1,13 +1,14 @@ package flags import ( + "github.com/clevyr/kubedb/internal/consts" "github.com/spf13/cobra" ) func Directory(cmd *cobra.Command, p *string) { - cmd.Flags().StringVarP(p, "directory", "C", ".", "Directory to dump to") + cmd.Flags().StringVarP(p, consts.DirectoryFlag, "C", ".", "Directory to dump to") err := cmd.RegisterFlagCompletionFunc( - "directory", + consts.DirectoryFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return nil, cobra.ShellCompDirectiveFilterDirs }) diff --git a/internal/config/flags/generic.go b/internal/config/flags/generic.go index 70a9f34b..e21e95bc 100644 --- a/internal/config/flags/generic.go +++ b/internal/config/flags/generic.go @@ -1,6 +1,7 @@ package flags import ( + "github.com/clevyr/kubedb/internal/consts" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -8,14 +9,14 @@ import ( const DefaultSpinner = "sand" func Spinner(cmd *cobra.Command, p *string) { - cmd.Flags().StringVar(p, "spinner", DefaultSpinner, "Spinner from https://jsfiddle.net/sindresorhus/2eLtsbey/embedded/result/") - if err := cmd.Flags().MarkHidden("spinner"); err != nil { + cmd.Flags().StringVar(p, consts.SpinnerFlag, DefaultSpinner, "Spinner from https://jsfiddle.net/sindresorhus/2eLtsbey/embedded/result/") + if err := cmd.Flags().MarkHidden(consts.SpinnerFlag); err != nil { panic(err) } } func BindSpinner(cmd *cobra.Command) { - if err := viper.BindPFlag("spinner.name", cmd.Flags().Lookup("spinner")); err != nil { + if err := viper.BindPFlag(consts.SpinnerKey, cmd.Flags().Lookup(consts.SpinnerFlag)); err != nil { panic(err) } } diff --git a/internal/config/flags/kubernetes.go b/internal/config/flags/kubernetes.go index 5f8bf437..85b6e724 100644 --- a/internal/config/flags/kubernetes.go +++ b/internal/config/flags/kubernetes.go @@ -5,6 +5,7 @@ import ( "path/filepath" "github.com/clevyr/kubedb/internal/config" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/kubernetes" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -20,21 +21,21 @@ func Kubeconfig(cmd *cobra.Command) { kubeconfigEnv = filepath.Join("$HOME", ".kube", "config") } - cmd.PersistentFlags().String("kubeconfig", kubeconfigEnv, "Paths to the kubeconfig file") + cmd.PersistentFlags().String(consts.KubeconfigFlag, kubeconfigEnv, "Paths to the kubeconfig file") } func BindKubeconfig(cmd *cobra.Command) { - if err := viper.BindPFlag("kubernetes.kubeconfig", cmd.Flags().Lookup("kubeconfig")); err != nil { + if err := viper.BindPFlag(consts.KubeconfigKey, cmd.Flags().Lookup(consts.KubeconfigFlag)); err != nil { panic(err) } } func Context(cmd *cobra.Command) { - cmd.PersistentFlags().String("context", "", "Kubernetes context name") + cmd.PersistentFlags().String(consts.ContextFlag, "", "Kubernetes context name") err := cmd.RegisterFlagCompletionFunc( - "context", + consts.ContextFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - kubeconfig := viper.GetString("kubernetes.kubeconfig") + kubeconfig := viper.GetString(consts.KubeconfigKey) configLoader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( &clientcmd.ClientConfigLoadingRules{Precedence: filepath.SplitList(kubeconfig)}, nil, @@ -55,9 +56,9 @@ func Context(cmd *cobra.Command) { } func Namespace(cmd *cobra.Command) { - cmd.PersistentFlags().StringP("namespace", "n", "", "Kubernetes namespace") + cmd.PersistentFlags().StringP(consts.NamespaceFlag, "n", "", "Kubernetes namespace") err := cmd.RegisterFlagCompletionFunc( - "namespace", + consts.NamespaceFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { client, err := kubernetes.NewClientFromCmd(cmd) if err != nil { @@ -82,7 +83,7 @@ func Namespace(cmd *cobra.Command) { } func Pod(cmd *cobra.Command) { - cmd.PersistentFlags().String("pod", "", "Perform detection from a pod instead of searching the namespace") + cmd.PersistentFlags().String(consts.PodFlag, "", "Perform detection from a pod instead of searching the namespace") err := cmd.RegisterFlagCompletionFunc( "pod", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { @@ -106,21 +107,21 @@ func Pod(cmd *cobra.Command) { } func JobPodLabels(cmd *cobra.Command) { - cmd.Flags().StringToString("job-pod-labels", map[string]string{}, "Pod labels to add to the job") + cmd.Flags().StringToString(consts.JobPodLabelsFlag, map[string]string{}, "Pod labels to add to the job") } func BindJobPodLabels(cmd *cobra.Command) { - if err := viper.BindPFlag("kubernetes.job-pod-labels", cmd.Flags().Lookup("job-pod-labels")); err != nil { + if err := viper.BindPFlag(consts.JobPodLabelsKey, cmd.Flags().Lookup(consts.JobPodLabelsFlag)); err != nil { panic(err) } } func NoJob(cmd *cobra.Command) { - cmd.Flags().Bool("no-job", false, "Database commands will be run in the database pod instead of a dedicated job") + cmd.Flags().Bool(consts.NoJobFlag, false, "Database commands will be run in the database pod instead of a dedicated job") } func BindNoJob(cmd *cobra.Command) { - if err := viper.BindPFlag("kubernetes.no-job", cmd.Flags().Lookup("no-job")); err != nil { + if err := viper.BindPFlag(consts.NoJobKey, cmd.Flags().Lookup(consts.NoJobFlag)); err != nil { panic(err) } } diff --git a/internal/config/flags/log.go b/internal/config/flags/log.go index c2ffb51a..ea7e6e5f 100644 --- a/internal/config/flags/log.go +++ b/internal/config/flags/log.go @@ -1,19 +1,20 @@ package flags import ( + "github.com/clevyr/kubedb/internal/consts" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" ) func Quiet(cmd *cobra.Command, p *bool) { - cmd.PersistentFlags().BoolVarP(p, "quiet", "q", false, "Silence remote log output") + cmd.PersistentFlags().BoolVarP(p, consts.QuietFlag, "q", false, "Silence remote log output") } func LogLevel(cmd *cobra.Command) { - cmd.PersistentFlags().String("log-level", "info", "Log level. One of (trace|debug|info|warning|error|fatal|panic)") + cmd.PersistentFlags().String(consts.LogLevelFlag, "info", "Log level. One of (trace|debug|info|warning|error|fatal|panic)") err := cmd.RegisterFlagCompletionFunc( - "log-level", + consts.LogLevelFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{ log.TraceLevel.String(), @@ -31,15 +32,15 @@ func LogLevel(cmd *cobra.Command) { } func BindLogLevel(cmd *cobra.Command) { - if err := viper.BindPFlag("log.level", cmd.Flags().Lookup("log-level")); err != nil { + if err := viper.BindPFlag(consts.LogLevelKey, cmd.Flags().Lookup(consts.LogLevelFlag)); err != nil { panic(err) } } func LogFormat(cmd *cobra.Command) { - cmd.PersistentFlags().String("log-format", "text", "Log formatter. One of (text|json)") + cmd.PersistentFlags().String(consts.LogFormatFlag, "text", "Log formatter. One of (text|json)") err := cmd.RegisterFlagCompletionFunc( - "log-format", + consts.LogFormatFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{"text", "json"}, cobra.ShellCompDirectiveNoFileComp }) @@ -49,20 +50,20 @@ func LogFormat(cmd *cobra.Command) { } func BindLogFormat(cmd *cobra.Command) { - if err := viper.BindPFlag("log.format", cmd.Flags().Lookup("log-format")); err != nil { + if err := viper.BindPFlag(consts.LogFormatKey, cmd.Flags().Lookup(consts.LogFormatFlag)); err != nil { panic(err) } } func Redact(cmd *cobra.Command) { - cmd.PersistentFlags().Bool("redact", true, "Redact password from logs") - if err := cmd.PersistentFlags().MarkHidden("redact"); err != nil { + cmd.PersistentFlags().Bool(consts.RedactFlag, true, "Redact password from logs") + if err := cmd.PersistentFlags().MarkHidden(consts.RedactFlag); err != nil { panic(err) } } func BindRedact(cmd *cobra.Command) { - if err := viper.BindPFlag("log.redact", cmd.Flags().Lookup("redact")); err != nil { + if err := viper.BindPFlag(consts.LogRedactKey, cmd.Flags().Lookup(consts.RedactFlag)); err != nil { panic(err) } } diff --git a/internal/config/flags/network.go b/internal/config/flags/network.go index 323a6a0b..f76038ee 100644 --- a/internal/config/flags/network.go +++ b/internal/config/flags/network.go @@ -1,14 +1,15 @@ package flags import ( + "github.com/clevyr/kubedb/internal/consts" "github.com/spf13/cobra" "github.com/spf13/viper" ) func RemoteGzip(cmd *cobra.Command) { - cmd.Flags().Bool("remote-gzip", true, "Compress data over the wire. Results in lower bandwidth usage, but higher database load. May improve speed on slow connections.") + cmd.Flags().Bool(consts.RemoteGzipFlag, true, "Compress data over the wire. Results in lower bandwidth usage, but higher database load. May improve speed on slow connections.") err := cmd.RegisterFlagCompletionFunc( - "remote-gzip", + consts.RemoteGzipFlag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{"true", "false"}, cobra.ShellCompDirectiveNoFileComp }) @@ -18,7 +19,7 @@ func RemoteGzip(cmd *cobra.Command) { } func BindRemoteGzip(cmd *cobra.Command) { - if err := viper.BindPFlag("remote-gzip", cmd.Flags().Lookup("remote-gzip")); err != nil { + if err := viper.BindPFlag(consts.RemoteGzipKey, cmd.Flags().Lookup(consts.RemoteGzipFlag)); err != nil { panic(err) } } diff --git a/internal/config/namespace_filter.go b/internal/config/namespace_filter.go index a741906f..5bab008c 100644 --- a/internal/config/namespace_filter.go +++ b/internal/config/namespace_filter.go @@ -4,6 +4,7 @@ import ( "regexp" "strconv" + "github.com/clevyr/kubedb/internal/consts" "github.com/spf13/viper" ) @@ -24,7 +25,7 @@ type NamespaceRegexp struct { } func (level NamespaceRegexp) Match(namespace string) bool { - if !viper.GetBool("namespace.filter") { + if !viper.GetBool(consts.NamespaceFilterKey) { return true } return level.re.MatchString(namespace) @@ -39,7 +40,7 @@ func NewNamespaceRegexp(accessLevel string) NamespaceRegexp { } func init() { - viper.SetDefault("namespace.filter", true) - viper.SetDefault("namespace.ro", namespaceFilterReadOnly) - viper.SetDefault("namespace.rw", namespaceFilterReadWrite) + viper.SetDefault(consts.NamespaceFilterKey, true) + viper.SetDefault(consts.NamespaceFilterROKey, namespaceFilterReadOnly) + viper.SetDefault(consts.NamespaceFilterRWKey, namespaceFilterReadWrite) } diff --git a/internal/config/namespace_filter_test.go b/internal/config/namespace_filter_test.go index fd2a871b..6b5cd64c 100644 --- a/internal/config/namespace_filter_test.go +++ b/internal/config/namespace_filter_test.go @@ -5,6 +5,7 @@ import ( "strconv" "testing" + "github.com/clevyr/kubedb/internal/consts" "github.com/spf13/viper" "github.com/stretchr/testify/assert" ) @@ -44,7 +45,7 @@ func TestNamespaceRegexp_Match(t *testing.T) { level := NamespaceRegexp{ re: tt.fields.re, } - viper.Set("namespace.filter", tt.enabled) + viper.Set(consts.NamespaceFilterKey, tt.enabled) got := level.Match(tt.args.namespace) assert.Equal(t, tt.want, got) }) diff --git a/internal/consts/flags.go b/internal/consts/flags.go new file mode 100644 index 00000000..1973e229 --- /dev/null +++ b/internal/consts/flags.go @@ -0,0 +1,41 @@ +package consts + +const ( + DialectFlag = "dialect" + FormatFlag = "format" + PortFlag = "port" + DbnameFlag = "dbname" + UsernameFlag = "username" + PasswordFlag = "password" + SingleTransactionFlag = "single-transaction" + CleanFlag = "clean" + IfExistsFlag = "if-exists" + NoOwnerFlag = "no-owner" + TableFlag = "table" + ExcludeTableFlag = "exclude-table" + ExcludeTableDataFlag = "exclude-table-data" + AnalyzeFlag = "analyze" + + DirectoryFlag = "directory" + + SpinnerFlag = "spinner" + + KubeconfigFlag = "kubeconfig" + ContextFlag = "context" + NamespaceFlag = "namespace" + PodFlag = "pod" + JobPodLabelsFlag = "job-pod-labels" + NoJobFlag = "no-job" + + QuietFlag = "quiet" + LogLevelFlag = "log-level" + LogFormatFlag = "log-format" + RedactFlag = "redact" + + RemoteGzipFlag = "remote-gzip" + + ListenPortFlag = "listen-port" + AddrFlag = "address" + CommandFlag = "command" + ForceFlag = "force" +) diff --git a/internal/consts/viper.go b/internal/consts/viper.go new file mode 100644 index 00000000..7adfb5c9 --- /dev/null +++ b/internal/consts/viper.go @@ -0,0 +1,17 @@ +package consts + +const ( + AnalyzeKey = "restore.analyze" + SpinnerKey = "spinner.name" + KubeconfigKey = "kubernetes.kubeconfig" + JobPodLabelsKey = "kubernetes.job-pod-labels" + NoJobKey = "kubernetes.no-job" + LogLevelKey = "log.level" + LogFormatKey = "log.format" + LogRedactKey = "log.redact" + RemoteGzipKey = "remote-gzip" + NamespaceFilterKey = "namespace.filter" + NamespaceFilterROKey = "namespace.ro" + NamespaceFilterRWKey = "namespace.rw" + PortForwardAddrKey = "port-forward.address" +) diff --git a/internal/kubernetes/client.go b/internal/kubernetes/client.go index 2289e316..7595c8e8 100644 --- a/internal/kubernetes/client.go +++ b/internal/kubernetes/client.go @@ -3,6 +3,7 @@ package kubernetes import ( "path/filepath" + "github.com/clevyr/kubedb/internal/consts" "github.com/spf13/cobra" "github.com/spf13/viper" "k8s.io/client-go/discovery" @@ -85,14 +86,14 @@ func NewClient(kubeconfig, context, namespace string) (config KubeClient, err er } func NewClientFromCmd(cmd *cobra.Command) (KubeClient, error) { - kubeconfig := viper.GetString("kubernetes.kubeconfig") + kubeconfig := viper.GetString(consts.KubeconfigKey) - context, err := cmd.Flags().GetString("context") + context, err := cmd.Flags().GetString(consts.ContextFlag) if err != nil { panic(err) } - namespace, err := cmd.Flags().GetString("namespace") + namespace, err := cmd.Flags().GetString(consts.NamespaceFlag) if err != nil { panic(err) } diff --git a/internal/util/cmd_setup.go b/internal/util/cmd_setup.go index 7b6d9b15..8ad59976 100644 --- a/internal/util/cmd_setup.go +++ b/internal/util/cmd_setup.go @@ -10,6 +10,7 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/clevyr/kubedb/internal/config" + "github.com/clevyr/kubedb/internal/consts" "github.com/clevyr/kubedb/internal/database" "github.com/clevyr/kubedb/internal/kubernetes" "github.com/clevyr/kubedb/internal/log_hooks" @@ -31,12 +32,12 @@ type SetupOptions struct { func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (err error) { cmd.SilenceUsage = true - conf.Kubeconfig = viper.GetString("kubernetes.kubeconfig") - conf.Context, err = cmd.Flags().GetString("context") + conf.Kubeconfig = viper.GetString(consts.KubeconfigKey) + conf.Context, err = cmd.Flags().GetString(consts.ContextFlag) if err != nil { panic(err) } - conf.Namespace, err = cmd.Flags().GetString("namespace") + conf.Namespace, err = cmd.Flags().GetString(consts.NamespaceFlag) if err != nil { panic(err) } @@ -52,7 +53,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e return errors.New("The current action is disabled for namespace " + conf.Client.Namespace) } - podFlag, err := cmd.Flags().GetString("pod") + podFlag, err := cmd.Flags().GetString(consts.PodFlag) if err != nil { panic(err) } @@ -69,7 +70,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e pods = []corev1.Pod{*pod} } - dialectFlag, err := cmd.Flags().GetString("dialect") + dialectFlag, err := cmd.Flags().GetString(consts.DialectFlag) if err != nil { panic(err) } @@ -129,7 +130,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e conf.DbPod = pods[idx] } - conf.Port, err = cmd.Flags().GetUint16("port") + conf.Port, err = cmd.Flags().GetUint16(consts.PortFlag) if err != nil { panic(err) } @@ -151,7 +152,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e conf.Port = conf.Dialect.DefaultPort() } - conf.Database, err = cmd.Flags().GetString("dbname") + conf.Database, err = cmd.Flags().GetString(consts.DbnameFlag) if err != nil && !opts.DisableAuthFlags { panic(err) } @@ -164,7 +165,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e } } - conf.Username, err = cmd.Flags().GetString("username") + conf.Username, err = cmd.Flags().GetString(consts.UsernameFlag) if err != nil && !opts.DisableAuthFlags { panic(err) } @@ -178,7 +179,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e } } - conf.Password, err = cmd.Flags().GetString("password") + conf.Password, err = cmd.Flags().GetString(consts.PasswordFlag) if err != nil && !opts.DisableAuthFlags { panic(err) } @@ -188,7 +189,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e return err } } - if viper.GetBool("log.redact") { + if viper.GetBool(consts.LogRedactKey) { log.AddHook(log_hooks.Redact(conf.Password)) } @@ -196,7 +197,7 @@ func DefaultSetup(cmd *cobra.Command, conf *config.Global, opts SetupOptions) (e } func CreateJob(cmd *cobra.Command, conf *config.Global, opts SetupOptions) error { - if viper.GetBool("kubernetes.no-job") { + if viper.GetBool(consts.NoJobKey) { conf.Host = "127.0.0.1" conf.JobPod = conf.DbPod } else { @@ -231,7 +232,7 @@ func createJob(cmd *cobra.Command, conf *config.Global, actionName string) error "sidecar.istio.io/inject": "false", } maps.Copy(podLabels, standardLabels) - maps.Copy(podLabels, viper.GetStringMapString("kubernetes.job-pod-labels")) + maps.Copy(podLabels, viper.GetStringMapString(consts.JobPodLabelsKey)) job := batchv1.Job{ ObjectMeta: metav1.ObjectMeta{