feat(codersdk): export template variable parser (#13984)

This commit is contained in:
Ethan
2024-07-24 14:11:29 +10:00
committed by GitHub
parent 177c7d3c68
commit 7028ff79c3
4 changed files with 28 additions and 31 deletions

View File

@ -97,7 +97,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
var varsFiles []string var varsFiles []string
if !uploadFlags.stdin() { if !uploadFlags.stdin() {
varsFiles, err = DiscoverVarsFiles(uploadFlags.directory) varsFiles, err = codersdk.DiscoverVarsFiles(uploadFlags.directory)
if err != nil { if err != nil {
return err return err
} }
@ -118,7 +118,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
return err return err
} }
userVariableValues, err := ParseUserVariableValues( userVariableValues, err := codersdk.ParseUserVariableValues(
varsFiles, varsFiles,
variablesFile, variablesFile,
commandLineVariables) commandLineVariables)

View File

@ -81,7 +81,7 @@ func (r *RootCmd) templatePush() *serpent.Command {
var varsFiles []string var varsFiles []string
if !uploadFlags.stdin() { if !uploadFlags.stdin() {
varsFiles, err = DiscoverVarsFiles(uploadFlags.directory) varsFiles, err = codersdk.DiscoverVarsFiles(uploadFlags.directory)
if err != nil { if err != nil {
return err return err
} }
@ -111,7 +111,7 @@ func (r *RootCmd) templatePush() *serpent.Command {
inv.Logger.Info(inv.Context(), "reusing existing provisioner tags", "tags", tags) inv.Logger.Info(inv.Context(), "reusing existing provisioner tags", "tags", tags)
} }
userVariableValues, err := ParseUserVariableValues( userVariableValues, err := codersdk.ParseUserVariableValues(
varsFiles, varsFiles,
variablesFile, variablesFile,
commandLineVariables) commandLineVariables)

View File

@ -1,4 +1,4 @@
package cli package codersdk
import ( import (
"encoding/json" "encoding/json"
@ -13,8 +13,6 @@ import (
"github.com/hashicorp/hcl/v2/hclparse" "github.com/hashicorp/hcl/v2/hclparse"
"github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty"
"github.com/coder/coder/v2/codersdk"
) )
/** /**
@ -54,7 +52,7 @@ func DiscoverVarsFiles(workDir string) ([]string, error) {
return found, nil return found, nil
} }
func ParseUserVariableValues(varsFiles []string, variablesFile string, commandLineVariables []string) ([]codersdk.VariableValue, error) { func ParseUserVariableValues(varsFiles []string, variablesFile string, commandLineVariables []string) ([]VariableValue, error) {
fromVars, err := parseVariableValuesFromVarsFiles(varsFiles) fromVars, err := parseVariableValuesFromVarsFiles(varsFiles)
if err != nil { if err != nil {
return nil, err return nil, err
@ -73,15 +71,15 @@ func ParseUserVariableValues(varsFiles []string, variablesFile string, commandLi
return combineVariableValues(fromVars, fromFile, fromCommandLine), nil return combineVariableValues(fromVars, fromFile, fromCommandLine), nil
} }
func parseVariableValuesFromVarsFiles(varsFiles []string) ([]codersdk.VariableValue, error) { func parseVariableValuesFromVarsFiles(varsFiles []string) ([]VariableValue, error) {
var parsed []codersdk.VariableValue var parsed []VariableValue
for _, varsFile := range varsFiles { for _, varsFile := range varsFiles {
content, err := os.ReadFile(varsFile) content, err := os.ReadFile(varsFile)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var t []codersdk.VariableValue var t []VariableValue
ext := filepath.Ext(varsFile) ext := filepath.Ext(varsFile)
switch ext { switch ext {
case ".tfvars": case ".tfvars":
@ -103,7 +101,7 @@ func parseVariableValuesFromVarsFiles(varsFiles []string) ([]codersdk.VariableVa
return parsed, nil return parsed, nil
} }
func parseVariableValuesFromHCL(content []byte) ([]codersdk.VariableValue, error) { func parseVariableValuesFromHCL(content []byte) ([]VariableValue, error) {
parser := hclparse.NewParser() parser := hclparse.NewParser()
hclFile, diags := parser.ParseHCL(content, "file.hcl") hclFile, diags := parser.ParseHCL(content, "file.hcl")
if diags.HasErrors() { if diags.HasErrors() {
@ -159,7 +157,7 @@ func parseVariableValuesFromHCL(content []byte) ([]codersdk.VariableValue, error
// parseVariableValuesFromJSON converts the .tfvars.json content into template variables. // parseVariableValuesFromJSON converts the .tfvars.json content into template variables.
// The function visits only root-level properties as template variables do not support nested // The function visits only root-level properties as template variables do not support nested
// structures. // structures.
func parseVariableValuesFromJSON(content []byte) ([]codersdk.VariableValue, error) { func parseVariableValuesFromJSON(content []byte) ([]VariableValue, error) {
var data map[string]interface{} var data map[string]interface{}
err := json.Unmarshal(content, &data) err := json.Unmarshal(content, &data)
if err != nil { if err != nil {
@ -183,10 +181,10 @@ func parseVariableValuesFromJSON(content []byte) ([]codersdk.VariableValue, erro
return convertMapIntoVariableValues(stringData), nil return convertMapIntoVariableValues(stringData), nil
} }
func convertMapIntoVariableValues(m map[string]string) []codersdk.VariableValue { func convertMapIntoVariableValues(m map[string]string) []VariableValue {
var parsed []codersdk.VariableValue var parsed []VariableValue
for key, value := range m { for key, value := range m {
parsed = append(parsed, codersdk.VariableValue{ parsed = append(parsed, VariableValue{
Name: key, Name: key,
Value: value, Value: value,
}) })
@ -197,8 +195,8 @@ func convertMapIntoVariableValues(m map[string]string) []codersdk.VariableValue
return parsed return parsed
} }
func parseVariableValuesFromFile(variablesFile string) ([]codersdk.VariableValue, error) { func parseVariableValuesFromFile(variablesFile string) ([]VariableValue, error) {
var values []codersdk.VariableValue var values []VariableValue
if variablesFile == "" { if variablesFile == "" {
return values, nil return values, nil
} }
@ -209,7 +207,7 @@ func parseVariableValuesFromFile(variablesFile string) ([]codersdk.VariableValue
} }
for name, value := range variablesMap { for name, value := range variablesMap {
values = append(values, codersdk.VariableValue{ values = append(values, VariableValue{
Name: name, Name: name,
Value: value, Value: value,
}) })
@ -237,15 +235,15 @@ func createVariablesMapFromFile(variablesFile string) (map[string]string, error)
return variablesMap, nil return variablesMap, nil
} }
func parseVariableValuesFromCommandLine(variables []string) ([]codersdk.VariableValue, error) { func parseVariableValuesFromCommandLine(variables []string) ([]VariableValue, error) {
var values []codersdk.VariableValue var values []VariableValue
for _, keyValue := range variables { for _, keyValue := range variables {
split := strings.SplitN(keyValue, "=", 2) split := strings.SplitN(keyValue, "=", 2)
if len(split) < 2 { if len(split) < 2 {
return nil, xerrors.Errorf("format key=value expected, but got %s", keyValue) return nil, xerrors.Errorf("format key=value expected, but got %s", keyValue)
} }
values = append(values, codersdk.VariableValue{ values = append(values, VariableValue{
Name: split[0], Name: split[0],
Value: split[1], Value: split[1],
}) })
@ -253,7 +251,7 @@ func parseVariableValuesFromCommandLine(variables []string) ([]codersdk.Variable
return values, nil return values, nil
} }
func combineVariableValues(valuesSets ...[]codersdk.VariableValue) []codersdk.VariableValue { func combineVariableValues(valuesSets ...[]VariableValue) []VariableValue {
combinedValues := make(map[string]string) combinedValues := make(map[string]string)
for _, values := range valuesSets { for _, values := range valuesSets {
@ -262,9 +260,9 @@ func combineVariableValues(valuesSets ...[]codersdk.VariableValue) []codersdk.Va
} }
} }
var result []codersdk.VariableValue var result []VariableValue
for name, value := range combinedValues { for name, value := range combinedValues {
result = append(result, codersdk.VariableValue{Name: name, Value: value}) result = append(result, VariableValue{Name: name, Value: value})
} }
sort.Slice(result, func(i, j int) bool { sort.Slice(result, func(i, j int) bool {

View File

@ -1,4 +1,4 @@
package cli_test package codersdk_test
import ( import (
"os" "os"
@ -7,7 +7,6 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli"
"github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/codersdk"
) )
@ -47,7 +46,7 @@ func TestDiscoverVarsFiles(t *testing.T) {
} }
// When // When
found, err := cli.DiscoverVarsFiles(tempDir) found, err := codersdk.DiscoverVarsFiles(tempDir)
require.NoError(t, err) require.NoError(t, err)
// Then // Then
@ -97,7 +96,7 @@ go_image = ["1.19","1.20","1.21"]`
require.NoError(t, err) require.NoError(t, err)
// When // When
actual, err := cli.ParseUserVariableValues([]string{ actual, err := codersdk.ParseUserVariableValues([]string{
filepath.Join(tempDir, hclFilename1), filepath.Join(tempDir, hclFilename1),
filepath.Join(tempDir, hclFilename2), filepath.Join(tempDir, hclFilename2),
filepath.Join(tempDir, jsonFilename3), filepath.Join(tempDir, jsonFilename3),
@ -136,7 +135,7 @@ func TestParseVariableValuesFromVarsFiles_InvalidJSON(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
// When // When
actual, err := cli.ParseUserVariableValues([]string{ actual, err := codersdk.ParseUserVariableValues([]string{
filepath.Join(tempDir, jsonFilename), filepath.Join(tempDir, jsonFilename),
}, "", nil) }, "", nil)
@ -167,7 +166,7 @@ cores: 2`
require.NoError(t, err) require.NoError(t, err)
// When // When
actual, err := cli.ParseUserVariableValues([]string{ actual, err := codersdk.ParseUserVariableValues([]string{
filepath.Join(tempDir, hclFilename), filepath.Join(tempDir, hclFilename),
}, "", nil) }, "", nil)