databricks-cli/cmd/init/init.go

71 lines
1.7 KiB
Go
Raw Normal View History

2023-05-15 09:25:01 +00:00
package init
import (
"encoding/json"
"os"
2023-05-17 00:43:41 +00:00
"path/filepath"
2023-05-15 09:25:01 +00:00
"github.com/databricks/bricks/cmd/root"
2023-05-17 09:53:13 +00:00
"github.com/databricks/bricks/libs/template"
2023-05-15 09:25:01 +00:00
"github.com/spf13/cobra"
)
2023-05-17 00:43:41 +00:00
const ConfigFileName = "config.json"
const SchemaFileName = "schema.json"
const TemplateDirname = "template"
2023-05-15 09:25:01 +00:00
var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize Template",
2023-05-17 00:43:41 +00:00
Long: `Initialize template`,
Args: cobra.ExactArgs(1),
2023-05-15 09:25:01 +00:00
RunE: func(cmd *cobra.Command, args []string) error {
2023-05-17 00:43:41 +00:00
templateLocation := args[0]
// read the file containing schema for template input parameters
schemaBytes, err := os.ReadFile(filepath.Join(templateLocation, SchemaFileName))
if err != nil {
return err
}
2023-05-17 09:53:13 +00:00
schema := template.Schema{}
2023-05-17 00:43:41 +00:00
err = json.Unmarshal(schemaBytes, &schema)
if err != nil {
return err
}
// read user config to initalize the template with
2023-05-15 09:25:01 +00:00
var config map[string]interface{}
2023-05-17 11:41:15 +00:00
b, err := os.ReadFile(filepath.Join(targetDir, ConfigFileName))
2023-05-15 09:25:01 +00:00
if err != nil {
return err
}
err = json.Unmarshal(b, &config)
if err != nil {
return err
}
2023-05-17 00:43:41 +00:00
// cast any fields that are supported to be integers. The json unmarshalling
// for a generic map converts all numbers to floating point
err = schema.CastFloatToInt(config)
2023-05-15 09:25:01 +00:00
if err != nil {
return err
}
2023-05-17 00:43:41 +00:00
// validate config according to schema
err = schema.ValidateConfig(config)
if err != nil {
return err
}
// materialize the template
2023-05-17 11:41:15 +00:00
return template.WalkFileTree(config, filepath.Join(args[0], TemplateDirname), targetDir)
2023-05-15 09:25:01 +00:00
},
}
2023-05-17 11:41:15 +00:00
var targetDir string
2023-05-15 09:25:01 +00:00
func init() {
2023-05-17 11:41:15 +00:00
initCmd.Flags().StringVar(&targetDir, "target-dir", ".", "path to directory template will be initialized in")
2023-05-15 09:25:01 +00:00
root.RootCmd.AddCommand(initCmd)
}