diff --git a/README.md b/README.md new file mode 100644 index 0000000..d325921 --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# yamlfmt + +Formats yaml files. + +## Install + +go get -u github.com/devopyio/yamlfmt + +## Usage + +yaml-cleaner -filename example.yaml + +``` +"groups": +- "name": "etcd" + "rules": + - "alert": "EtcdInsufficientMembers" + "annotations": + "message": "Etcd cluster \"{{ $labels.job }}\": insufficient members ({{ $value }})." + "expr": | + count(up{job="etcd"} == 0) by (job) > (count(up{job="etcd"}) by (job) / 2 - 1) + "for": "3m" + "labels": + "severity": "critical" + +``` + +Becomes: + +``` +groups: +- name: etcd + rules: + - alert: EtcdInsufficientMembers + annotations: + message: 'Etcd cluster "{{ $labels.job }}": insufficient members ({{ $value + }}).' + expr: | + count(up{job="etcd"} == 0) by (job) > (count(up{job="etcd"}) by (job) / 2 - 1) + for: 3m + labels: + severity: critical +``` diff --git a/main.go b/main.go index 723279e..250cd17 100644 --- a/main.go +++ b/main.go @@ -2,61 +2,37 @@ package main import ( "flag" - "io/ioutil" "log" - "path/filepath" - "strings" + "os" yaml "gopkg.in/yaml.v2" ) -type YAMLContainer struct { - Groups []struct { - Name string `yaml:"name"` - Rules []struct { - Alert string `yaml:"alert,omitempty"` - Annotations struct { - Message string `yaml:"message"` - } `yaml:"annotations,omitempty"` - Expr string `yaml:"expr"` - For string `yaml:"for,omitempty"` - Labels struct { - Severity string `yaml:"severity"` - } `yaml:"labels,omitempty"` - Record string `yaml:"record,omitempty"` - } `yaml:"rules"` - } `yaml:"groups"` -} - func main() { - dir := flag.String("dir", "./yamlfiles", "path to yaml files") + file := flag.String("filename", "", "filename") + flag.Parse() - filesInDir, err := ioutil.ReadDir(*dir) + + yamlFile, err := os.OpenFile(*file, os.O_RDWR, 0644) if err != nil { log.Fatal(err) } - for _, file := range filesInDir { - if strings.HasSuffix(file.Name(), ".yml") || strings.HasSuffix(file.Name(), ".yaml") { - yamlFile, err := ioutil.ReadFile(filepath.Join(*dir, file.Name())) - if err != nil { - log.Fatal(err) - } - - yamlsave := YAMLContainer{} - - err = yaml.Unmarshal(yamlFile, &yamlsave) - if err != nil { - log.Fatal(err) - } - out, err := yaml.Marshal(yamlsave) - if err != nil { - log.Fatal(err) - } - - err = ioutil.WriteFile(filepath.Join(*dir, file.Name()), out, 0644) - if err != nil { - log.Fatal(err) - } - } + defer yamlFile.Close() + + var out interface{} + if err = yaml.NewDecoder(yamlFile).Decode(&out); err != nil { + log.Fatal(err) + } + + if err = yamlFile.Truncate(0); err != nil { + log.Fatal(err) + } + if _, err = yamlFile.Seek(0, 0); err != nil { + log.Fatal(err) + } + + err = yaml.NewEncoder(yamlFile).Encode(out) + if err != nil { + log.Fatal(err) } }