databricks-cli/bundle/python/transform.go

86 lines
1.9 KiB
Go
Raw Normal View History

package python
import (
"fmt"
2023-08-18 09:23:45 +00:00
"strconv"
"strings"
"github.com/databricks/cli/bundle"
2023-08-18 09:23:45 +00:00
"github.com/databricks/cli/bundle/config/mutator"
"github.com/databricks/cli/bundle/libraries"
"github.com/databricks/databricks-sdk-go/service/jobs"
)
2023-08-14 15:36:37 +00:00
const NOTEBOOK_TEMPLATE = `# Databricks notebook source
%python
{{range .Libraries}}
%pip install --force-reinstall {{.Whl}}
{{end}}
from contextlib import redirect_stdout
import io
import sys
2023-08-14 15:36:37 +00:00
sys.argv = [{{.Params}}]
import pkg_resources
2023-08-14 15:36:37 +00:00
_func = pkg_resources.load_entry_point("{{.Task.PackageName}}", "console_scripts", "{{.Task.EntryPoint}}")
f = io.StringIO()
with redirect_stdout(f):
_func()
s = f.getvalue()
dbutils.notebook.exit(s)
`
2023-08-14 15:36:37 +00:00
// This mutator takes the wheel task and transforms it into notebook
// which installs uploaded wheels using %pip and then calling corresponding
// entry point.
func TransformWheelTask() bundle.Mutator {
2023-08-18 09:23:45 +00:00
return mutator.NewTrampoline(
"python_wheel",
getTasks,
generateTemplateData,
cleanUpTask,
NOTEBOOK_TEMPLATE,
)
2023-08-14 15:36:37 +00:00
}
2023-08-18 09:23:45 +00:00
func getTasks(b *bundle.Bundle) []*jobs.Task {
return libraries.FindAllWheelTasks(b)
2023-08-14 15:36:37 +00:00
}
2023-08-18 09:23:45 +00:00
func generateTemplateData(task *jobs.Task) (map[string]any, error) {
params, err := generateParameters(task.PythonWheelTask)
2023-08-16 14:34:46 +00:00
if err != nil {
2023-08-18 09:23:45 +00:00
return nil, err
2023-08-16 14:34:46 +00:00
}
2023-08-14 15:36:37 +00:00
data := map[string]any{
2023-08-18 09:23:45 +00:00
"Libraries": task.Libraries,
2023-08-16 14:34:46 +00:00
"Params": params,
2023-08-18 09:23:45 +00:00
"Task": task.PythonWheelTask,
2023-08-14 15:36:37 +00:00
}
2023-08-18 09:23:45 +00:00
return data, nil
}
2023-08-16 14:34:46 +00:00
func generateParameters(task *jobs.PythonWheelTask) (string, error) {
if task.Parameters != nil && task.NamedParameters != nil {
return "", fmt.Errorf("not allowed to pass both paramaters and named_parameters")
}
params := append([]string{"python"}, task.Parameters...)
for k, v := range task.NamedParameters {
params = append(params, fmt.Sprintf("%s=%s", k, v))
}
2023-08-18 09:23:45 +00:00
for i := range params {
2023-08-18 09:23:45 +00:00
params[i] = strconv.Quote(params[i])
}
2023-08-16 14:34:46 +00:00
return strings.Join(params, ", "), nil
}
2023-08-18 09:23:45 +00:00
func cleanUpTask(task *jobs.Task) {
task.PythonWheelTask = nil
task.Libraries = nil
}