k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/cmd/yamlfmt/yamlfmt.go (about) 1 /* 2 Copyright 2021 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "flag" 21 "fmt" 22 "io" 23 "os" 24 25 "gopkg.in/yaml.v3" 26 ) 27 28 func main() { 29 indent := flag.Int("indent", 2, "default indent") 30 flag.Parse() 31 for _, path := range flag.Args() { 32 sourceYaml, err := os.ReadFile(path) 33 if err != nil { 34 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err) 35 continue 36 } 37 rootNode, err := fetchYaml(sourceYaml) 38 if err != nil { 39 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err) 40 continue 41 } 42 writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) 43 if err != nil { 44 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err) 45 continue 46 } 47 err = streamYaml(writer, indent, rootNode) 48 if err != nil { 49 fmt.Fprintf(os.Stderr, "%s: %v\n", path, err) 50 continue 51 } 52 } 53 } 54 55 func fetchYaml(sourceYaml []byte) (*yaml.Node, error) { 56 rootNode := yaml.Node{} 57 err := yaml.Unmarshal(sourceYaml, &rootNode) 58 if err != nil { 59 return nil, err 60 } 61 return &rootNode, nil 62 } 63 64 func streamYaml(writer io.Writer, indent *int, in *yaml.Node) error { 65 encoder := yaml.NewEncoder(writer) 66 encoder.SetIndent(*indent) 67 err := encoder.Encode(in) 68 if err != nil { 69 return err 70 } 71 return encoder.Close() 72 }