Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .nextchanges/bundles/8184.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Fix bundle commands failing with `can't find ".venv/bin/python3"` when run from a subdirectory of a bundle that sets a relative `python.venv_path`. ([#8184](https://github.com/databricks/cli/pull/8184))
24 changes: 23 additions & 1 deletion acceptance/bundle/python/venv-path-subdir/output.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,27 @@ Resources:
=== from a subdirectory

>>> withdir src [CLI] bundle summary
Error: failed to get Python interpreter path: can't find "[VENV_PYTHON]", check if virtualenv is created
Name: my_project
Target: default
Workspace:
User: [USERNAME]
Path: /Workspace/Users/[USERNAME]/.bundle/my_project/default
Resources:
Jobs:
my_job:
Name: My Job
URL: (not deployed)

=== from a subdirectory with a relative DATABRICKS_BUNDLE_ROOT

>>> withdir src [CLI] bundle summary
Name: my_project
Target: default
Workspace:
User: [USERNAME]
Path: /Workspace/Users/[USERNAME]/.bundle/my_project/default
Resources:
Jobs:
my_job:
Name: My Job
URL: (not deployed)
5 changes: 4 additions & 1 deletion acceptance/bundle/python/venv-path-subdir/script
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ title "from the bundle root"
trace $CLI bundle summary

title "from a subdirectory"
musterr trace withdir src $CLI bundle summary
trace withdir src $CLI bundle summary

title "from a subdirectory with a relative DATABRICKS_BUNDLE_ROOT"
DATABRICKS_BUNDLE_ROOT=.. trace withdir src $CLI bundle summary

rm -fr .databricks __pycache__ .venv
7 changes: 0 additions & 7 deletions acceptance/bundle/python/venv-path-subdir/test.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,2 @@
# The venv gets the wheel built from this commit; another databricks-bundles version adds nothing here.
EnvMatrix.PYDAB_VERSION = ["current"]

Badness = "python.venv_path is resolved against the current directory instead of the bundle root, so with the default venv_path: .venv every bundle command run from a subdirectory of the bundle (here src/) fails with 'can't find \".venv/bin/python3\", check if virtualenv is created'; it should use <bundle root>/.venv as it does when run from the root."

# The venv interpreter is bin/python3 on Unix and Scripts\python.exe on Windows.
[[Repls]]
Old = '\.venv[/\\]+(bin[/\\]+python3|Scripts[/\\]+python\.exe)'
New = '[VENV_PYTHON]'
3 changes: 2 additions & 1 deletion bundle/config/experimental.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ type Python struct {
// Example: ["my_project.mutators:add_default_cluster"]
Mutators []string `json:"mutators,omitempty"`

// VEnvPath is path to the virtual environment.
// VEnvPath is path to the virtual environment. A relative path is relative
// to the bundle root.
//
// If enabled, Python code will execute within this environment. If disabled,
// it defaults to using the Python interpreter available in the current shell.
Expand Down
26 changes: 23 additions & 3 deletions bundle/config/mutator/python/python_mutator.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func (m *pythonMutator) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagno
mutateDiagsHasError := errors.New("unexpected error")

err = b.Config.Mutate(func(leftRoot dyn.Value) (dyn.Value, error) {
pythonPath, err := detectExecutable(ctx, opts.venvPath)
pythonPath, err := detectExecutable(ctx, b.BundleRootPath, opts.venvPath)
if err != nil {
return dyn.InvalidValue, fmt.Errorf("failed to get Python interpreter path: %w", err)
}
Expand Down Expand Up @@ -612,7 +612,11 @@ func loadDiagnosticsFile(path string) (diag.Diagnostics, error) {
}

// detectExecutable lookups Python interpreter in virtual environment, or if not set, in PATH.
func detectExecutable(ctx context.Context, venvPath string) (string, error) {
// A relative venvPath is relative to the bundle root, not to the current directory,
// because bundle commands can run from any directory inside the bundle.
// The returned path is absolute: the interpreter runs with the bundle root as its working
// directory, where a path relative to the current directory would not resolve.
func detectExecutable(ctx context.Context, bundleRootPath, venvPath string) (string, error) {
if venvPath == "" {
interpreter, err := python.DetectExecutable(ctx)
if err != nil {
Expand All @@ -622,5 +626,21 @@ func detectExecutable(ctx context.Context, venvPath string) (string, error) {
return interpreter, nil
}

return python.DetectVEnvExecutable(venvPath)
if isRelativeToBundleRoot(venvPath) {
venvPath = filepath.Join(bundleRootPath, venvPath)
}

interpreter, err := python.DetectVEnvExecutable(venvPath)
if err != nil {
return "", err
}

return filepath.Abs(interpreter)
}

// isRelativeToBundleRoot reports whether path can be joined with the bundle root.
// Windows paths that are not absolute but still name a drive (C:venv) or the root
// of the current drive (\venv) keep their meaning.
func isRelativeToBundleRoot(path string) bool {
return !filepath.IsAbs(path) && filepath.VolumeName(path) == "" && !strings.HasPrefix(filepath.ToSlash(path), "/")
}
36 changes: 28 additions & 8 deletions bundle/config/mutator/python/python_mutator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ func TestPythonMutator_Name_applyMutators(t *testing.T) {
}

func TestPythonMutator_loadResources(t *testing.T) {
withFakeVEnv(t, ".venv")

rootPath := filepath.Join(t.TempDir(), "my_project")

// the current directory is not the bundle root, venv_path is relative to the bundle root
pythonPath := withFakeVEnv(t, filepath.Join(rootPath, ".venv"))

b := loadYaml("databricks.yml", `
experimental:
python:
Expand All @@ -63,7 +64,7 @@ workspace: { current_user: { userName: test }}`)
ctx := withProcessStub(
t,
[]string{
interpreterPath(".venv"),
pythonPath,
"-m",
"databricks.bundles.build",
"--phase",
Expand Down Expand Up @@ -178,7 +179,7 @@ workspace: { current_user: { userName: test }}`)
}

func TestPythonMutator_applyMutators(t *testing.T) {
withFakeVEnv(t, ".venv")
pythonPath := withFakeVEnv(t, ".venv")
b := loadYaml("databricks.yml", `
experimental:
python:
Expand All @@ -193,7 +194,7 @@ resources:
ctx := withProcessStub(
t,
[]string{
interpreterPath(".venv"),
pythonPath,
"-m",
"databricks.bundles.build",
"--phase",
Expand Down Expand Up @@ -269,7 +270,7 @@ experimental: {python: {resources: ["resources:load"]}}`, protos.PydabsConfigSec
}

func TestPythonMutator_badOutput(t *testing.T) {
withFakeVEnv(t, ".venv")
pythonPath := withFakeVEnv(t, ".venv")
b := loadYaml("databricks.yml", `
experimental:
python:
Expand All @@ -284,7 +285,7 @@ resources:
ctx := withProcessStub(
t,
[]string{
interpreterPath(".venv"),
pythonPath,
"-m",
"databricks.bundles.build",
"--phase",
Expand Down Expand Up @@ -316,6 +317,17 @@ func TestPythonMutator_disabled(t *testing.T) {
assert.NoError(t, diag.Error())
}

func TestIsRelativeToBundleRoot(t *testing.T) {
assert.True(t, isRelativeToBundleRoot(".venv"))
assert.True(t, isRelativeToBundleRoot(filepath.Join("..", "venv")))
assert.False(t, isRelativeToBundleRoot(t.TempDir()))

if runtime.GOOS == "windows" {
assert.False(t, isRelativeToBundleRoot(`\envs\venv`))
assert.False(t, isRelativeToBundleRoot(`C:envs\venv`))
}
}

func TestPythonMutator_venvNotFound(t *testing.T) {
expectedError := fmt.Sprintf("failed to get Python interpreter path: can't find %q, check if virtualenv is created", interpreterPath("bad_path"))

Expand Down Expand Up @@ -569,6 +581,9 @@ func withProcessStub(t *testing.T, args []string, output, diagnostics, locations
_, err := os.Stat(inputPath)
assert.NoError(t, err)

require.Greater(t, len(actual.Args), len(args))
require.Equal(t, args, actual.Args[:len(args)])

actualInputPath := getArg(actual.Args, "--input")
actualOutputPath := getArg(actual.Args, "--output")
actualDiagnosticsPath := getArg(actual.Args, "--diagnostics")
Expand Down Expand Up @@ -623,7 +638,8 @@ func loadYaml(name, content string) *bundle.Bundle {
return b
}

func withFakeVEnv(t *testing.T, venvPath string) {
// withFakeVEnv creates a fake virtual environment and returns the absolute path of its interpreter.
func withFakeVEnv(t *testing.T, venvPath string) string {
t.Chdir(t.TempDir())

interpreterPath := interpreterPath(venvPath)
Expand All @@ -642,6 +658,10 @@ func withFakeVEnv(t *testing.T, venvPath string) {
if err != nil {
panic(err)
}

absInterpreterPath, err := filepath.Abs(interpreterPath)
require.NoError(t, err)
return absInterpreterPath
}

func interpreterPath(venvPath string) string {
Expand Down
3 changes: 2 additions & 1 deletion bundle/internal/schema/annotations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ experimental:
Example: ["my_project.resources:load_resources"]
"venv_path":
"description": |-
VEnvPath is path to the virtual environment.
VEnvPath is path to the virtual environment. A relative path is relative
to the bundle root.

If enabled, Python code will execute within this environment. If disabled,
it defaults to using the Python interpreter available in the current shell.
Expand Down
2 changes: 1 addition & 1 deletion bundle/schema/jsonschema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading