forked from vmware-archive/fly
/
format_pipeline.go
64 lines (52 loc) · 1.77 KB
/
format_pipeline.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package commands
import (
"bytes"
"fmt"
"io/ioutil"
"os"
yaml "gopkg.in/yaml.v2"
"github.com/concourse/atc"
"github.com/concourse/fly/commands/internal/displayhelpers"
yamlpatch "github.com/krishicks/yaml-patch"
)
type FormatPipelineCommand struct {
Config atc.PathFlag `short:"c" long:"config" required:"true" description:"Pipeline configuration file"`
Write bool `short:"w" long:"write" description:"Do not print to stdout; overwrite the file in place"`
}
func (command *FormatPipelineCommand) Execute(args []string) error {
configPath := string(command.Config)
configBytes, err := ioutil.ReadFile(configPath)
if err != nil {
displayhelpers.FailWithErrorf("could not read config file", err)
}
placeholderWrapper := yamlpatch.NewPlaceholderWrapper("{{", "}}")
wrappedConfigBytes := placeholderWrapper.Wrap(configBytes)
var config atc.Config
err = yaml.Unmarshal(wrappedConfigBytes, &config)
if err != nil {
displayhelpers.FailWithErrorf("could not unmarshal config", err)
}
formattedBytes, err := yaml.Marshal(config)
if err != nil {
displayhelpers.FailWithErrorf("could not marshal config", err)
}
if !bytes.Equal(configBytes, formattedBytes) {
unwrappedConfigBytes := placeholderWrapper.Unwrap(formattedBytes)
if command.Write {
fi, err := os.Stat(configPath)
if err != nil {
displayhelpers.FailWithErrorf("could not stat config file", err)
}
err = ioutil.WriteFile(configPath, unwrappedConfigBytes, fi.Mode())
if err != nil {
displayhelpers.FailWithErrorf("could not write formatted config to %s", err, command.Config)
}
} else {
_, err = fmt.Fprint(os.Stdout, string(unwrappedConfigBytes))
if err != nil {
displayhelpers.FailWithErrorf("could not write formatted config to stdout", err)
}
}
}
return nil
}