Skip to content

Instantly share code, notes, and snippets.

@jasoet
Last active November 8, 2019 05:58
Show Gist options
  • Save jasoet/5d69238bd0e5d42daad9ba69cd9c51ff to your computer and use it in GitHub Desktop.
Save jasoet/5d69238bd0e5d42daad9ba69cd9c51ff to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"k8s.io/client-go/kubernetes/scheme"
"os"
"os/user"
"regexp"
)
func main() {
file, err := os.Open(HomeDir("proctor-manifest.yaml"))
if err != nil {
fmt.Printf("%#v", err)
}
decode := scheme.Codecs.UniversalDeserializer().Decode
yamlDocs := SplitYaml(file)
for _, yaml := range yamlDocs {
obj, groupKind, err := decode([]byte(yaml), nil, nil)
if err != nil {
fmt.Printf("%#v", err)
}
fmt.Printf("=====================\n")
fmt.Printf("%#v\n", groupKind)
fmt.Printf("%#v\n", obj)
}
}
func HomeDir(children ...string) string {
usr, _ := user.Current()
home := usr.HomeDir
for _, child := range children {
home = fmt.Sprintf("%s/%s", home, child)
}
return home
}
func SplitYaml(source io.ReadCloser) (result []string) {
separator := regexp.MustCompile("(^-+$)")
whitespace := regexp.MustCompile(`^\s+$`)
scanner := bufio.NewScanner(source)
result = []string{}
stringBuffer := bytes.NewBufferString("")
for scanner.Scan() {
text := scanner.Text()
if separator.MatchString(text) {
yamlDoc := stringBuffer.String()
if !whitespace.MatchString(yamlDoc) {
result = append(result, stringBuffer.String())
}
stringBuffer.Reset()
} else {
stringBuffer.WriteString(fmt.Sprintf("%s\n", text))
}
}
yamlDoc := stringBuffer.String()
if !whitespace.MatchString(yamlDoc) {
result = append(result, stringBuffer.String())
}
stringBuffer.Reset()
return
}
@jasoet
Copy link
Author

jasoet commented Nov 8, 2019

Support multiple Yaml config in single file, separated to with ---.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment