github.com/crossplane/upjet@v1.3.0/pkg/pipeline/conversion_hub.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  	"go/types"
     9  	"os"
    10  	"path/filepath"
    11  	"strings"
    12  
    13  	"github.com/muvaf/typewriter/pkg/wrapper"
    14  	"github.com/pkg/errors"
    15  
    16  	"github.com/crossplane/upjet/pkg/pipeline/templates"
    17  )
    18  
    19  // NewConversionHubGenerator returns a new ConversionHubGenerator.
    20  func NewConversionHubGenerator(pkg *types.Package, rootDir, group, version string) *ConversionHubGenerator {
    21  	return &ConversionHubGenerator{
    22  		LocalDirectoryPath: filepath.Join(rootDir, "apis", strings.ToLower(strings.Split(group, ".")[0]), version),
    23  		LicenseHeaderPath:  filepath.Join(rootDir, "hack", "boilerplate.go.txt"),
    24  		pkg:                pkg,
    25  	}
    26  }
    27  
    28  // ConversionHubGenerator generates conversion methods implementing the
    29  // conversion.Hub interface on the CRD structs.
    30  type ConversionHubGenerator struct {
    31  	LocalDirectoryPath string
    32  	LicenseHeaderPath  string
    33  
    34  	pkg *types.Package
    35  }
    36  
    37  // Generate writes generated conversion.Hub interface functions
    38  func (cg *ConversionHubGenerator) Generate(cfgs []*terraformedInput, apiVersion string) error {
    39  	trFile := wrapper.NewFile(cg.pkg.Path(), cg.pkg.Name(), templates.ConversionHubTemplate,
    40  		wrapper.WithGenStatement(GenStatement),
    41  		wrapper.WithHeaderPath(cg.LicenseHeaderPath),
    42  	)
    43  	filePath := filepath.Join(cg.LocalDirectoryPath, "zz_generated.conversion_hubs.go")
    44  	vars := map[string]any{
    45  		"APIVersion": apiVersion,
    46  	}
    47  	resources := make([]map[string]any, len(cfgs))
    48  	index := 0
    49  	for _, cfg := range cfgs {
    50  		resources[index] = map[string]any{
    51  			"CRD": map[string]string{
    52  				"Kind": cfg.Kind,
    53  			},
    54  		}
    55  		index++
    56  	}
    57  	vars["Resources"] = resources
    58  	if len(resources) == 0 {
    59  		return nil
    60  	}
    61  	return errors.Wrapf(
    62  		trFile.Write(filePath, vars, os.ModePerm),
    63  		"cannot write the generated conversion Hub functions file %s", filePath,
    64  	)
    65  }