Skip to content

Commit

Permalink
feat(config): added validation
Browse files Browse the repository at this point in the history
  • Loading branch information
StanGirard committed Apr 9, 2023
1 parent a675028 commit c170337
Showing 1 changed file with 42 additions and 10 deletions.
52 changes: 42 additions & 10 deletions plugins/commons/config.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,66 @@
package commons

import (
"fmt"
"strings"

"github.com/padok-team/yatas/internal/helpers"
"github.com/padok-team/yatas/plugins/logger"
"gopkg.in/yaml.v3"
)

// ParseConfig reads the specified configuration file, parses its content, and returns a Config object.
// It returns an error if the file cannot be read, the content is not valid YAML, or the configuration is not valid.
func ParseConfig(configFile string) (*Config, error) {
// Read the file .yatas.yml
// File to array of bytes
data, err := helpers.ReadFile(configFile)
if err != nil {
return &Config{}, err
logger.Error("Error reading config file", "config_file", configFile, "error", err)
return nil, err
}

// Parse the yaml file
config := Config{}
err = unmarshalYAML(data, &config)
if err != nil {
return &Config{}, err
// Parse the YAML file
var config Config
if err := unmarshalYAML(data, &config); err != nil {
logger.Error("Error parsing YAML config", "config_file", configFile, "error", err)
return nil, err
}

// Validate the configuration
if err := validateConfig(&config); err != nil {
logger.Error("Error validating config", "config_file", configFile, "error", err)
return nil, err
}

return &config, nil
}

func unmarshalYAML(data []byte, config *Config) error {
err := yaml.Unmarshal([]byte(data), &config)
// unmarshalYAML unmarshals the given YAML data into the provided object.
func unmarshalYAML(data []byte, obj interface{}) error {
return yaml.Unmarshal(data, obj)
}

return err
func validateConfig(config *Config) error {
if len(config.Plugins) == 0 {
return fmt.Errorf("no plugins defined in config file %s", ".yatas.yml")
}

for i, plugin := range config.Plugins {
if plugin.Name == "" {
return fmt.Errorf("Plugin at index %d must have a name", i)
}
if plugin.Source == "" {
return fmt.Errorf("Plugin '%s' must have a source", plugin.Name)
}
if plugin.Type != "checks" && plugin.Type != "mod" && plugin.Type != "report" && plugin.Type != "" {
return fmt.Errorf("Plugin '%s' has invalid type '%s'", plugin.Name, plugin.Type)
}
if plugin.Version == "" {
return fmt.Errorf("Plugin '%s' must have a version", plugin.Name)
}
}

return nil
}

func (c *Config) FindPluginWithName(name string) *Plugin {
Expand Down

0 comments on commit c170337

Please sign in to comment.