Skip to content

Commit

Permalink
Validate configuration
Browse files Browse the repository at this point in the history
Validating passed Config prevents a panic or rendering invalid markdown.

Signed-off-by: Anna Kapuscinska <anna@isovalent.com>
  • Loading branch information
lambdanis committed Mar 1, 2024
1 parent 08cc0b2 commit 4a9deeb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
14 changes: 14 additions & 0 deletions pkg/metricsmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package metricsmd

import (
"fmt"
"log/slog"

"github.com/prometheus/client_golang/prometheus"
Expand Down Expand Up @@ -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
}
8 changes: 6 additions & 2 deletions pkg/metricsmd/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -71,5 +75,5 @@ please do not edit directly.
return nil
},
}
return cmd
return cmd, nil
}

0 comments on commit 4a9deeb

Please sign in to comment.