From 4a9deeb339b63564090d557194275bf4ef6dbdac Mon Sep 17 00:00:00 2001 From: Anna Kapuscinska Date: Fri, 1 Mar 2024 00:37:26 +0000 Subject: [PATCH] Validate configuration Validating passed Config prevents a panic or rendering invalid markdown. Signed-off-by: Anna Kapuscinska --- pkg/metricsmd/config.go | 14 ++++++++++++++ pkg/metricsmd/print.go | 8 ++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/pkg/metricsmd/config.go b/pkg/metricsmd/config.go index 3c1628c..751bd88 100644 --- a/pkg/metricsmd/config.go +++ b/pkg/metricsmd/config.go @@ -4,6 +4,7 @@ package metricsmd import ( + "fmt" "log/slog" "github.com/prometheus/client_golang/prometheus" @@ -33,3 +34,16 @@ type Config struct { CommentStyle CommentStyle HeadingLevel int // must be between 0 and 4 } + +func validateConfig(config *Config) error { + if config.Targets == nil { + return fmt.Errorf("config.Targets must be set") + } + if config.InitMetrics == nil { + return fmt.Errorf("config.InitMetrics must be set") + } + if config.HeadingLevel < 0 || config.HeadingLevel > 4 { + return fmt.Errorf("config.HeadingLevel must be between 0 and 4") + } + return nil +} diff --git a/pkg/metricsmd/print.go b/pkg/metricsmd/print.go index 12e34eb..437428e 100644 --- a/pkg/metricsmd/print.go +++ b/pkg/metricsmd/print.go @@ -19,7 +19,11 @@ import ( // NewCmd creates a Cobra command for generating metrics reference docs. // It's intended to be used as an add-on to applications that have a Cobra CLI // and expose Prometheus metrics. -func NewCmd(vp *viper.Viper, log *slog.Logger, config *Config) *cobra.Command { +func NewCmd(vp *viper.Viper, log *slog.Logger, config *Config) (*cobra.Command, error) { + err := validateConfig(config) + if err != nil { + return nil, err + } cmd := &cobra.Command{ Use: "metrics-docs", Hidden: true, @@ -71,5 +75,5 @@ please do not edit directly. return nil }, } - return cmd + return cmd, nil }