Skip to content

Commit

Permalink
config: normalize keys of the config before any manipulation
Browse files Browse the repository at this point in the history
Signed-off-by: Mathieu Tortuyaux <[email protected]>
  • Loading branch information
tormath1 committed Feb 22, 2024
1 parent 223c9f0 commit 6bc0b0f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
36 changes: 36 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package config
import (
"bufio"
"fmt"
"io"
"net/textproto"
"reflect"
"regexp"
Expand Down Expand Up @@ -70,10 +71,45 @@ func IsMultipartMime(userdata string) bool {
return strings.Contains(contentType, "multipart/mixed")
}

// Normalize transform the "-" in "_" for the keys
// in the YAML configuration.
// e.g reboot-strategy -> reboot_strategy
func Normalize(r io.Reader) string {
var (
l string
w strings.Builder
)

sc := bufio.NewScanner(r)
for sc.Scan() {
l = sc.Text()
// sl = write_files:
sl := strings.Split(l, ":")
// sl = ["write_files", " "]
if len(sl) == 2 {
ssl := strings.Split(sl[0], "-")
// Handle case where it starts with -
// e.g:
// ---
// files:
// - permissions: 0644
if len(ssl) == 2 && !strings.HasPrefix(ssl[1], " ") {
sl[0] = strings.Replace(sl[0], "-", "_", -1)
}
l = strings.Join(sl, ":")
}
w.WriteString(l + "\n")
}

return w.String()
}

// NewCloudConfig instantiates a new CloudConfig from the given contents (a
// string of YAML), returning any error encountered. It will ignore unknown
// fields but log encountering them.
func NewCloudConfig(contents string) (*CloudConfig, error) {
contents = Normalize(strings.NewReader(contents))

var cfg CloudConfig
err := yaml.Unmarshal([]byte(contents), &cfg)
return &cfg, err
Expand Down
5 changes: 4 additions & 1 deletion config/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package validate

import (
"bytes"
"errors"
"fmt"
"regexp"
Expand Down Expand Up @@ -77,10 +78,12 @@ func validateCloudConfig(config []byte, rules []rule) (report Report, err error)
// any parsing issues into the provided report. Unrecoverable errors are
// returned as an error.
func parseCloudConfig(cfg []byte, report *Report) (node, error) {
cfg = []byte(config.Normalize(bytes.NewReader(cfg)))

// unmarshal the config into an implicitly-typed form. The yaml library
// will implicitly convert types into their normalized form
// (e.g. 0744 -> 484, off -> false).
var weak map[interface{}]interface{}
var weak map[string]interface{}
if err := yaml.Unmarshal(cfg, &weak); err != nil {
matches := yamlLineError.FindStringSubmatch(err.Error())
if len(matches) == 3 {
Expand Down

0 comments on commit 6bc0b0f

Please sign in to comment.