Skip to content

Commit

Permalink
Fix yaml cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
Devopy committed Sep 28, 2018
1 parent c65b776 commit a16a312
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 46 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
```
68 changes: 22 additions & 46 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit a16a312

Please sign in to comment.