83 lines
2.1 KiB
Go
83 lines
2.1 KiB
Go
package daggerhelm
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path"
|
|
"text/template"
|
|
|
|
"dagger.io/dagger"
|
|
)
|
|
|
|
const CONTAINER_IMAGE = "docker.io/alpine/k8s:1.26.3"
|
|
|
|
func Compile(
|
|
ctx context.Context,
|
|
client *dagger.Client,
|
|
chartPath string,
|
|
valuesFilePath string,
|
|
) (*dagger.Directory, error) {
|
|
|
|
chart := client.Host().Directory(chartPath)
|
|
|
|
tmpdir := os.TempDir()
|
|
tmpdir = path.Join(tmpdir, "helm-dagger")
|
|
err := os.MkdirAll(tmpdir, 0755)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create tmpdir: %v", err)
|
|
}
|
|
tmpvalues, err := os.CreateTemp(tmpdir, "")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("could not create a tempdir. err: %v", err)
|
|
}
|
|
|
|
if _, err := os.Stat(valuesFilePath); errors.Is(err, os.ErrNotExist) {
|
|
return nil, fmt.Errorf("the values file does not exist: %v", err)
|
|
}
|
|
|
|
contents, err := os.ReadFile(valuesFilePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read values file: %v", err)
|
|
}
|
|
|
|
tmpl, err := template.New(valuesFilePath).Delims("[[", "]]").Parse(string(contents))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to build template for values.yaml, err: %v", err)
|
|
}
|
|
err = tmpl.Execute(tmpvalues, struct{}{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to execute template. err: %v", err)
|
|
}
|
|
|
|
err = tmpvalues.Sync()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to write to tmpfile. err: %v", err)
|
|
}
|
|
|
|
files, err := os.ReadDir(tmpdir)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read tmpdir. err: %v", err)
|
|
}
|
|
|
|
valuesFileDirPath := tmpdir
|
|
valuesFileRelativePath := files[0].Name()
|
|
log.Println(valuesFileRelativePath)
|
|
valuesFile := client.Host().Directory(valuesFileDirPath).File(valuesFileRelativePath)
|
|
|
|
helmoutput := client.Container().
|
|
From(CONTAINER_IMAGE).
|
|
WithWorkdir("/mnt").
|
|
WithDirectory("chart", chart).
|
|
WithFile("chart/values.yaml", valuesFile).
|
|
WithWorkdir("/mnt/chart").
|
|
WithExec([]string{"helm", "template", ".", "--output-dir", "/mnt/output"})
|
|
if exitCode, err := helmoutput.ExitCode(ctx); err != nil || exitCode != 0 {
|
|
return nil, fmt.Errorf("failed to render helm chart: %v", err)
|
|
}
|
|
|
|
return helmoutput.Directory("/mnt/output"), nil
|
|
}
|