sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/plugins/golang/declarative/v1/init.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 v1 18 19 import ( 20 "fmt" 21 "os" 22 "path/filepath" 23 "strings" 24 25 log "github.com/sirupsen/logrus" 26 27 "sigs.k8s.io/kubebuilder/v3/pkg/config" 28 "sigs.k8s.io/kubebuilder/v3/pkg/machinery" 29 "sigs.k8s.io/kubebuilder/v3/pkg/plugin" 30 "sigs.k8s.io/kubebuilder/v3/pkg/plugin/util" 31 ) 32 33 var _ plugin.InitSubcommand = &initSubcommand{} 34 35 type initSubcommand struct { 36 config config.Config 37 } 38 39 func (p *initSubcommand) InjectConfig(c config.Config) error { 40 p.config = c 41 42 return nil 43 } 44 45 func (p *initSubcommand) Scaffold(_ machinery.Filesystem) error { 46 //nolint:staticcheck 47 err := updateDockerfile(plugin.IsLegacyLayout(p.config)) 48 if err != nil { 49 return err 50 } 51 return nil 52 } 53 54 // updateDockerfile will add channels staging required for declarative plugin 55 func updateDockerfile(isLegacyLayout bool) error { 56 log.Println("updating Dockerfile to add channels/ directory in the image") 57 dockerfile := filepath.Join("Dockerfile") 58 59 controllerPath := "internal/controller/" 60 if isLegacyLayout { 61 controllerPath = "controllers/" 62 } 63 // nolint:lll 64 err := insertCodeIfDoesNotExist(dockerfile, 65 fmt.Sprintf("COPY %s %s", controllerPath, controllerPath), 66 "\n# https://github.com/kubernetes-sigs/kubebuilder-declarative-pattern/blob/master/docs/addon/walkthrough/README.md#adding-a-manifest\n# Stage channels and make readable\nCOPY channels/ /channels/\nRUN chmod -R a+rx /channels/") 67 if err != nil { 68 return err 69 } 70 71 err = insertCodeIfDoesNotExist(dockerfile, 72 "COPY --from=builder /workspace/manager .", 73 "\n# copy channels\nCOPY --from=builder /channels /channels\n") 74 if err != nil { 75 return err 76 } 77 return nil 78 } 79 80 // insertCodeIfDoesNotExist insert code if it does not already exists 81 func insertCodeIfDoesNotExist(filename, target, code string) error { 82 // false positive 83 // nolint:gosec 84 contents, err := os.ReadFile(filename) 85 if err != nil { 86 return err 87 } 88 89 idx := strings.Index(string(contents), code) 90 if idx != -1 { 91 return nil 92 } 93 94 return util.InsertCode(filename, target, code) 95 }