github.com/kata-containers/tests@v0.0.0-20240307153542-772105b56064/cmd/github-labels/yaml.go (about) 1 // Copyright (c) 2019 Intel Corporation 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 // 5 6 package main 7 8 import ( 9 "fmt" 10 "os" 11 "sort" 12 13 yaml "gopkg.in/yaml.v2" 14 ) 15 16 const fileMode os.FileMode = 0600 17 18 func readYAML(file string) (*LabelsFile, error) { 19 bytes, err := os.ReadFile(file) 20 if err != nil { 21 return nil, err 22 } 23 24 lf := LabelsFile{} 25 26 err = yaml.Unmarshal(bytes, &lf) 27 if err != nil { 28 return nil, err 29 } 30 31 sort.Sort(lf.Labels) 32 sort.Sort(lf.Categories) 33 34 clean(&lf) 35 36 err = check(&lf) 37 if err != nil { 38 return nil, fmt.Errorf("file was not in expected format: %v", err) 39 } 40 41 return &lf, nil 42 } 43 44 func writeYAML(lf *LabelsFile, file string) error { 45 bytes, err := yaml.Marshal(lf) 46 if err != nil { 47 return err 48 } 49 50 return os.WriteFile(file, bytes, fileMode) 51 } 52 53 func checkYAML(file string) error { 54 // read and check 55 _, err := readYAML(file) 56 57 if err == nil { 58 fmt.Printf("Checked file %v\n", file) 59 } 60 61 return err 62 } 63 64 func sortYAML(fromFile, toFile string) error { 65 // read and sort 66 lf, err := readYAML(fromFile) 67 if err != nil { 68 return err 69 } 70 71 return writeYAML(lf, toFile) 72 }