github.com/Racer159/jackal@v0.32.7-0.20240401174413-0bd2339e4f2e/src/internal/packager/kustomize/build.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // SPDX-FileCopyrightText: 2021-Present The Jackal Authors
     3  
     4  // Package kustomize provides functions for building kustomizations.
     5  package kustomize
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  
    11  	"github.com/defenseunicorns/pkg/helpers"
    12  	"sigs.k8s.io/kustomize/api/krusty"
    13  	krustytypes "sigs.k8s.io/kustomize/api/types"
    14  	"sigs.k8s.io/kustomize/kyaml/filesys"
    15  )
    16  
    17  // Build reads a kustomization and builds it into a single yaml file.
    18  func Build(path string, destination string, kustomizeAllowAnyDirectory bool) error {
    19  	// Kustomize has to write to the filesystem on-disk
    20  	fSys := filesys.MakeFsOnDisk()
    21  
    22  	// flux2 build options for consistency, load restrictions none applies only to local files
    23  	buildOptions := krusty.MakeDefaultOptions()
    24  
    25  	if kustomizeAllowAnyDirectory {
    26  		buildOptions.LoadRestrictions = krustytypes.LoadRestrictionsNone
    27  	}
    28  
    29  	kustomizer := krusty.MakeKustomizer(buildOptions)
    30  
    31  	// Try to build the kustomization
    32  	resources, err := kustomizer.Run(fSys, path)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	yaml, err := resources.AsYaml()
    38  
    39  	if err != nil {
    40  		return fmt.Errorf("problem converting kustomization to yaml: %w", err)
    41  	}
    42  
    43  	return os.WriteFile(destination, yaml, helpers.ReadWriteUser)
    44  }