mirror of https://github.com/databricks/cli.git
Compare commits
8 Commits
84cc4a8fcd
...
0e533e1af3
Author | SHA1 | Date |
---|---|---|
Gleb Kanterov | 0e533e1af3 | |
Pieter Noordhuis | 7d732ceba8 | |
Andrew Nester | 7f3fb10c4a | |
Gleb Kanterov | 96a6cef0d6 | |
Gleb Kanterov | bfb13afa8e | |
Gleb Kanterov | 43ce278299 | |
Gleb Kanterov | df61375995 | |
Gleb Kanterov | 3438455459 |
|
@ -45,6 +45,12 @@ type PyDABs struct {
|
||||||
// These packages are imported to discover resources, resource generators, and mutators.
|
// These packages are imported to discover resources, resource generators, and mutators.
|
||||||
// This list can include namespace packages, which causes the import of nested packages.
|
// This list can include namespace packages, which causes the import of nested packages.
|
||||||
Import []string `json:"import,omitempty"`
|
Import []string `json:"import,omitempty"`
|
||||||
|
|
||||||
|
// LoadLocations is a flag to enable loading Python source locations from the PyDABs.
|
||||||
|
//
|
||||||
|
// Locations are only supported since PyDABs 0.6.0, and because of that,
|
||||||
|
// this flag is disabled by default.
|
||||||
|
LoadLocations bool `json:"load_locations,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Command string
|
type Command string
|
||||||
|
|
|
@ -44,6 +44,11 @@ func (m *prependWorkspacePrefix) Apply(ctx context.Context, b *bundle.Bundle) di
|
||||||
return dyn.InvalidValue, fmt.Errorf("expected string, got %s", v.Kind())
|
return dyn.InvalidValue, fmt.Errorf("expected string, got %s", v.Kind())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Skip prefixing if the path does not start with /, it might be variable reference or smth else.
|
||||||
|
if !strings.HasPrefix(path, "/") {
|
||||||
|
return pv, nil
|
||||||
|
}
|
||||||
|
|
||||||
for _, prefix := range skipPrefixes {
|
for _, prefix := range skipPrefixes {
|
||||||
if strings.HasPrefix(path, prefix) {
|
if strings.HasPrefix(path, prefix) {
|
||||||
return pv, nil
|
return pv, nil
|
||||||
|
|
|
@ -31,6 +31,14 @@ func TestPrependWorkspacePrefix(t *testing.T) {
|
||||||
path: "/Volumes/Users/test",
|
path: "/Volumes/Users/test",
|
||||||
expected: "/Volumes/Users/test",
|
expected: "/Volumes/Users/test",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: "~/test",
|
||||||
|
expected: "~/test",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: "${workspace.file_path}/test",
|
||||||
|
expected: "${workspace.file_path}/test",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range testCases {
|
for _, tc := range testCases {
|
||||||
|
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"github.com/databricks/cli/libs/dyn"
|
"github.com/databricks/cli/libs/dyn"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// pythonDiagnostic is a single entry in diagnostics.json
|
||||||
type pythonDiagnostic struct {
|
type pythonDiagnostic struct {
|
||||||
Severity pythonSeverity `json:"severity"`
|
Severity pythonSeverity `json:"severity"`
|
||||||
Summary string `json:"summary"`
|
Summary string `json:"summary"`
|
||||||
|
|
|
@ -0,0 +1,181 @@
|
||||||
|
package python
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/databricks/cli/libs/dyn"
|
||||||
|
)
|
||||||
|
|
||||||
|
// generatedFileName is used as the virtual file name for YAML generated by PyDABs.
|
||||||
|
//
|
||||||
|
// mergePythonLocations replaces dyn.Location with generatedFileName with locations loaded
|
||||||
|
// from locations.json
|
||||||
|
const generatedFileName = "__generated_by_pydabs__.yml"
|
||||||
|
|
||||||
|
// pythonLocations is data structure for efficient location lookup for a given path
|
||||||
|
//
|
||||||
|
// Locations form a tree, and we assign locations of the closest ancestor to each dyn.Value based on its path.
|
||||||
|
// We implement it as a trie (prefix tree) where keys are components of the path. With that, lookups are O(n)
|
||||||
|
// where n is the number of components in the path.
|
||||||
|
//
|
||||||
|
// For example, with locations.json:
|
||||||
|
//
|
||||||
|
// {"path": "resources.jobs.job_0", "file": "src/examples/job_0.py", "line": 3, "column": 5}
|
||||||
|
// {"path": "resources.jobs.job_0.tasks[0].task_key", "file": "src/examples/job_0.py", "line": 10, "column": 5}
|
||||||
|
// {"path": "resources.jobs.job_1", "file": "src/examples/job_1.py", "line": 5, "column": 7}
|
||||||
|
//
|
||||||
|
// - resources.jobs.job_0.tasks[0].task_key is located at job_0.py:10:5
|
||||||
|
//
|
||||||
|
// - resources.jobs.job_0.tasks[0].email_notifications is located at job_0.py:3:5,
|
||||||
|
// because we use the location of the job as the most precise approximation.
|
||||||
|
type pythonLocations struct {
|
||||||
|
// descendants referenced by index, e.g. '.foo'
|
||||||
|
keys map[string]*pythonLocations
|
||||||
|
|
||||||
|
// descendants referenced by key, e.g. '[0]'
|
||||||
|
indexes map[int]*pythonLocations
|
||||||
|
|
||||||
|
// location for the current node if it exists
|
||||||
|
location dyn.Location
|
||||||
|
|
||||||
|
// if true, location is present
|
||||||
|
exists bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// pythonLocationEntry is a single entry in locations.json
|
||||||
|
type pythonLocationEntry struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
File string `json:"file"`
|
||||||
|
Line int `json:"line"`
|
||||||
|
Column int `json:"column"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergePythonLocations applies locations from Python mutator into given dyn.Value
|
||||||
|
//
|
||||||
|
// The primary use-case is to merge locations.json with output.json, so that any
|
||||||
|
// validation errors will point to Python source code instead of generated YAML.
|
||||||
|
func mergePythonLocations(value dyn.Value, locations *pythonLocations) (dyn.Value, error) {
|
||||||
|
return dyn.Walk(value, func(path dyn.Path, value dyn.Value) (dyn.Value, error) {
|
||||||
|
newLocation, ok := findPythonLocation(locations, path)
|
||||||
|
if !ok {
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var newLocations []dyn.Location
|
||||||
|
|
||||||
|
// the first item in the list is the "last" location used for error reporting
|
||||||
|
newLocations = append(newLocations, newLocation)
|
||||||
|
|
||||||
|
for _, location := range value.Locations() {
|
||||||
|
// When loaded, dyn.Value created by PyDABs use the virtual file path as their location,
|
||||||
|
// we replace it with newLocation.
|
||||||
|
if filepath.Base(location.File) == generatedFileName {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
newLocations = append(newLocations, location)
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.WithLocations(newLocations), nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// parsePythonLocations parses locations.json from the Python mutator.
|
||||||
|
//
|
||||||
|
// locations file is newline-separated JSON objects with pythonLocationEntry structure.
|
||||||
|
func parsePythonLocations(input io.Reader) (*pythonLocations, error) {
|
||||||
|
decoder := json.NewDecoder(input)
|
||||||
|
locations := newPythonLocations()
|
||||||
|
|
||||||
|
for decoder.More() {
|
||||||
|
var entry pythonLocationEntry
|
||||||
|
|
||||||
|
err := decoder.Decode(&entry)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse python location: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
path, err := dyn.NewPathFromString(entry.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse python location: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
location := dyn.Location{
|
||||||
|
File: entry.File,
|
||||||
|
Line: entry.Line,
|
||||||
|
Column: entry.Column,
|
||||||
|
}
|
||||||
|
|
||||||
|
putPythonLocation(locations, path, location)
|
||||||
|
}
|
||||||
|
|
||||||
|
return locations, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// putPythonLocation puts the location to the trie for the given path
|
||||||
|
func putPythonLocation(trie *pythonLocations, path dyn.Path, location dyn.Location) {
|
||||||
|
var currentNode = trie
|
||||||
|
|
||||||
|
for _, component := range path {
|
||||||
|
if key := component.Key(); key != "" {
|
||||||
|
if _, ok := currentNode.keys[key]; !ok {
|
||||||
|
currentNode.keys[key] = newPythonLocations()
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode = currentNode.keys[key]
|
||||||
|
} else {
|
||||||
|
index := component.Index()
|
||||||
|
if _, ok := currentNode.indexes[index]; !ok {
|
||||||
|
currentNode.indexes[index] = newPythonLocations()
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode = currentNode.indexes[index]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode.location = location
|
||||||
|
currentNode.exists = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// newPythonLocations creates a new trie node
|
||||||
|
func newPythonLocations() *pythonLocations {
|
||||||
|
return &pythonLocations{
|
||||||
|
keys: make(map[string]*pythonLocations),
|
||||||
|
indexes: make(map[int]*pythonLocations),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// findPythonLocation finds the location or closest ancestor location in the trie for the given path
|
||||||
|
// if no ancestor or exact location is found, false is returned.
|
||||||
|
func findPythonLocation(locations *pythonLocations, path dyn.Path) (dyn.Location, bool) {
|
||||||
|
var currentNode = locations
|
||||||
|
var lastLocation = locations.location
|
||||||
|
var exists = locations.exists
|
||||||
|
|
||||||
|
for _, component := range path {
|
||||||
|
if key := component.Key(); key != "" {
|
||||||
|
if _, ok := currentNode.keys[key]; !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode = currentNode.keys[key]
|
||||||
|
} else {
|
||||||
|
index := component.Index()
|
||||||
|
if _, ok := currentNode.indexes[index]; !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
currentNode = currentNode.indexes[index]
|
||||||
|
}
|
||||||
|
|
||||||
|
if currentNode.exists {
|
||||||
|
lastLocation = currentNode.location
|
||||||
|
exists = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lastLocation, exists
|
||||||
|
}
|
|
@ -0,0 +1,124 @@
|
||||||
|
package python
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/databricks/cli/libs/dyn"
|
||||||
|
assert "github.com/databricks/cli/libs/dyn/dynassert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMergeLocations(t *testing.T) {
|
||||||
|
pythonLocation := dyn.Location{File: "foo.py", Line: 1, Column: 1}
|
||||||
|
generatedLocation := dyn.Location{File: generatedFileName, Line: 1, Column: 1}
|
||||||
|
yamlLocation := dyn.Location{File: "foo.yml", Line: 1, Column: 1}
|
||||||
|
|
||||||
|
locations := newPythonLocations()
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo"), pythonLocation)
|
||||||
|
|
||||||
|
input := dyn.NewValue(
|
||||||
|
map[string]dyn.Value{
|
||||||
|
"foo": dyn.NewValue(
|
||||||
|
map[string]dyn.Value{
|
||||||
|
"baz": dyn.NewValue("baz", []dyn.Location{yamlLocation}),
|
||||||
|
"qux": dyn.NewValue("baz", []dyn.Location{generatedLocation, yamlLocation}),
|
||||||
|
},
|
||||||
|
[]dyn.Location{},
|
||||||
|
),
|
||||||
|
"bar": dyn.NewValue("baz", []dyn.Location{generatedLocation}),
|
||||||
|
},
|
||||||
|
[]dyn.Location{yamlLocation},
|
||||||
|
)
|
||||||
|
|
||||||
|
expected := dyn.NewValue(
|
||||||
|
map[string]dyn.Value{
|
||||||
|
"foo": dyn.NewValue(
|
||||||
|
map[string]dyn.Value{
|
||||||
|
// pythonLocation is appended to the beginning of the list if absent
|
||||||
|
"baz": dyn.NewValue("baz", []dyn.Location{pythonLocation, yamlLocation}),
|
||||||
|
// generatedLocation is replaced by pythonLocation
|
||||||
|
"qux": dyn.NewValue("baz", []dyn.Location{pythonLocation, yamlLocation}),
|
||||||
|
},
|
||||||
|
[]dyn.Location{pythonLocation},
|
||||||
|
),
|
||||||
|
// if location is unknown, we keep it as-is
|
||||||
|
"bar": dyn.NewValue("baz", []dyn.Location{generatedLocation}),
|
||||||
|
},
|
||||||
|
[]dyn.Location{yamlLocation},
|
||||||
|
)
|
||||||
|
|
||||||
|
actual, err := mergePythonLocations(input, locations)
|
||||||
|
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, expected, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindLocation(t *testing.T) {
|
||||||
|
location0 := dyn.Location{File: "foo.py", Line: 1, Column: 1}
|
||||||
|
location1 := dyn.Location{File: "foo.py", Line: 2, Column: 1}
|
||||||
|
|
||||||
|
locations := newPythonLocations()
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo"), location0)
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo.bar"), location1)
|
||||||
|
|
||||||
|
actual, exists := findPythonLocation(locations, dyn.MustPathFromString("foo.bar"))
|
||||||
|
|
||||||
|
assert.True(t, exists)
|
||||||
|
assert.Equal(t, location1, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindLocation_indexPathComponent(t *testing.T) {
|
||||||
|
location0 := dyn.Location{File: "foo.py", Line: 1, Column: 1}
|
||||||
|
location1 := dyn.Location{File: "foo.py", Line: 2, Column: 1}
|
||||||
|
location2 := dyn.Location{File: "foo.py", Line: 3, Column: 1}
|
||||||
|
|
||||||
|
locations := newPythonLocations()
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo"), location0)
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo.bar"), location1)
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo.bar[0]"), location2)
|
||||||
|
|
||||||
|
actual, exists := findPythonLocation(locations, dyn.MustPathFromString("foo.bar[0]"))
|
||||||
|
|
||||||
|
assert.True(t, exists)
|
||||||
|
assert.Equal(t, location2, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindLocation_closestAncestorLocation(t *testing.T) {
|
||||||
|
location0 := dyn.Location{File: "foo.py", Line: 1, Column: 1}
|
||||||
|
location1 := dyn.Location{File: "foo.py", Line: 2, Column: 1}
|
||||||
|
|
||||||
|
locations := newPythonLocations()
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo"), location0)
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo.bar"), location1)
|
||||||
|
|
||||||
|
actual, exists := findPythonLocation(locations, dyn.MustPathFromString("foo.bar.baz"))
|
||||||
|
|
||||||
|
assert.True(t, exists)
|
||||||
|
assert.Equal(t, location1, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindLocation_unknownLocation(t *testing.T) {
|
||||||
|
location0 := dyn.Location{File: "foo.py", Line: 1, Column: 1}
|
||||||
|
location1 := dyn.Location{File: "foo.py", Line: 2, Column: 1}
|
||||||
|
|
||||||
|
locations := newPythonLocations()
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo"), location0)
|
||||||
|
putPythonLocation(locations, dyn.MustPathFromString("foo.bar"), location1)
|
||||||
|
|
||||||
|
_, exists := findPythonLocation(locations, dyn.MustPathFromString("bar"))
|
||||||
|
|
||||||
|
assert.False(t, exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParsePythonLocations(t *testing.T) {
|
||||||
|
expected := dyn.Location{File: "foo.py", Line: 1, Column: 2}
|
||||||
|
|
||||||
|
input := `{"path": "foo", "file": "foo.py", "line": 1, "column": 2}`
|
||||||
|
reader := bytes.NewReader([]byte(input))
|
||||||
|
locations, err := parsePythonLocations(reader)
|
||||||
|
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
assert.True(t, locations.keys["foo"].exists)
|
||||||
|
assert.Equal(t, expected, locations.keys["foo"].location)
|
||||||
|
}
|
|
@ -7,9 +7,12 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/databricks/cli/bundle/config/mutator/paths"
|
||||||
|
|
||||||
"github.com/databricks/databricks-sdk-go/logger"
|
"github.com/databricks/databricks-sdk-go/logger"
|
||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
|
|
||||||
|
@ -108,7 +111,12 @@ func (m *pythonMutator) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagno
|
||||||
return dyn.InvalidValue, fmt.Errorf("failed to create cache dir: %w", err)
|
return dyn.InvalidValue, fmt.Errorf("failed to create cache dir: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
rightRoot, diags := m.runPythonMutator(ctx, cacheDir, b.BundleRootPath, pythonPath, leftRoot)
|
rightRoot, diags := m.runPythonMutator(ctx, leftRoot, runPythonMutatorOpts{
|
||||||
|
cacheDir: cacheDir,
|
||||||
|
bundleRootPath: b.BundleRootPath,
|
||||||
|
pythonPath: pythonPath,
|
||||||
|
loadLocations: experimental.PyDABs.LoadLocations,
|
||||||
|
})
|
||||||
mutateDiags = diags
|
mutateDiags = diags
|
||||||
if diags.HasError() {
|
if diags.HasError() {
|
||||||
return dyn.InvalidValue, mutateDiagsHasError
|
return dyn.InvalidValue, mutateDiagsHasError
|
||||||
|
@ -152,13 +160,21 @@ func createCacheDir(ctx context.Context) (string, error) {
|
||||||
return os.MkdirTemp("", "-pydabs")
|
return os.MkdirTemp("", "-pydabs")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir string, rootPath string, pythonPath string, root dyn.Value) (dyn.Value, diag.Diagnostics) {
|
type runPythonMutatorOpts struct {
|
||||||
inputPath := filepath.Join(cacheDir, "input.json")
|
cacheDir string
|
||||||
outputPath := filepath.Join(cacheDir, "output.json")
|
bundleRootPath string
|
||||||
diagnosticsPath := filepath.Join(cacheDir, "diagnostics.json")
|
pythonPath string
|
||||||
|
loadLocations bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *pythonMutator) runPythonMutator(ctx context.Context, root dyn.Value, opts runPythonMutatorOpts) (dyn.Value, diag.Diagnostics) {
|
||||||
|
inputPath := filepath.Join(opts.cacheDir, "input.json")
|
||||||
|
outputPath := filepath.Join(opts.cacheDir, "output.json")
|
||||||
|
diagnosticsPath := filepath.Join(opts.cacheDir, "diagnostics.json")
|
||||||
|
locationsPath := filepath.Join(opts.cacheDir, "locations.json")
|
||||||
|
|
||||||
args := []string{
|
args := []string{
|
||||||
pythonPath,
|
opts.pythonPath,
|
||||||
"-m",
|
"-m",
|
||||||
"databricks.bundles.build",
|
"databricks.bundles.build",
|
||||||
"--phase",
|
"--phase",
|
||||||
|
@ -171,6 +187,10 @@ func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir string, r
|
||||||
diagnosticsPath,
|
diagnosticsPath,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if opts.loadLocations {
|
||||||
|
args = append(args, "--locations", locationsPath)
|
||||||
|
}
|
||||||
|
|
||||||
if err := writeInputFile(inputPath, root); err != nil {
|
if err := writeInputFile(inputPath, root); err != nil {
|
||||||
return dyn.InvalidValue, diag.Errorf("failed to write input file: %s", err)
|
return dyn.InvalidValue, diag.Errorf("failed to write input file: %s", err)
|
||||||
}
|
}
|
||||||
|
@ -185,7 +205,7 @@ func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir string, r
|
||||||
_, processErr := process.Background(
|
_, processErr := process.Background(
|
||||||
ctx,
|
ctx,
|
||||||
args,
|
args,
|
||||||
process.WithDir(rootPath),
|
process.WithDir(opts.bundleRootPath),
|
||||||
process.WithStderrWriter(stderrWriter),
|
process.WithStderrWriter(stderrWriter),
|
||||||
process.WithStdoutWriter(stdoutWriter),
|
process.WithStdoutWriter(stdoutWriter),
|
||||||
)
|
)
|
||||||
|
@ -221,7 +241,12 @@ func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir string, r
|
||||||
return dyn.InvalidValue, diag.Errorf("failed to load diagnostics: %s", pythonDiagnosticsErr)
|
return dyn.InvalidValue, diag.Errorf("failed to load diagnostics: %s", pythonDiagnosticsErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
output, outputDiags := loadOutputFile(rootPath, outputPath)
|
locations, err := loadLocationsFile(locationsPath)
|
||||||
|
if err != nil {
|
||||||
|
return dyn.InvalidValue, diag.Errorf("failed to load locations: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
output, outputDiags := loadOutputFile(opts.bundleRootPath, outputPath, locations)
|
||||||
pythonDiagnostics = pythonDiagnostics.Extend(outputDiags)
|
pythonDiagnostics = pythonDiagnostics.Extend(outputDiags)
|
||||||
|
|
||||||
// we pass through pythonDiagnostic because it contains warnings
|
// we pass through pythonDiagnostic because it contains warnings
|
||||||
|
@ -266,7 +291,21 @@ func writeInputFile(inputPath string, input dyn.Value) error {
|
||||||
return os.WriteFile(inputPath, rootConfigJson, 0600)
|
return os.WriteFile(inputPath, rootConfigJson, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadOutputFile(rootPath string, outputPath string) (dyn.Value, diag.Diagnostics) {
|
// loadLocationsFile loads locations.json containing source locations for generated YAML.
|
||||||
|
func loadLocationsFile(locationsPath string) (*pythonLocations, error) {
|
||||||
|
locationsFile, err := os.Open(locationsPath)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return newPythonLocations(), nil
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to open locations file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer locationsFile.Close()
|
||||||
|
|
||||||
|
return parsePythonLocations(locationsFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOutputFile(rootPath string, outputPath string, locations *pythonLocations) (dyn.Value, diag.Diagnostics) {
|
||||||
outputFile, err := os.Open(outputPath)
|
outputFile, err := os.Open(outputPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to open output file: %w", err))
|
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to open output file: %w", err))
|
||||||
|
@ -277,12 +316,12 @@ func loadOutputFile(rootPath string, outputPath string) (dyn.Value, diag.Diagnos
|
||||||
// we need absolute path because later parts of pipeline assume all paths are absolute
|
// we need absolute path because later parts of pipeline assume all paths are absolute
|
||||||
// and this file will be used as location to resolve relative paths.
|
// and this file will be used as location to resolve relative paths.
|
||||||
//
|
//
|
||||||
// virtualPath has to stay in rootPath, because locations outside root path are not allowed:
|
// virtualPath has to stay in bundleRootPath, because locations outside root path are not allowed:
|
||||||
//
|
//
|
||||||
// Error: path /var/folders/.../pydabs/dist/*.whl is not contained in bundle root path
|
// Error: path /var/folders/.../pydabs/dist/*.whl is not contained in bundle root path
|
||||||
//
|
//
|
||||||
// for that, we pass virtualPath instead of outputPath as file location
|
// for that, we pass virtualPath instead of outputPath as file location
|
||||||
virtualPath, err := filepath.Abs(filepath.Join(rootPath, "__generated_by_pydabs__.yml"))
|
virtualPath, err := filepath.Abs(filepath.Join(rootPath, generatedFileName))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to get absolute path: %w", err))
|
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to get absolute path: %w", err))
|
||||||
}
|
}
|
||||||
|
@ -292,7 +331,25 @@ func loadOutputFile(rootPath string, outputPath string) (dyn.Value, diag.Diagnos
|
||||||
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to parse output file: %w", err))
|
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to parse output file: %w", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
return strictNormalize(config.Root{}, generated)
|
// paths are resolved relative to locations of their values, if we change location
|
||||||
|
// we have to update each path, until we simplify that, we don't update locations
|
||||||
|
// for such values, so we don't change how paths are resolved
|
||||||
|
_, err = paths.VisitJobPaths(generated, func(p dyn.Path, kind paths.PathKind, v dyn.Value) (dyn.Value, error) {
|
||||||
|
putPythonLocation(locations, p, v.Location())
|
||||||
|
return v, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to update locations: %w", err))
|
||||||
|
}
|
||||||
|
|
||||||
|
// generated has dyn.Location as if it comes from generated YAML file
|
||||||
|
// earlier we loaded locations.json with source locations in Python code
|
||||||
|
generatedWithLocations, err := mergePythonLocations(generated, locations)
|
||||||
|
if err != nil {
|
||||||
|
return dyn.InvalidValue, diag.FromErr(fmt.Errorf("failed to update locations: %w", err))
|
||||||
|
}
|
||||||
|
|
||||||
|
return strictNormalize(config.Root{}, generatedWithLocations)
|
||||||
}
|
}
|
||||||
|
|
||||||
func strictNormalize(dst any, generated dyn.Value) (dyn.Value, diag.Diagnostics) {
|
func strictNormalize(dst any, generated dyn.Value) (dyn.Value, diag.Diagnostics) {
|
||||||
|
|
|
@ -6,7 +6,6 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
@ -47,6 +46,7 @@ func TestPythonMutator_load(t *testing.T) {
|
||||||
pydabs:
|
pydabs:
|
||||||
enabled: true
|
enabled: true
|
||||||
venv_path: .venv
|
venv_path: .venv
|
||||||
|
load_locations: true
|
||||||
resources:
|
resources:
|
||||||
jobs:
|
jobs:
|
||||||
job0:
|
job0:
|
||||||
|
@ -65,7 +65,8 @@ func TestPythonMutator_load(t *testing.T) {
|
||||||
"experimental": {
|
"experimental": {
|
||||||
"pydabs": {
|
"pydabs": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"venv_path": ".venv"
|
"venv_path": ".venv",
|
||||||
|
"load_locations": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"resources": {
|
"resources": {
|
||||||
|
@ -80,6 +81,8 @@ func TestPythonMutator_load(t *testing.T) {
|
||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
`{"severity": "warning", "summary": "job doesn't have any tasks", "location": {"file": "src/examples/file.py", "line": 10, "column": 5}}`,
|
`{"severity": "warning", "summary": "job doesn't have any tasks", "location": {"file": "src/examples/file.py", "line": 10, "column": 5}}`,
|
||||||
|
`{"path": "resources.jobs.job0", "file": "src/examples/job0.py", "line": 3, "column": 5}
|
||||||
|
{"path": "resources.jobs.job1", "file": "src/examples/job1.py", "line": 5, "column": 7}`,
|
||||||
)
|
)
|
||||||
|
|
||||||
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
||||||
|
@ -97,6 +100,25 @@ func TestPythonMutator_load(t *testing.T) {
|
||||||
assert.Equal(t, "job_1", job1.Name)
|
assert.Equal(t, "job_1", job1.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// output of locations.json should be applied to underlying dyn.Value
|
||||||
|
err := b.Config.Mutate(func(v dyn.Value) (dyn.Value, error) {
|
||||||
|
name1, err := dyn.GetByPath(v, dyn.MustPathFromString("resources.jobs.job1.name"))
|
||||||
|
if err != nil {
|
||||||
|
return dyn.InvalidValue, err
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, []dyn.Location{
|
||||||
|
{
|
||||||
|
File: "src/examples/job1.py",
|
||||||
|
Line: 5,
|
||||||
|
Column: 7,
|
||||||
|
},
|
||||||
|
}, name1.Locations())
|
||||||
|
|
||||||
|
return v, nil
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
assert.Equal(t, 1, len(diags))
|
assert.Equal(t, 1, len(diags))
|
||||||
assert.Equal(t, "job doesn't have any tasks", diags[0].Summary)
|
assert.Equal(t, "job doesn't have any tasks", diags[0].Summary)
|
||||||
assert.Equal(t, []dyn.Location{
|
assert.Equal(t, []dyn.Location{
|
||||||
|
@ -106,7 +128,6 @@ func TestPythonMutator_load(t *testing.T) {
|
||||||
Column: 5,
|
Column: 5,
|
||||||
},
|
},
|
||||||
}, diags[0].Locations)
|
}, diags[0].Locations)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPythonMutator_load_disallowed(t *testing.T) {
|
func TestPythonMutator_load_disallowed(t *testing.T) {
|
||||||
|
@ -146,7 +167,7 @@ func TestPythonMutator_load_disallowed(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}`, "")
|
}`, "", "")
|
||||||
|
|
||||||
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
||||||
diag := bundle.Apply(ctx, b, mutator)
|
diag := bundle.Apply(ctx, b, mutator)
|
||||||
|
@ -191,7 +212,7 @@ func TestPythonMutator_init(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}`, "")
|
}`, "", "")
|
||||||
|
|
||||||
mutator := PythonMutator(PythonMutatorPhaseInit)
|
mutator := PythonMutator(PythonMutatorPhaseInit)
|
||||||
diag := bundle.Apply(ctx, b, mutator)
|
diag := bundle.Apply(ctx, b, mutator)
|
||||||
|
@ -252,7 +273,7 @@ func TestPythonMutator_badOutput(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}`, "")
|
}`, "", "")
|
||||||
|
|
||||||
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
||||||
diag := bundle.Apply(ctx, b, mutator)
|
diag := bundle.Apply(ctx, b, mutator)
|
||||||
|
@ -588,7 +609,7 @@ or activate the environment before running CLI commands:
|
||||||
assert.Equal(t, expected, out)
|
assert.Equal(t, expected, out)
|
||||||
}
|
}
|
||||||
|
|
||||||
func withProcessStub(t *testing.T, args []string, output string, diagnostics string) context.Context {
|
func withProcessStub(t *testing.T, args []string, output string, diagnostics string, locations string) context.Context {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
ctx, stub := process.WithStub(ctx)
|
ctx, stub := process.WithStub(ctx)
|
||||||
|
|
||||||
|
@ -600,32 +621,51 @@ func withProcessStub(t *testing.T, args []string, output string, diagnostics str
|
||||||
|
|
||||||
inputPath := filepath.Join(cacheDir, "input.json")
|
inputPath := filepath.Join(cacheDir, "input.json")
|
||||||
outputPath := filepath.Join(cacheDir, "output.json")
|
outputPath := filepath.Join(cacheDir, "output.json")
|
||||||
|
locationsPath := filepath.Join(cacheDir, "locations.json")
|
||||||
diagnosticsPath := filepath.Join(cacheDir, "diagnostics.json")
|
diagnosticsPath := filepath.Join(cacheDir, "diagnostics.json")
|
||||||
|
|
||||||
args = append(args, "--input", inputPath)
|
|
||||||
args = append(args, "--output", outputPath)
|
|
||||||
args = append(args, "--diagnostics", diagnosticsPath)
|
|
||||||
|
|
||||||
stub.WithCallback(func(actual *exec.Cmd) error {
|
stub.WithCallback(func(actual *exec.Cmd) error {
|
||||||
_, err := os.Stat(inputPath)
|
_, err := os.Stat(inputPath)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
if reflect.DeepEqual(actual.Args, args) {
|
actualInputPath := getArg(actual.Args, "--input")
|
||||||
err := os.WriteFile(outputPath, []byte(output), 0600)
|
actualOutputPath := getArg(actual.Args, "--output")
|
||||||
require.NoError(t, err)
|
actualDiagnosticsPath := getArg(actual.Args, "--diagnostics")
|
||||||
|
actualLocationsPath := getArg(actual.Args, "--locations")
|
||||||
|
|
||||||
err = os.WriteFile(diagnosticsPath, []byte(diagnostics), 0600)
|
require.Equal(t, inputPath, actualInputPath)
|
||||||
require.NoError(t, err)
|
require.Equal(t, outputPath, actualOutputPath)
|
||||||
|
require.Equal(t, diagnosticsPath, actualDiagnosticsPath)
|
||||||
|
|
||||||
return nil
|
// locations is an optional argument
|
||||||
} else {
|
if locations != "" {
|
||||||
return fmt.Errorf("unexpected command: %v", actual.Args)
|
require.Equal(t, locationsPath, actualLocationsPath)
|
||||||
|
|
||||||
|
err = os.WriteFile(locationsPath, []byte(locations), 0600)
|
||||||
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = os.WriteFile(outputPath, []byte(output), 0600)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
err = os.WriteFile(diagnosticsPath, []byte(diagnostics), 0600)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
return ctx
|
return ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getArg(args []string, name string) string {
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
if args[i] == name {
|
||||||
|
return args[i+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func loadYaml(name string, content string) *bundle.Bundle {
|
func loadYaml(name string, content string) *bundle.Bundle {
|
||||||
v, diag := config.LoadFromBytes(name, []byte(content))
|
v, diag := config.LoadFromBytes(name, []byte(content))
|
||||||
|
|
||||||
|
|
|
@ -7,6 +7,7 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/databricks/cli/cmd/root"
|
"github.com/databricks/cli/cmd/root"
|
||||||
|
"github.com/databricks/cli/libs/fakefs"
|
||||||
"github.com/databricks/cli/libs/filer"
|
"github.com/databricks/cli/libs/filer"
|
||||||
"github.com/databricks/databricks-sdk-go/experimental/mocks"
|
"github.com/databricks/databricks-sdk-go/experimental/mocks"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
@ -84,7 +85,7 @@ func setupTest(t *testing.T) (*validArgs, *cobra.Command, *mocks.MockWorkspaceCl
|
||||||
cmd, m := setupCommand(t)
|
cmd, m := setupCommand(t)
|
||||||
|
|
||||||
fakeFilerForPath := func(ctx context.Context, fullPath string) (filer.Filer, string, error) {
|
fakeFilerForPath := func(ctx context.Context, fullPath string) (filer.Filer, string, error) {
|
||||||
fakeFiler := filer.NewFakeFiler(map[string]filer.FakeFileInfo{
|
fakeFiler := filer.NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
"dir": {FakeName: "root", FakeDir: true},
|
"dir": {FakeName: "root", FakeDir: true},
|
||||||
"dir/dirA": {FakeDir: true},
|
"dir/dirA": {FakeDir: true},
|
||||||
"dir/dirB": {FakeDir: true},
|
"dir/dirB": {FakeDir: true},
|
||||||
|
|
|
@ -1,18 +1,21 @@
|
||||||
package fakefs
|
package fakefs
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrNotImplemented = fmt.Errorf("not implemented")
|
||||||
|
|
||||||
// DirEntry is a fake implementation of [fs.DirEntry].
|
// DirEntry is a fake implementation of [fs.DirEntry].
|
||||||
type DirEntry struct {
|
type DirEntry struct {
|
||||||
FileInfo
|
fs.FileInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry DirEntry) Type() fs.FileMode {
|
func (entry DirEntry) Type() fs.FileMode {
|
||||||
typ := fs.ModePerm
|
typ := fs.ModePerm
|
||||||
if entry.FakeDir {
|
if entry.IsDir() {
|
||||||
typ |= fs.ModeDir
|
typ |= fs.ModeDir
|
||||||
}
|
}
|
||||||
return typ
|
return typ
|
||||||
|
@ -53,3 +56,32 @@ func (info FileInfo) IsDir() bool {
|
||||||
func (info FileInfo) Sys() any {
|
func (info FileInfo) Sys() any {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// File is a fake implementation of [fs.File].
|
||||||
|
type File struct {
|
||||||
|
FileInfo fs.FileInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f File) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f File) Read(p []byte) (n int, err error) {
|
||||||
|
return 0, ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f File) Stat() (fs.FileInfo, error) {
|
||||||
|
return f.FileInfo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FS is a fake implementation of [fs.FS].
|
||||||
|
type FS map[string]fs.File
|
||||||
|
|
||||||
|
func (f FS) Open(name string) (fs.File, error) {
|
||||||
|
e, ok := f[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fs.ErrNotExist
|
||||||
|
}
|
||||||
|
|
||||||
|
return e, nil
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,38 @@
|
||||||
|
package fakefs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFile(t *testing.T) {
|
||||||
|
var fakefile fs.File = File{
|
||||||
|
FileInfo: FileInfo{
|
||||||
|
FakeName: "file",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := fakefile.Read([]byte{})
|
||||||
|
assert.ErrorIs(t, err, ErrNotImplemented)
|
||||||
|
|
||||||
|
fi, err := fakefile.Stat()
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, "file", fi.Name())
|
||||||
|
|
||||||
|
err = fakefile.Close()
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFS(t *testing.T) {
|
||||||
|
var fakefs fs.FS = FS{
|
||||||
|
"file": File{},
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := fakefs.Open("doesntexist")
|
||||||
|
assert.ErrorIs(t, err, fs.ErrNotExist)
|
||||||
|
|
||||||
|
_, err = fakefs.Open("file")
|
||||||
|
assert.NoError(t, err)
|
||||||
|
}
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/databricks/cli/cmd/root"
|
"github.com/databricks/cli/cmd/root"
|
||||||
|
"github.com/databricks/cli/libs/fakefs"
|
||||||
"github.com/databricks/cli/libs/filer"
|
"github.com/databricks/cli/libs/filer"
|
||||||
"github.com/databricks/databricks-sdk-go/experimental/mocks"
|
"github.com/databricks/databricks-sdk-go/experimental/mocks"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
@ -17,7 +18,7 @@ func setupCompleter(t *testing.T, onlyDirs bool) *completer {
|
||||||
// Needed to make type context.valueCtx for mockFilerForPath
|
// Needed to make type context.valueCtx for mockFilerForPath
|
||||||
ctx = root.SetWorkspaceClient(ctx, mocks.NewMockWorkspaceClient(t).WorkspaceClient)
|
ctx = root.SetWorkspaceClient(ctx, mocks.NewMockWorkspaceClient(t).WorkspaceClient)
|
||||||
|
|
||||||
fakeFiler := filer.NewFakeFiler(map[string]filer.FakeFileInfo{
|
fakeFiler := filer.NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
"dir": {FakeName: "root", FakeDir: true},
|
"dir": {FakeName: "root", FakeDir: true},
|
||||||
"dir/dirA": {FakeDir: true},
|
"dir/dirA": {FakeDir: true},
|
||||||
"dir/dirB": {FakeDir: true},
|
"dir/dirB": {FakeDir: true},
|
||||||
|
|
|
@ -8,58 +8,12 @@ import (
|
||||||
"path"
|
"path"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
"github.com/databricks/cli/libs/fakefs"
|
||||||
)
|
)
|
||||||
|
|
||||||
type FakeDirEntry struct {
|
|
||||||
FakeFileInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry FakeDirEntry) Type() fs.FileMode {
|
|
||||||
typ := fs.ModePerm
|
|
||||||
if entry.FakeDir {
|
|
||||||
typ |= fs.ModeDir
|
|
||||||
}
|
|
||||||
return typ
|
|
||||||
}
|
|
||||||
|
|
||||||
func (entry FakeDirEntry) Info() (fs.FileInfo, error) {
|
|
||||||
return entry.FakeFileInfo, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type FakeFileInfo struct {
|
|
||||||
FakeName string
|
|
||||||
FakeSize int64
|
|
||||||
FakeDir bool
|
|
||||||
FakeMode fs.FileMode
|
|
||||||
}
|
|
||||||
|
|
||||||
func (info FakeFileInfo) Name() string {
|
|
||||||
return info.FakeName
|
|
||||||
}
|
|
||||||
|
|
||||||
func (info FakeFileInfo) Size() int64 {
|
|
||||||
return info.FakeSize
|
|
||||||
}
|
|
||||||
|
|
||||||
func (info FakeFileInfo) Mode() fs.FileMode {
|
|
||||||
return info.FakeMode
|
|
||||||
}
|
|
||||||
|
|
||||||
func (info FakeFileInfo) ModTime() time.Time {
|
|
||||||
return time.Now()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (info FakeFileInfo) IsDir() bool {
|
|
||||||
return info.FakeDir
|
|
||||||
}
|
|
||||||
|
|
||||||
func (info FakeFileInfo) Sys() any {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type FakeFiler struct {
|
type FakeFiler struct {
|
||||||
entries map[string]FakeFileInfo
|
entries map[string]fakefs.FileInfo
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FakeFiler) Write(ctx context.Context, p string, reader io.Reader, mode ...WriteMode) error {
|
func (f *FakeFiler) Write(ctx context.Context, p string, reader io.Reader, mode ...WriteMode) error {
|
||||||
|
@ -97,7 +51,7 @@ func (f *FakeFiler) ReadDir(ctx context.Context, p string) ([]fs.DirEntry, error
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
out = append(out, FakeDirEntry{v})
|
out = append(out, fakefs.DirEntry{FileInfo: v})
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
|
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
|
||||||
|
@ -117,7 +71,11 @@ func (f *FakeFiler) Stat(ctx context.Context, path string) (fs.FileInfo, error)
|
||||||
return entry, nil
|
return entry, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFakeFiler(entries map[string]FakeFileInfo) *FakeFiler {
|
// NewFakeFiler creates a new fake [Filer] instance with the given entries.
|
||||||
|
// It sets the [Name] field of each entry to the base name of the path.
|
||||||
|
//
|
||||||
|
// This is meant to be used in tests.
|
||||||
|
func NewFakeFiler(entries map[string]fakefs.FileInfo) *FakeFiler {
|
||||||
fakeFiler := &FakeFiler{
|
fakeFiler := &FakeFiler{
|
||||||
entries: entries,
|
entries: entries,
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,98 @@
|
||||||
|
package filer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/databricks/cli/libs/fakefs"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFakeFiler_Read(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"file": {},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
r, err := f.Read(ctx, "file")
|
||||||
|
require.NoError(t, err)
|
||||||
|
contents, err := io.ReadAll(r)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// Contents of every file is "foo".
|
||||||
|
assert.Equal(t, "foo", string(contents))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFakeFiler_Read_NotFound(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"foo": {},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
_, err := f.Read(ctx, "bar")
|
||||||
|
assert.ErrorIs(t, err, fs.ErrNotExist)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFakeFiler_ReadDir_NotFound(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"dir1": {FakeDir: true},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
_, err := f.ReadDir(ctx, "dir2")
|
||||||
|
assert.ErrorIs(t, err, fs.ErrNotExist)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFakeFiler_ReadDir_NotADirectory(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"file": {},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
_, err := f.ReadDir(ctx, "file")
|
||||||
|
assert.ErrorIs(t, err, fs.ErrInvalid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFakeFiler_ReadDir(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"dir1": {FakeDir: true},
|
||||||
|
"dir1/file2": {},
|
||||||
|
"dir1/dir2": {FakeDir: true},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
entries, err := f.ReadDir(ctx, "dir1/")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, entries, 2)
|
||||||
|
|
||||||
|
// The entries are sorted by name.
|
||||||
|
assert.Equal(t, "dir2", entries[0].Name())
|
||||||
|
assert.True(t, entries[0].IsDir())
|
||||||
|
assert.Equal(t, "file2", entries[1].Name())
|
||||||
|
assert.False(t, entries[1].IsDir())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFakeFiler_Stat(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"file": {},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
info, err := f.Stat(ctx, "file")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
assert.Equal(t, "file", info.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFakeFiler_Stat_NotFound(t *testing.T) {
|
||||||
|
f := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
|
"foo": {},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
_, err := f.Stat(ctx, "bar")
|
||||||
|
assert.ErrorIs(t, err, fs.ErrNotExist)
|
||||||
|
}
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/databricks/cli/libs/fakefs"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
@ -35,7 +36,7 @@ func TestFsDirImplementsFsReadDirFile(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func fakeFS() fs.FS {
|
func fakeFS() fs.FS {
|
||||||
fakeFiler := NewFakeFiler(map[string]FakeFileInfo{
|
fakeFiler := NewFakeFiler(map[string]fakefs.FileInfo{
|
||||||
".": {FakeName: "root", FakeDir: true},
|
".": {FakeName: "root", FakeDir: true},
|
||||||
"dirA": {FakeDir: true},
|
"dirA": {FakeDir: true},
|
||||||
"dirB": {FakeDir: true},
|
"dirB": {FakeDir: true},
|
||||||
|
|
|
@ -7,6 +7,7 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/databricks/cli/libs/fakefs"
|
||||||
"github.com/databricks/databricks-sdk-go/service/workspace"
|
"github.com/databricks/databricks-sdk-go/service/workspace"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
@ -100,11 +101,21 @@ func TestDetectFileWithLongHeader(t *testing.T) {
|
||||||
assert.False(t, nb)
|
assert.False(t, nb)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type fileInfoWithWorkspaceInfo struct {
|
||||||
|
fakefs.FileInfo
|
||||||
|
|
||||||
|
oi workspace.ObjectInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fileInfoWithWorkspaceInfo) WorkspaceObjectInfo() workspace.ObjectInfo {
|
||||||
|
return f.oi
|
||||||
|
}
|
||||||
|
|
||||||
func TestDetectWithObjectInfo(t *testing.T) {
|
func TestDetectWithObjectInfo(t *testing.T) {
|
||||||
fakeFS := &fakeFS{
|
fakefs := fakefs.FS{
|
||||||
fakeFile{
|
"file.py": fakefs.File{
|
||||||
fakeFileInfo{
|
FileInfo: fileInfoWithWorkspaceInfo{
|
||||||
workspace.ObjectInfo{
|
oi: workspace.ObjectInfo{
|
||||||
ObjectType: workspace.ObjectTypeNotebook,
|
ObjectType: workspace.ObjectTypeNotebook,
|
||||||
Language: workspace.LanguagePython,
|
Language: workspace.LanguagePython,
|
||||||
},
|
},
|
||||||
|
@ -112,7 +123,7 @@ func TestDetectWithObjectInfo(t *testing.T) {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
nb, lang, err := DetectWithFS(fakeFS, "doesntmatter")
|
nb, lang, err := DetectWithFS(fakefs, "file.py")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.True(t, nb)
|
assert.True(t, nb)
|
||||||
assert.Equal(t, workspace.LanguagePython, lang)
|
assert.Equal(t, workspace.LanguagePython, lang)
|
||||||
|
|
|
@ -1,77 +0,0 @@
|
||||||
package notebook
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io/fs"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/databricks/databricks-sdk-go/service/workspace"
|
|
||||||
)
|
|
||||||
|
|
||||||
type fakeFS struct {
|
|
||||||
fakeFile
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeFile struct {
|
|
||||||
fakeFileInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFile) Close() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFile) Read(p []byte) (n int, err error) {
|
|
||||||
return 0, fmt.Errorf("not implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFile) Stat() (fs.FileInfo, error) {
|
|
||||||
return f.fakeFileInfo, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeFileInfo struct {
|
|
||||||
oi workspace.ObjectInfo
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) WorkspaceObjectInfo() workspace.ObjectInfo {
|
|
||||||
return f.oi
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) Name() string {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) Size() int64 {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) Mode() fs.FileMode {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) ModTime() time.Time {
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) IsDir() bool {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFileInfo) Sys() any {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFS) Open(name string) (fs.File, error) {
|
|
||||||
return f.fakeFile, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFS) Stat(name string) (fs.FileInfo, error) {
|
|
||||||
panic("not implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFS) ReadDir(name string) ([]fs.DirEntry, error) {
|
|
||||||
panic("not implemented")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeFS) ReadFile(name string) ([]byte, error) {
|
|
||||||
panic("not implemented")
|
|
||||||
}
|
|
Loading…
Reference in New Issue