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