sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/plugins/golang/v3/scaffolds/edit.go (about) 1 /* 2 Copyright 2020 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 scaffolds 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/spf13/afero" 24 25 "sigs.k8s.io/kubebuilder/v3/pkg/config" 26 "sigs.k8s.io/kubebuilder/v3/pkg/machinery" 27 "sigs.k8s.io/kubebuilder/v3/pkg/plugins" 28 ) 29 30 var _ plugins.Scaffolder = &editScaffolder{} 31 32 type editScaffolder struct { 33 config config.Config 34 multigroup bool 35 36 // fs is the filesystem that will be used by the scaffolder 37 fs machinery.Filesystem 38 } 39 40 // NewEditScaffolder returns a new Scaffolder for configuration edit operations 41 func NewEditScaffolder(config config.Config, multigroup bool) plugins.Scaffolder { 42 return &editScaffolder{ 43 config: config, 44 multigroup: multigroup, 45 } 46 } 47 48 // InjectFS implements cmdutil.Scaffolder 49 func (s *editScaffolder) InjectFS(fs machinery.Filesystem) { 50 s.fs = fs 51 } 52 53 // Scaffold implements cmdutil.Scaffolder 54 func (s *editScaffolder) Scaffold() error { 55 filename := "Dockerfile" 56 bs, err := afero.ReadFile(s.fs.FS, filename) 57 if err != nil { 58 return err 59 } 60 str := string(bs) 61 62 // update dockerfile 63 if s.multigroup { 64 str, err = ensureExistAndReplace( 65 str, 66 "COPY api/ api/", 67 `COPY apis/ apis/`) 68 69 } else { 70 str, err = ensureExistAndReplace( 71 str, 72 "COPY apis/ apis/", 73 `COPY api/ api/`) 74 } 75 76 // Ignore the error encountered, if the file is already in desired format. 77 if err != nil && s.multigroup != s.config.IsMultiGroup() { 78 return err 79 } 80 81 if s.multigroup { 82 _ = s.config.SetMultiGroup() 83 } else { 84 _ = s.config.ClearMultiGroup() 85 } 86 87 // Check if the str is not empty, because when the file is already in desired format it will return empty string 88 // because there is nothing to replace. 89 if str != "" { 90 // TODO: instead of writing it directly, we should use the scaffolding machinery for consistency 91 return afero.WriteFile(s.fs.FS, filename, []byte(str), 0644) 92 } 93 94 return nil 95 } 96 97 func ensureExistAndReplace(input, match, replace string) (string, error) { 98 if !strings.Contains(input, match) { 99 return "", fmt.Errorf("can't find %q", match) 100 } 101 return strings.Replace(input, match, replace, -1), nil 102 }