github.com/crossplane/upjet@v1.3.0/pkg/pipeline/controller.go (about) 1 // SPDX-FileCopyrightText: 2023 The Crossplane Authors <https://crossplane.io> 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package pipeline 6 7 import ( 8 "os" 9 "path/filepath" 10 "strings" 11 12 "github.com/muvaf/typewriter/pkg/wrapper" 13 "github.com/pkg/errors" 14 15 "github.com/crossplane/upjet/pkg/config" 16 "github.com/crossplane/upjet/pkg/pipeline/templates" 17 ) 18 19 // NewControllerGenerator returns a new ControllerGenerator. 20 func NewControllerGenerator(rootDir, modulePath, group string) *ControllerGenerator { 21 return &ControllerGenerator{ 22 Group: group, 23 ControllerGroupDir: filepath.Join(rootDir, "internal", "controller", strings.Split(group, ".")[0]), 24 ModulePath: modulePath, 25 LicenseHeaderPath: filepath.Join(rootDir, "hack", "boilerplate.go.txt"), 26 } 27 } 28 29 // ControllerGenerator generates controller setup functions. 30 type ControllerGenerator struct { 31 Group string 32 ControllerGroupDir string 33 ModulePath string 34 LicenseHeaderPath string 35 } 36 37 // Generate writes controller setup functions. 38 func (cg *ControllerGenerator) Generate(cfg *config.Resource, typesPkgPath string, featuresPkgPath string) (pkgPath string, err error) { 39 controllerPkgPath := filepath.Join(cg.ModulePath, "internal", "controller", strings.ToLower(strings.Split(cg.Group, ".")[0]), strings.ToLower(cfg.Kind)) 40 ctrlFile := wrapper.NewFile(controllerPkgPath, strings.ToLower(cfg.Kind), templates.ControllerTemplate, 41 wrapper.WithGenStatement(GenStatement), 42 wrapper.WithHeaderPath(cg.LicenseHeaderPath), 43 ) 44 45 vars := map[string]any{ 46 "Package": strings.ToLower(cfg.Kind), 47 "CRD": map[string]string{ 48 "Kind": cfg.Kind, 49 }, 50 "DisableNameInitializer": cfg.ExternalName.DisableNameInitializer, 51 "TypePackageAlias": ctrlFile.Imports.UsePackage(typesPkgPath), 52 "UseAsync": cfg.UseAsync, 53 "UseTerraformPluginSDKClient": cfg.ShouldUseTerraformPluginSDKClient(), 54 "UseTerraformPluginFrameworkClient": cfg.ShouldUseTerraformPluginFrameworkClient(), 55 "ResourceType": cfg.Name, 56 "Initializers": cfg.InitializerFns, 57 } 58 59 // If the provider has a features package, add it to the controller template. 60 // This is to ensure we don't break existing providers that don't have a 61 // features package (yet). 62 if featuresPkgPath != "" { 63 vars["FeaturesPackageAlias"] = ctrlFile.Imports.UsePackage(featuresPkgPath) 64 } 65 66 filePath := filepath.Join(cg.ControllerGroupDir, strings.ToLower(cfg.Kind), "zz_controller.go") 67 return controllerPkgPath, errors.Wrap( 68 ctrlFile.Write(filePath, vars, os.ModePerm), 69 "cannot write controller file", 70 ) 71 }