2023-01-23 14:00:11 +00:00
|
|
|
package bundle
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2023-11-27 10:42:39 +00:00
|
|
|
"os"
|
2023-01-23 14:00:11 +00:00
|
|
|
"reflect"
|
|
|
|
|
2023-05-16 16:35:39 +00:00
|
|
|
"github.com/databricks/cli/bundle/config"
|
|
|
|
"github.com/databricks/cli/bundle/schema"
|
2023-01-23 14:00:11 +00:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2023-07-27 10:03:08 +00:00
|
|
|
func newSchemaCommand() *cobra.Command {
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "schema",
|
|
|
|
Short: "Generate JSON Schema for bundle configuration",
|
|
|
|
}
|
2023-01-23 14:00:11 +00:00
|
|
|
|
2023-07-27 10:03:08 +00:00
|
|
|
var openapi string
|
2023-11-27 10:42:39 +00:00
|
|
|
var outputFile string
|
2023-07-27 10:03:08 +00:00
|
|
|
var onlyDocs bool
|
|
|
|
cmd.Flags().StringVar(&openapi, "openapi", "", "path to a databricks openapi spec")
|
|
|
|
cmd.Flags().BoolVar(&onlyDocs, "only-docs", false, "only generate descriptions for the schema")
|
2023-11-27 10:42:39 +00:00
|
|
|
cmd.Flags().StringVar(&outputFile, "output-file", "", "File path to write the schema to. If not specified, the schema will be written to stdout.")
|
2023-07-27 10:03:08 +00:00
|
|
|
|
|
|
|
cmd.RunE = func(cmd *cobra.Command, args []string) error {
|
2023-11-27 10:42:39 +00:00
|
|
|
// If no openapi spec is provided, try to use the environment variable.
|
|
|
|
// This environment variable is set during CLI code generation.
|
|
|
|
if openapi == "" {
|
|
|
|
openapi = os.Getenv("DATABRICKS_OPENAPI_SPEC")
|
|
|
|
}
|
2023-03-15 02:18:51 +00:00
|
|
|
docs, err := schema.BundleDocs(openapi)
|
2023-01-23 14:00:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
schema, err := schema.New(reflect.TypeOf(config.Root{}), docs)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-15 02:18:51 +00:00
|
|
|
result, err := json.MarshalIndent(schema, "", " ")
|
2023-01-23 14:00:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-15 02:18:51 +00:00
|
|
|
if onlyDocs {
|
|
|
|
result, err = json.MarshalIndent(docs, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2023-11-27 10:42:39 +00:00
|
|
|
|
|
|
|
// If outputFile is provided, write to that file.
|
|
|
|
if outputFile != "" {
|
|
|
|
f, err := os.OpenFile(outputFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
cmd.SetOut(f)
|
|
|
|
}
|
2023-03-15 02:18:51 +00:00
|
|
|
cmd.OutOrStdout().Write(result)
|
2023-01-23 14:00:11 +00:00
|
|
|
return nil
|
2023-07-27 10:03:08 +00:00
|
|
|
}
|
2023-03-15 02:18:51 +00:00
|
|
|
|
2023-07-27 10:03:08 +00:00
|
|
|
return cmd
|
2023-01-23 14:00:11 +00:00
|
|
|
}
|