pkg/csconfig: use yaml.v3; deprecate yaml.v2 for new code (#2867)

* pkg/csconfig: use yaml.v3; deprecate yaml.v2 for new code
* yaml.v3: handle empty files
* Lint whitespace, errors
This commit is contained in:
mmetc 2024-03-04 14:22:53 +01:00 committed by GitHub
parent 41b43733b0
commit e7ecea764e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 153 additions and 43 deletions

View file

@ -1,10 +1,13 @@
package csconfig
import (
"bytes"
"errors"
"fmt"
"io"
"path/filepath"
"gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/go-cs-lib/yamlpatch"
)
@ -20,37 +23,51 @@ func (s *SimulationConfig) IsSimulated(scenario string) bool {
if s.Simulation != nil && *s.Simulation {
simulated = true
}
for _, excluded := range s.Exclusions {
if excluded == scenario {
simulated = !simulated
break
}
}
return simulated
}
func (c *Config) LoadSimulation() error {
simCfg := SimulationConfig{}
if c.ConfigPaths.SimulationFilePath == "" {
c.ConfigPaths.SimulationFilePath = filepath.Clean(c.ConfigPaths.ConfigDir + "/simulation.yaml")
}
patcher := yamlpatch.NewPatcher(c.ConfigPaths.SimulationFilePath, ".local")
rcfg, err := patcher.MergedPatchContent()
if err != nil {
return err
}
if err := yaml.UnmarshalStrict(rcfg, &simCfg); err != nil {
return fmt.Errorf("while unmarshaling simulation file '%s' : %s", c.ConfigPaths.SimulationFilePath, err)
dec := yaml.NewDecoder(bytes.NewReader(rcfg))
dec.KnownFields(true)
if err := dec.Decode(&simCfg); err != nil {
if !errors.Is(err, io.EOF) {
return fmt.Errorf("while unmarshaling simulation file '%s': %w", c.ConfigPaths.SimulationFilePath, err)
}
}
if simCfg.Simulation == nil {
simCfg.Simulation = new(bool)
}
if c.Crowdsec != nil {
c.Crowdsec.SimulationConfig = &simCfg
}
if c.Cscli != nil {
c.Cscli.SimulationConfig = &simCfg
}
return nil
}