github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/inspect/helper.go (about) 1 /* 2 Copyright 2021 The Skaffold 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 inspect 18 19 import ( 20 "bytes" 21 "fmt" 22 "io" 23 "io/ioutil" 24 25 yamlv3 "gopkg.in/yaml.v3" 26 27 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/parser" 28 sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/errors" 29 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" 30 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" 31 ) 32 33 var ( 34 ReadFileFunc = util.ReadConfiguration 35 WriteFileFunc = func(filename string, data []byte) error { 36 return ioutil.WriteFile(filename, data, 0644) 37 } 38 ) 39 40 // MarshalConfigSet marshals out the slice of skaffold configs into the respective source `skaffold.yaml` files. 41 // It ensures that the unmodified configs are copied over as-is in their original positions in the file. 42 func MarshalConfigSet(cfgs parser.SkaffoldConfigSet) error { 43 m := make(map[string]parser.SkaffoldConfigSet) 44 for _, cfg := range cfgs { 45 m[cfg.SourceFile] = append(m[cfg.SourceFile], cfg) 46 } 47 for file, set := range m { 48 if err := marshalConfigSetForFile(file, set); err != nil { 49 return err 50 } 51 } 52 return nil 53 } 54 55 func marshalConfigSetForFile(filename string, cfgs parser.SkaffoldConfigSet) error { 56 buf, err := ReadFileFunc(filename) 57 if err != nil { 58 return sErrors.ConfigParsingError(err) 59 } 60 in := bytes.NewReader(buf) 61 decoder := yamlv3.NewDecoder(in) 62 decoder.KnownFields(true) 63 var sl []interface{} 64 for { 65 var parsed yamlv3.Node 66 err := decoder.Decode(&parsed) 67 if err == io.EOF { 68 break 69 } 70 if err != nil { 71 return fmt.Errorf("unable to parse YAML: %w", err) 72 } 73 // parsed content is a document so the `Content` slice has exactly one element 74 sl = append(sl, parsed.Content[0]) 75 } 76 77 for i, cfg := range cfgs { 78 sl[cfg.SourceIndex] = cfgs[i].SkaffoldConfig 79 } 80 81 newCfgs, err := yaml.MarshalWithSeparator(sl) 82 if err != nil { 83 return fmt.Errorf("marshaling new configs: %w", err) 84 } 85 if err := WriteFileFunc(filename, newCfgs); err != nil { 86 return fmt.Errorf("writing config file: %w", err) 87 } 88 return nil 89 }