mirror of https://github.com/databricks/cli.git
Compare commits
8 Commits
853b9f7294
...
3d28be5298
Author | SHA1 | Date |
---|---|---|
Gleb Kanterov | 3d28be5298 | |
Pieter Noordhuis | 75b09ff230 | |
Pieter Noordhuis | 4fea0219fd | |
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.
|
||||
// This list can include namespace packages, which causes the import of nested packages.
|
||||
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
|
||||
|
|
|
@ -9,6 +9,7 @@ import (
|
|||
"github.com/databricks/cli/libs/dyn"
|
||||
)
|
||||
|
||||
// pythonDiagnostic is a single entry in diagnostics.json
|
||||
type pythonDiagnostic struct {
|
||||
Severity pythonSeverity `json:"severity"`
|
||||
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"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/databricks/cli/bundle/config/mutator/paths"
|
||||
|
||||
"github.com/databricks/databricks-sdk-go/logger"
|
||||
"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)
|
||||
}
|
||||
|
||||
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
|
||||
if diags.HasError() {
|
||||
return dyn.InvalidValue, mutateDiagsHasError
|
||||
|
@ -152,13 +160,21 @@ func createCacheDir(ctx context.Context) (string, error) {
|
|||
return os.MkdirTemp("", "-pydabs")
|
||||
}
|
||||
|
||||
func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir string, rootPath string, pythonPath string, root dyn.Value) (dyn.Value, diag.Diagnostics) {
|
||||
inputPath := filepath.Join(cacheDir, "input.json")
|
||||
outputPath := filepath.Join(cacheDir, "output.json")
|
||||
diagnosticsPath := filepath.Join(cacheDir, "diagnostics.json")
|
||||
type runPythonMutatorOpts struct {
|
||||
cacheDir string
|
||||
bundleRootPath string
|
||||
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{
|
||||
pythonPath,
|
||||
opts.pythonPath,
|
||||
"-m",
|
||||
"databricks.bundles.build",
|
||||
"--phase",
|
||||
|
@ -171,6 +187,10 @@ func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir string, r
|
|||
diagnosticsPath,
|
||||
}
|
||||
|
||||
if opts.loadLocations {
|
||||
args = append(args, "--locations", locationsPath)
|
||||
}
|
||||
|
||||
if err := writeInputFile(inputPath, root); err != nil {
|
||||
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(
|
||||
ctx,
|
||||
args,
|
||||
process.WithDir(rootPath),
|
||||
process.WithDir(opts.bundleRootPath),
|
||||
process.WithStderrWriter(stderrWriter),
|
||||
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)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
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
|
||||
// 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
|
||||
//
|
||||
// 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 {
|
||||
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 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) {
|
||||
|
|
|
@ -6,7 +6,6 @@ import (
|
|||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
|
@ -47,6 +46,7 @@ func TestPythonMutator_load(t *testing.T) {
|
|||
pydabs:
|
||||
enabled: true
|
||||
venv_path: .venv
|
||||
load_locations: true
|
||||
resources:
|
||||
jobs:
|
||||
job0:
|
||||
|
@ -65,7 +65,8 @@ func TestPythonMutator_load(t *testing.T) {
|
|||
"experimental": {
|
||||
"pydabs": {
|
||||
"enabled": true,
|
||||
"venv_path": ".venv"
|
||||
"venv_path": ".venv",
|
||||
"load_locations": true
|
||||
}
|
||||
},
|
||||
"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}}`,
|
||||
`{"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)
|
||||
|
@ -97,6 +100,25 @@ func TestPythonMutator_load(t *testing.T) {
|
|||
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, "job doesn't have any tasks", diags[0].Summary)
|
||||
assert.Equal(t, []dyn.Location{
|
||||
|
@ -106,7 +128,6 @@ func TestPythonMutator_load(t *testing.T) {
|
|||
Column: 5,
|
||||
},
|
||||
}, diags[0].Locations)
|
||||
|
||||
}
|
||||
|
||||
func TestPythonMutator_load_disallowed(t *testing.T) {
|
||||
|
@ -146,7 +167,7 @@ func TestPythonMutator_load_disallowed(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
}`, "")
|
||||
}`, "", "")
|
||||
|
||||
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
||||
diag := bundle.Apply(ctx, b, mutator)
|
||||
|
@ -191,7 +212,7 @@ func TestPythonMutator_init(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
}`, "")
|
||||
}`, "", "")
|
||||
|
||||
mutator := PythonMutator(PythonMutatorPhaseInit)
|
||||
diag := bundle.Apply(ctx, b, mutator)
|
||||
|
@ -252,7 +273,7 @@ func TestPythonMutator_badOutput(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
}`, "")
|
||||
}`, "", "")
|
||||
|
||||
mutator := PythonMutator(PythonMutatorPhaseLoad)
|
||||
diag := bundle.Apply(ctx, b, mutator)
|
||||
|
@ -588,7 +609,7 @@ or activate the environment before running CLI commands:
|
|||
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, 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")
|
||||
outputPath := filepath.Join(cacheDir, "output.json")
|
||||
locationsPath := filepath.Join(cacheDir, "locations.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 {
|
||||
_, err := os.Stat(inputPath)
|
||||
assert.NoError(t, err)
|
||||
|
||||
if reflect.DeepEqual(actual.Args, args) {
|
||||
err := os.WriteFile(outputPath, []byte(output), 0600)
|
||||
require.NoError(t, err)
|
||||
actualInputPath := getArg(actual.Args, "--input")
|
||||
actualOutputPath := getArg(actual.Args, "--output")
|
||||
actualDiagnosticsPath := getArg(actual.Args, "--diagnostics")
|
||||
actualLocationsPath := getArg(actual.Args, "--locations")
|
||||
|
||||
err = os.WriteFile(diagnosticsPath, []byte(diagnostics), 0600)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, inputPath, actualInputPath)
|
||||
require.Equal(t, outputPath, actualOutputPath)
|
||||
require.Equal(t, diagnosticsPath, actualDiagnosticsPath)
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf("unexpected command: %v", actual.Args)
|
||||
// locations is an optional argument
|
||||
if locations != "" {
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
v, diag := config.LoadFromBytes(name, []byte(content))
|
||||
|
||||
|
|
|
@ -3,6 +3,7 @@ package bundle
|
|||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
|
@ -109,6 +110,24 @@ func getUrlForNativeTemplate(name string) string {
|
|||
return ""
|
||||
}
|
||||
|
||||
func getFsForNativeTemplate(name string) (fs.FS, error) {
|
||||
builtin, err := template.Builtin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If this is a built-in template, the return value will be non-nil.
|
||||
var templateFS fs.FS
|
||||
for _, entry := range builtin {
|
||||
if entry.Name == name {
|
||||
templateFS = entry.FS
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return templateFS, nil
|
||||
}
|
||||
|
||||
func isRepoUrl(url string) bool {
|
||||
result := false
|
||||
for _, prefix := range gitUrlPrefixes {
|
||||
|
@ -198,9 +217,20 @@ See https://docs.databricks.com/en/dev-tools/bundles/templates.html for more inf
|
|||
if templateDir != "" {
|
||||
return errors.New("--template-dir can only be used with a Git repository URL")
|
||||
}
|
||||
|
||||
templateFS, err := getFsForNativeTemplate(templatePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// If this is not a built-in template, then it must be a local file system path.
|
||||
if templateFS == nil {
|
||||
templateFS = os.DirFS(templatePath)
|
||||
}
|
||||
|
||||
// skip downloading the repo because input arg is not a URL. We assume
|
||||
// it's a path on the local file system in that case
|
||||
return template.Materialize(ctx, configFile, templatePath, outputDir)
|
||||
return template.Materialize(ctx, configFile, templateFS, outputDir)
|
||||
}
|
||||
|
||||
// Create a temporary directory with the name of the repository. The '*'
|
||||
|
@ -224,7 +254,8 @@ See https://docs.databricks.com/en/dev-tools/bundles/templates.html for more inf
|
|||
|
||||
// Clean up downloaded repository once the template is materialized.
|
||||
defer os.RemoveAll(repoDir)
|
||||
return template.Materialize(ctx, configFile, filepath.Join(repoDir, templateDir), outputDir)
|
||||
templateFS := os.DirFS(filepath.Join(repoDir, templateDir))
|
||||
return template.Materialize(ctx, configFile, templateFS, outputDir)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
|
|
@ -42,7 +42,7 @@ func initTestTemplateWithBundleRoot(t *testing.T, ctx context.Context, templateN
|
|||
cmd := cmdio.NewIO(flags.OutputJSON, strings.NewReader(""), os.Stdout, os.Stderr, "", "bundles")
|
||||
ctx = cmdio.InContext(ctx, cmd)
|
||||
|
||||
err = template.Materialize(ctx, configFilePath, templateRoot, bundleRoot)
|
||||
err = template.Materialize(ctx, configFilePath, os.DirFS(templateRoot), bundleRoot)
|
||||
return bundleRoot, err
|
||||
}
|
||||
|
||||
|
|
|
@ -7,13 +7,24 @@ import (
|
|||
"io/fs"
|
||||
)
|
||||
|
||||
// WriteMode captures intent when writing a file.
|
||||
//
|
||||
// The first 9 bits are reserved for the [fs.FileMode] permission bits.
|
||||
// These are used only by the local filer implementation and have
|
||||
// no effect for the other implementations.
|
||||
type WriteMode int
|
||||
|
||||
// writeModePerm is a mask to extract permission bits from a WriteMode.
|
||||
const writeModePerm = WriteMode(fs.ModePerm)
|
||||
|
||||
const (
|
||||
OverwriteIfExists WriteMode = 1 << iota
|
||||
// Note: these constants are defined as powers of 2 to support combining them using a bit-wise OR.
|
||||
// They starts from the 10th bit (permission mask + 1) to avoid conflicts with the permission bits.
|
||||
OverwriteIfExists WriteMode = (writeModePerm + 1) << iota
|
||||
CreateParentDirectories
|
||||
)
|
||||
|
||||
// DeleteMode captures intent when deleting a file.
|
||||
type DeleteMode int
|
||||
|
||||
const (
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
package filer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestWriteMode(t *testing.T) {
|
||||
assert.Equal(t, 512, int(OverwriteIfExists))
|
||||
assert.Equal(t, 1024, int(CreateParentDirectories))
|
||||
}
|
|
@ -28,6 +28,15 @@ func (w *LocalClient) Write(ctx context.Context, name string, reader io.Reader,
|
|||
return err
|
||||
}
|
||||
|
||||
// Retrieve permission mask from the [WriteMode], if present.
|
||||
perm := fs.FileMode(0644)
|
||||
for _, m := range mode {
|
||||
bits := m & writeModePerm
|
||||
if bits != 0 {
|
||||
perm = fs.FileMode(bits)
|
||||
}
|
||||
}
|
||||
|
||||
flags := os.O_WRONLY | os.O_CREATE
|
||||
if slices.Contains(mode, OverwriteIfExists) {
|
||||
flags |= os.O_TRUNC
|
||||
|
@ -35,7 +44,7 @@ func (w *LocalClient) Write(ctx context.Context, name string, reader io.Reader,
|
|||
flags |= os.O_EXCL
|
||||
}
|
||||
|
||||
f, err := os.OpenFile(absPath, flags, 0644)
|
||||
f, err := os.OpenFile(absPath, flags, perm)
|
||||
if errors.Is(err, fs.ErrNotExist) && slices.Contains(mode, CreateParentDirectories) {
|
||||
// Create parent directories if they don't exist.
|
||||
err = os.MkdirAll(filepath.Dir(absPath), 0755)
|
||||
|
@ -43,7 +52,7 @@ func (w *LocalClient) Write(ctx context.Context, name string, reader io.Reader,
|
|||
return err
|
||||
}
|
||||
// Try again.
|
||||
f, err = os.OpenFile(absPath, flags, 0644)
|
||||
f, err = os.OpenFile(absPath, flags, perm)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
|
|
@ -3,7 +3,9 @@ package jsonschema
|
|||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
|
||||
|
@ -255,7 +257,12 @@ func (schema *Schema) validate() error {
|
|||
}
|
||||
|
||||
func Load(path string) (*Schema, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
dir, file := filepath.Split(path)
|
||||
return LoadFS(os.DirFS(dir), file)
|
||||
}
|
||||
|
||||
func LoadFS(fsys fs.FS, path string) (*Schema, error) {
|
||||
b, err := fs.ReadFile(fsys, path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package jsonschema
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
@ -305,3 +306,9 @@ func TestValidateSchemaSkippedPropertiesHaveDefaults(t *testing.T) {
|
|||
err = s.validate()
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestSchema_LoadFS(t *testing.T) {
|
||||
fsys := os.DirFS("./testdata/schema-load-int")
|
||||
_, err := LoadFS(fsys, "schema-valid.json")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
|
|
@ -0,0 +1,47 @@
|
|||
package template
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
//go:embed all:templates
|
||||
var builtinTemplates embed.FS
|
||||
|
||||
// BuiltinTemplate represents a template that is built into the CLI.
|
||||
type BuiltinTemplate struct {
|
||||
Name string
|
||||
FS fs.FS
|
||||
}
|
||||
|
||||
// Builtin returns the list of all built-in templates.
|
||||
func Builtin() ([]BuiltinTemplate, error) {
|
||||
templates, err := fs.Sub(builtinTemplates, "templates")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries, err := fs.ReadDir(templates, ".")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var out []BuiltinTemplate
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
templateFS, err := fs.Sub(templates, entry.Name())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out = append(out, BuiltinTemplate{
|
||||
Name: entry.Name(),
|
||||
FS: templateFS,
|
||||
})
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package template
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuiltin(t *testing.T) {
|
||||
out, err := Builtin()
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, out, 3)
|
||||
|
||||
// Confirm names.
|
||||
assert.Equal(t, "dbt-sql", out[0].Name)
|
||||
assert.Equal(t, "default-python", out[1].Name)
|
||||
assert.Equal(t, "default-sql", out[2].Name)
|
||||
|
||||
// Confirm that the filesystems work.
|
||||
_, err = fs.Stat(out[0].FS, `template/{{.project_name}}/dbt_project.yml.tmpl`)
|
||||
assert.NoError(t, err)
|
||||
_, err = fs.Stat(out[1].FS, `template/{{.project_name}}/tests/main_test.py.tmpl`)
|
||||
assert.NoError(t, err)
|
||||
_, err = fs.Stat(out[2].FS, `template/{{.project_name}}/src/orders_daily.sql.tmpl`)
|
||||
assert.NoError(t, err)
|
||||
}
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
|
||||
"github.com/databricks/cli/libs/cmdio"
|
||||
"github.com/databricks/cli/libs/jsonschema"
|
||||
|
@ -28,9 +29,8 @@ type config struct {
|
|||
schema *jsonschema.Schema
|
||||
}
|
||||
|
||||
func newConfig(ctx context.Context, schemaPath string) (*config, error) {
|
||||
// Read config schema
|
||||
schema, err := jsonschema.Load(schemaPath)
|
||||
func newConfig(ctx context.Context, templateFS fs.FS, schemaPath string) (*config, error) {
|
||||
schema, err := jsonschema.LoadFS(templateFS, schemaPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
@ -3,6 +3,8 @@ package template
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"text/template"
|
||||
|
@ -16,7 +18,7 @@ func TestTemplateConfigAssignValuesFromFile(t *testing.T) {
|
|||
testDir := "./testdata/config-assign-from-file"
|
||||
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, filepath.Join(testDir, "schema.json"))
|
||||
c, err := newConfig(ctx, os.DirFS(testDir), "schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = c.assignValuesFromFile(filepath.Join(testDir, "config.json"))
|
||||
|
@ -32,7 +34,7 @@ func TestTemplateConfigAssignValuesFromFileDoesNotOverwriteExistingConfigs(t *te
|
|||
testDir := "./testdata/config-assign-from-file"
|
||||
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, filepath.Join(testDir, "schema.json"))
|
||||
c, err := newConfig(ctx, os.DirFS(testDir), "schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
c.values = map[string]any{
|
||||
|
@ -52,7 +54,7 @@ func TestTemplateConfigAssignValuesFromFileForInvalidIntegerValue(t *testing.T)
|
|||
testDir := "./testdata/config-assign-from-file-invalid-int"
|
||||
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, filepath.Join(testDir, "schema.json"))
|
||||
c, err := newConfig(ctx, os.DirFS(testDir), "schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = c.assignValuesFromFile(filepath.Join(testDir, "config.json"))
|
||||
|
@ -63,7 +65,7 @@ func TestTemplateConfigAssignValuesFromFileFiltersPropertiesNotInTheSchema(t *te
|
|||
testDir := "./testdata/config-assign-from-file-unknown-property"
|
||||
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, filepath.Join(testDir, "schema.json"))
|
||||
c, err := newConfig(ctx, os.DirFS(testDir), "schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = c.assignValuesFromFile(filepath.Join(testDir, "config.json"))
|
||||
|
@ -78,10 +80,10 @@ func TestTemplateConfigAssignValuesFromDefaultValues(t *testing.T) {
|
|||
testDir := "./testdata/config-assign-from-default-value"
|
||||
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, filepath.Join(testDir, "schema.json"))
|
||||
c, err := newConfig(ctx, os.DirFS(testDir), "schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
r, err := newRenderer(ctx, nil, nil, "./testdata/empty/template", "./testdata/empty/library", t.TempDir())
|
||||
r, err := newRenderer(ctx, nil, nil, os.DirFS("."), "./testdata/empty/template", "./testdata/empty/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = c.assignDefaultValues(r)
|
||||
|
@ -97,10 +99,10 @@ func TestTemplateConfigAssignValuesFromTemplatedDefaultValues(t *testing.T) {
|
|||
testDir := "./testdata/config-assign-from-templated-default-value"
|
||||
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, filepath.Join(testDir, "schema.json"))
|
||||
c, err := newConfig(ctx, os.DirFS(testDir), "schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
r, err := newRenderer(ctx, nil, nil, filepath.Join(testDir, "template/template"), filepath.Join(testDir, "template/library"), t.TempDir())
|
||||
r, err := newRenderer(ctx, nil, nil, os.DirFS("."), path.Join(testDir, "template/template"), path.Join(testDir, "template/library"))
|
||||
require.NoError(t, err)
|
||||
|
||||
// Note: only the string value is templated.
|
||||
|
@ -116,7 +118,7 @@ func TestTemplateConfigAssignValuesFromTemplatedDefaultValues(t *testing.T) {
|
|||
|
||||
func TestTemplateConfigValidateValuesDefined(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, "testdata/config-test-schema/test-schema.json")
|
||||
c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
c.values = map[string]any{
|
||||
|
@ -131,7 +133,7 @@ func TestTemplateConfigValidateValuesDefined(t *testing.T) {
|
|||
|
||||
func TestTemplateConfigValidateTypeForValidConfig(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, "testdata/config-test-schema/test-schema.json")
|
||||
c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
c.values = map[string]any{
|
||||
|
@ -147,7 +149,7 @@ func TestTemplateConfigValidateTypeForValidConfig(t *testing.T) {
|
|||
|
||||
func TestTemplateConfigValidateTypeForUnknownField(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, "testdata/config-test-schema/test-schema.json")
|
||||
c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
c.values = map[string]any{
|
||||
|
@ -164,7 +166,7 @@ func TestTemplateConfigValidateTypeForUnknownField(t *testing.T) {
|
|||
|
||||
func TestTemplateConfigValidateTypeForInvalidType(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := newConfig(ctx, "testdata/config-test-schema/test-schema.json")
|
||||
c, err := newConfig(ctx, os.DirFS("testdata/config-test-schema"), "test-schema.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
c.values = map[string]any{
|
||||
|
@ -271,7 +273,8 @@ func TestTemplateEnumValidation(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestTemplateSchemaErrorsWithEmptyDescription(t *testing.T) {
|
||||
_, err := newConfig(context.Background(), "./testdata/config-test-schema/invalid-test-schema.json")
|
||||
ctx := context.Background()
|
||||
_, err := newConfig(ctx, os.DirFS("./testdata/config-test-schema"), "invalid-test-schema.json")
|
||||
assert.EqualError(t, err, "template property property-without-description is missing a description")
|
||||
}
|
||||
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
package template
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
|
||||
"github.com/databricks/cli/libs/filer"
|
||||
)
|
||||
|
@ -13,89 +12,69 @@ import (
|
|||
// Interface representing a file to be materialized from a template into a project
|
||||
// instance
|
||||
type file interface {
|
||||
// Destination path for file. This is where the file will be created when
|
||||
// PersistToDisk is called.
|
||||
DstPath() *destinationPath
|
||||
// Path of the file relative to the root of the instantiated template.
|
||||
// This is where the file is written to when persisting the template to disk.
|
||||
// Must be slash-separated.
|
||||
RelPath() string
|
||||
|
||||
// Write file to disk at the destination path.
|
||||
PersistToDisk() error
|
||||
}
|
||||
Write(ctx context.Context, out filer.Filer) error
|
||||
|
||||
type destinationPath struct {
|
||||
// Root path for the project instance. This path uses the system's default
|
||||
// file separator. For example /foo/bar on Unix and C:\foo\bar on windows
|
||||
root string
|
||||
|
||||
// Unix like file path relative to the "root" of the instantiated project. Is used to
|
||||
// evaluate whether the file should be skipped by comparing it to a list of
|
||||
// skip glob patterns.
|
||||
relPath string
|
||||
}
|
||||
|
||||
// Absolute path of the file, in the os native format. For example /foo/bar on
|
||||
// Unix and C:\foo\bar on windows
|
||||
func (f *destinationPath) absPath() string {
|
||||
return filepath.Join(f.root, filepath.FromSlash(f.relPath))
|
||||
// contents returns the file contents as a byte slice.
|
||||
// This is used for testing purposes.
|
||||
contents() ([]byte, error)
|
||||
}
|
||||
|
||||
type copyFile struct {
|
||||
ctx context.Context
|
||||
|
||||
// Permissions bits for the destination file
|
||||
perm fs.FileMode
|
||||
|
||||
dstPath *destinationPath
|
||||
// Destination path for the file.
|
||||
relPath string
|
||||
|
||||
// Filer rooted at template root. Used to read srcPath.
|
||||
srcFiler filer.Filer
|
||||
// [fs.FS] rooted at template root. Used to read srcPath.
|
||||
srcFS fs.FS
|
||||
|
||||
// Relative path from template root for file to be copied.
|
||||
srcPath string
|
||||
}
|
||||
|
||||
func (f *copyFile) DstPath() *destinationPath {
|
||||
return f.dstPath
|
||||
func (f *copyFile) RelPath() string {
|
||||
return f.relPath
|
||||
}
|
||||
|
||||
func (f *copyFile) PersistToDisk() error {
|
||||
path := f.DstPath().absPath()
|
||||
err := os.MkdirAll(filepath.Dir(path), 0755)
|
||||
func (f *copyFile) Write(ctx context.Context, out filer.Filer) error {
|
||||
src, err := f.srcFS.Open(f.srcPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srcFile, err := f.srcFiler.Read(f.ctx, f.srcPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer srcFile.Close()
|
||||
dstFile, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, f.perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dstFile.Close()
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
return err
|
||||
defer src.Close()
|
||||
return out.Write(ctx, f.relPath, src, filer.CreateParentDirectories, filer.WriteMode(f.perm))
|
||||
}
|
||||
|
||||
func (f *copyFile) contents() ([]byte, error) {
|
||||
return fs.ReadFile(f.srcFS, f.srcPath)
|
||||
}
|
||||
|
||||
type inMemoryFile struct {
|
||||
dstPath *destinationPath
|
||||
|
||||
content []byte
|
||||
|
||||
// Permissions bits for the destination file
|
||||
perm fs.FileMode
|
||||
|
||||
// Destination path for the file.
|
||||
relPath string
|
||||
|
||||
// Contents of the file.
|
||||
content []byte
|
||||
}
|
||||
|
||||
func (f *inMemoryFile) DstPath() *destinationPath {
|
||||
return f.dstPath
|
||||
func (f *inMemoryFile) RelPath() string {
|
||||
return f.relPath
|
||||
}
|
||||
|
||||
func (f *inMemoryFile) PersistToDisk() error {
|
||||
path := f.DstPath().absPath()
|
||||
|
||||
err := os.MkdirAll(filepath.Dir(path), 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, f.content, f.perm)
|
||||
func (f *inMemoryFile) Write(ctx context.Context, out filer.Filer) error {
|
||||
return out.Write(ctx, f.relPath, bytes.NewReader(f.content), filer.CreateParentDirectories, filer.WriteMode(f.perm))
|
||||
}
|
||||
|
||||
func (f *inMemoryFile) contents() ([]byte, error) {
|
||||
return slices.Clone(f.content), nil
|
||||
}
|
||||
|
|
|
@ -13,76 +13,51 @@ import (
|
|||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func testInMemoryFile(t *testing.T, perm fs.FileMode) {
|
||||
func testInMemoryFile(t *testing.T, ctx context.Context, perm fs.FileMode) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
f := &inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "a/b/c",
|
||||
},
|
||||
perm: perm,
|
||||
relPath: "a/b/c",
|
||||
content: []byte("123"),
|
||||
}
|
||||
err := f.PersistToDisk()
|
||||
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = f.Write(ctx, out)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assertFileContent(t, filepath.Join(tmpDir, "a/b/c"), "123")
|
||||
assertFilePermissions(t, filepath.Join(tmpDir, "a/b/c"), perm)
|
||||
}
|
||||
|
||||
func testCopyFile(t *testing.T, perm fs.FileMode) {
|
||||
func testCopyFile(t *testing.T, ctx context.Context, perm fs.FileMode) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
templateFiler, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = os.WriteFile(filepath.Join(tmpDir, "source"), []byte("qwerty"), perm)
|
||||
err := os.WriteFile(filepath.Join(tmpDir, "source"), []byte("qwerty"), perm)
|
||||
require.NoError(t, err)
|
||||
|
||||
f := ©File{
|
||||
ctx: context.Background(),
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "a/b/c",
|
||||
},
|
||||
perm: perm,
|
||||
srcPath: "source",
|
||||
srcFiler: templateFiler,
|
||||
perm: perm,
|
||||
relPath: "a/b/c",
|
||||
srcFS: os.DirFS(tmpDir),
|
||||
srcPath: "source",
|
||||
}
|
||||
err = f.PersistToDisk()
|
||||
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = f.Write(ctx, out)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assertFileContent(t, filepath.Join(tmpDir, "a/b/c"), "qwerty")
|
||||
assertFilePermissions(t, filepath.Join(tmpDir, "a/b/c"), perm)
|
||||
}
|
||||
|
||||
func TestTemplateFileDestinationPath(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.SkipNow()
|
||||
}
|
||||
f := &destinationPath{
|
||||
root: `a/b/c`,
|
||||
relPath: "d/e",
|
||||
}
|
||||
assert.Equal(t, `a/b/c/d/e`, f.absPath())
|
||||
}
|
||||
|
||||
func TestTemplateFileDestinationPathForWindows(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.SkipNow()
|
||||
}
|
||||
f := &destinationPath{
|
||||
root: `c:\a\b\c`,
|
||||
relPath: "d/e",
|
||||
}
|
||||
assert.Equal(t, `c:\a\b\c\d\e`, f.absPath())
|
||||
}
|
||||
|
||||
func TestTemplateInMemoryFilePersistToDisk(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.SkipNow()
|
||||
}
|
||||
testInMemoryFile(t, 0755)
|
||||
ctx := context.Background()
|
||||
testInMemoryFile(t, ctx, 0755)
|
||||
}
|
||||
|
||||
func TestTemplateInMemoryFilePersistToDiskForWindows(t *testing.T) {
|
||||
|
@ -91,14 +66,16 @@ func TestTemplateInMemoryFilePersistToDiskForWindows(t *testing.T) {
|
|||
}
|
||||
// we have separate tests for windows because of differences in valid
|
||||
// fs.FileMode values we can use for different operating systems.
|
||||
testInMemoryFile(t, 0666)
|
||||
ctx := context.Background()
|
||||
testInMemoryFile(t, ctx, 0666)
|
||||
}
|
||||
|
||||
func TestTemplateCopyFilePersistToDisk(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.SkipNow()
|
||||
}
|
||||
testCopyFile(t, 0644)
|
||||
ctx := context.Background()
|
||||
testCopyFile(t, ctx, 0644)
|
||||
}
|
||||
|
||||
func TestTemplateCopyFilePersistToDiskForWindows(t *testing.T) {
|
||||
|
@ -107,5 +84,6 @@ func TestTemplateCopyFilePersistToDiskForWindows(t *testing.T) {
|
|||
}
|
||||
// we have separate tests for windows because of differences in valid
|
||||
// fs.FileMode values we can use for different operating systems.
|
||||
testCopyFile(t, 0666)
|
||||
ctx := context.Background()
|
||||
testCopyFile(t, ctx, 0666)
|
||||
}
|
||||
|
|
|
@ -18,11 +18,10 @@ import (
|
|||
|
||||
func TestTemplatePrintStringWithoutProcessing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/print-without-processing/template", "./testdata/print-without-processing/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/print-without-processing/template", "./testdata/print-without-processing/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -35,11 +34,10 @@ func TestTemplatePrintStringWithoutProcessing(t *testing.T) {
|
|||
|
||||
func TestTemplateRegexpCompileFunction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/regexp-compile/template", "./testdata/regexp-compile/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/regexp-compile/template", "./testdata/regexp-compile/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -53,11 +51,10 @@ func TestTemplateRegexpCompileFunction(t *testing.T) {
|
|||
|
||||
func TestTemplateRandIntFunction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/random-int/template", "./testdata/random-int/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/random-int/template", "./testdata/random-int/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -71,11 +68,10 @@ func TestTemplateRandIntFunction(t *testing.T) {
|
|||
|
||||
func TestTemplateUuidFunction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/uuid/template", "./testdata/uuid/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/uuid/template", "./testdata/uuid/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -88,11 +84,10 @@ func TestTemplateUuidFunction(t *testing.T) {
|
|||
|
||||
func TestTemplateUrlFunction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/urlparse-function/template", "./testdata/urlparse-function/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/urlparse-function/template", "./testdata/urlparse-function/library")
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
|
@ -105,11 +100,10 @@ func TestTemplateUrlFunction(t *testing.T) {
|
|||
|
||||
func TestTemplateMapPairFunction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/map-pair/template", "./testdata/map-pair/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/map-pair/template", "./testdata/map-pair/library")
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
|
@ -122,7 +116,6 @@ func TestTemplateMapPairFunction(t *testing.T) {
|
|||
|
||||
func TestWorkspaceHost(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
w := &databricks.WorkspaceClient{
|
||||
Config: &workspaceConfig.Config{
|
||||
|
@ -132,7 +125,7 @@ func TestWorkspaceHost(t *testing.T) {
|
|||
ctx = root.SetWorkspaceClient(ctx, w)
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/workspace-host/template", "./testdata/map-pair/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/workspace-host/template", "./testdata/map-pair/library")
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
|
@ -149,7 +142,6 @@ func TestWorkspaceHostNotConfigured(t *testing.T) {
|
|||
ctx := context.Background()
|
||||
cmd := cmdio.NewIO(flags.OutputJSON, strings.NewReader(""), os.Stdout, os.Stderr, "", "template")
|
||||
ctx = cmdio.InContext(ctx, cmd)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
w := &databricks.WorkspaceClient{
|
||||
Config: &workspaceConfig.Config{},
|
||||
|
@ -157,7 +149,7 @@ func TestWorkspaceHostNotConfigured(t *testing.T) {
|
|||
ctx = root.SetWorkspaceClient(ctx, w)
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/workspace-host/template", "./testdata/map-pair/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/workspace-host/template", "./testdata/map-pair/library")
|
||||
|
||||
assert.NoError(t, err)
|
||||
|
||||
|
|
|
@ -2,54 +2,32 @@ package template
|
|||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/databricks/cli/libs/cmdio"
|
||||
"github.com/databricks/cli/libs/filer"
|
||||
)
|
||||
|
||||
const libraryDirName = "library"
|
||||
const templateDirName = "template"
|
||||
const schemaFileName = "databricks_template_schema.json"
|
||||
|
||||
//go:embed all:templates
|
||||
var builtinTemplates embed.FS
|
||||
|
||||
// This function materializes the input templates as a project, using user defined
|
||||
// configurations.
|
||||
// Parameters:
|
||||
//
|
||||
// ctx: context containing a cmdio object. This is used to prompt the user
|
||||
// configFilePath: file path containing user defined config values
|
||||
// templateRoot: root of the template definition
|
||||
// templateFS: root of the template definition
|
||||
// outputDir: root of directory where to initialize the template
|
||||
func Materialize(ctx context.Context, configFilePath, templateRoot, outputDir string) error {
|
||||
// Use a temporary directory in case any builtin templates like default-python are used
|
||||
tempDir, err := os.MkdirTemp("", "templates")
|
||||
defer os.RemoveAll(tempDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
templateRoot, err = prepareBuiltinTemplates(templateRoot, tempDir)
|
||||
if err != nil {
|
||||
return err
|
||||
func Materialize(ctx context.Context, configFilePath string, templateFS fs.FS, outputDir string) error {
|
||||
if _, err := fs.Stat(templateFS, schemaFileName); errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("not a bundle template: expected to find a template schema file at %s", schemaFileName)
|
||||
}
|
||||
|
||||
templatePath := filepath.Join(templateRoot, templateDirName)
|
||||
libraryPath := filepath.Join(templateRoot, libraryDirName)
|
||||
schemaPath := filepath.Join(templateRoot, schemaFileName)
|
||||
helpers := loadHelpers(ctx)
|
||||
|
||||
if _, err := os.Stat(schemaPath); errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("not a bundle template: expected to find a template schema file at %s", schemaPath)
|
||||
}
|
||||
|
||||
config, err := newConfig(ctx, schemaPath)
|
||||
config, err := newConfig(ctx, templateFS, schemaFileName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -62,7 +40,8 @@ func Materialize(ctx context.Context, configFilePath, templateRoot, outputDir st
|
|||
}
|
||||
}
|
||||
|
||||
r, err := newRenderer(ctx, config.values, helpers, templatePath, libraryPath, outputDir)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, config.values, helpers, templateFS, templateDirName, libraryDirName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -94,7 +73,12 @@ func Materialize(ctx context.Context, configFilePath, templateRoot, outputDir st
|
|||
return err
|
||||
}
|
||||
|
||||
err = r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(outputDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = r.persistToDisk(ctx, out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -111,44 +95,3 @@ func Materialize(ctx context.Context, configFilePath, templateRoot, outputDir st
|
|||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// If the given templateRoot matches
|
||||
func prepareBuiltinTemplates(templateRoot string, tempDir string) (string, error) {
|
||||
// Check that `templateRoot` is a clean basename, i.e. `some_path` and not `./some_path` or "."
|
||||
// Return early if that's not the case.
|
||||
if templateRoot == "." || path.Base(templateRoot) != templateRoot {
|
||||
return templateRoot, nil
|
||||
}
|
||||
|
||||
_, err := fs.Stat(builtinTemplates, path.Join("templates", templateRoot))
|
||||
if err != nil {
|
||||
// The given path doesn't appear to be using out built-in templates
|
||||
return templateRoot, nil
|
||||
}
|
||||
|
||||
// We have a built-in template with the same name as templateRoot!
|
||||
// Now we need to make a fully copy of the builtin templates to a real file system
|
||||
// since template.Parse() doesn't support embed.FS.
|
||||
err = fs.WalkDir(builtinTemplates, "templates", func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
targetPath := filepath.Join(tempDir, path)
|
||||
if entry.IsDir() {
|
||||
return os.Mkdir(targetPath, 0755)
|
||||
} else {
|
||||
content, err := fs.ReadFile(builtinTemplates, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(targetPath, content, 0644)
|
||||
}
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filepath.Join(tempDir, "templates", templateRoot), nil
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ package template
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/databricks/cli/cmd/root"
|
||||
|
@ -19,6 +19,6 @@ func TestMaterializeForNonTemplateDirectory(t *testing.T) {
|
|||
ctx := root.SetWorkspaceClient(context.Background(), w)
|
||||
|
||||
// Try to materialize a non-template directory.
|
||||
err = Materialize(ctx, "", tmpDir, "")
|
||||
assert.EqualError(t, err, fmt.Sprintf("not a bundle template: expected to find a template schema file at %s", filepath.Join(tmpDir, schemaFileName)))
|
||||
err = Materialize(ctx, "", os.DirFS(tmpDir), "")
|
||||
assert.EqualError(t, err, fmt.Sprintf("not a bundle template: expected to find a template schema file at %s", schemaFileName))
|
||||
}
|
||||
|
|
|
@ -6,9 +6,7 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
|
@ -52,32 +50,38 @@ type renderer struct {
|
|||
// do not match any glob patterns from this list
|
||||
skipPatterns []string
|
||||
|
||||
// Filer rooted at template root. The file tree from this root is walked to
|
||||
// generate the project
|
||||
templateFiler filer.Filer
|
||||
|
||||
// Root directory for the project instantiated from the template
|
||||
instanceRoot string
|
||||
// [fs.FS] that holds the template's file tree.
|
||||
srcFS fs.FS
|
||||
}
|
||||
|
||||
func newRenderer(ctx context.Context, config map[string]any, helpers template.FuncMap, templateRoot, libraryRoot, instanceRoot string) (*renderer, error) {
|
||||
func newRenderer(
|
||||
ctx context.Context,
|
||||
config map[string]any,
|
||||
helpers template.FuncMap,
|
||||
templateFS fs.FS,
|
||||
templateDir string,
|
||||
libraryDir string,
|
||||
) (*renderer, error) {
|
||||
// Initialize new template, with helper functions loaded
|
||||
tmpl := template.New("").Funcs(helpers)
|
||||
|
||||
// Load user defined associated templates from the library root
|
||||
libraryGlob := filepath.Join(libraryRoot, "*")
|
||||
matches, err := filepath.Glob(libraryGlob)
|
||||
// Find user-defined templates in the library directory
|
||||
matches, err := fs.Glob(templateFS, path.Join(libraryDir, "*"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Parse user-defined templates.
|
||||
// Note: we do not call [ParseFS] with the glob directly because
|
||||
// it returns an error if no files match the pattern.
|
||||
if len(matches) != 0 {
|
||||
tmpl, err = tmpl.ParseFiles(matches...)
|
||||
tmpl, err = tmpl.ParseFS(templateFS, matches...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
templateFiler, err := filer.NewLocalClient(templateRoot)
|
||||
srcFS, err := fs.Sub(templateFS, path.Clean(templateDir))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -85,13 +89,12 @@ func newRenderer(ctx context.Context, config map[string]any, helpers template.Fu
|
|||
ctx = log.NewContext(ctx, log.GetLogger(ctx).With("action", "initialize-template"))
|
||||
|
||||
return &renderer{
|
||||
ctx: ctx,
|
||||
config: config,
|
||||
baseTemplate: tmpl,
|
||||
files: make([]file, 0),
|
||||
skipPatterns: make([]string, 0),
|
||||
templateFiler: templateFiler,
|
||||
instanceRoot: instanceRoot,
|
||||
ctx: ctx,
|
||||
config: config,
|
||||
baseTemplate: tmpl,
|
||||
files: make([]file, 0),
|
||||
skipPatterns: make([]string, 0),
|
||||
srcFS: srcFS,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
@ -141,7 +144,7 @@ func (r *renderer) executeTemplate(templateDefinition string) (string, error) {
|
|||
|
||||
func (r *renderer) computeFile(relPathTemplate string) (file, error) {
|
||||
// read file permissions
|
||||
info, err := r.templateFiler.Stat(r.ctx, relPathTemplate)
|
||||
info, err := fs.Stat(r.srcFS, relPathTemplate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -157,14 +160,10 @@ func (r *renderer) computeFile(relPathTemplate string) (file, error) {
|
|||
// over as is, without treating it as a template
|
||||
if !strings.HasSuffix(relPathTemplate, templateExtension) {
|
||||
return ©File{
|
||||
dstPath: &destinationPath{
|
||||
root: r.instanceRoot,
|
||||
relPath: relPath,
|
||||
},
|
||||
perm: perm,
|
||||
ctx: r.ctx,
|
||||
srcPath: relPathTemplate,
|
||||
srcFiler: r.templateFiler,
|
||||
perm: perm,
|
||||
relPath: relPath,
|
||||
srcFS: r.srcFS,
|
||||
srcPath: relPathTemplate,
|
||||
}, nil
|
||||
} else {
|
||||
// Trim the .tmpl suffix from file name, if specified in the template
|
||||
|
@ -173,7 +172,7 @@ func (r *renderer) computeFile(relPathTemplate string) (file, error) {
|
|||
}
|
||||
|
||||
// read template file's content
|
||||
templateReader, err := r.templateFiler.Read(r.ctx, relPathTemplate)
|
||||
templateReader, err := r.srcFS.Open(relPathTemplate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -194,11 +193,8 @@ func (r *renderer) computeFile(relPathTemplate string) (file, error) {
|
|||
}
|
||||
|
||||
return &inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: r.instanceRoot,
|
||||
relPath: relPath,
|
||||
},
|
||||
perm: perm,
|
||||
relPath: relPath,
|
||||
content: []byte(content),
|
||||
}, nil
|
||||
}
|
||||
|
@ -263,7 +259,7 @@ func (r *renderer) walk() error {
|
|||
//
|
||||
// 2. For directories: They are appended to a slice, which acts as a queue
|
||||
// allowing BFS traversal of the template file tree
|
||||
entries, err := r.templateFiler.ReadDir(r.ctx, currentDirectory)
|
||||
entries, err := fs.ReadDir(r.srcFS, currentDirectory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -283,7 +279,7 @@ func (r *renderer) walk() error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Infof(r.ctx, "added file to list of possible project files: %s", f.DstPath().relPath)
|
||||
logger.Infof(r.ctx, "added file to list of possible project files: %s", f.RelPath())
|
||||
r.files = append(r.files, f)
|
||||
}
|
||||
|
||||
|
@ -291,17 +287,17 @@ func (r *renderer) walk() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (r *renderer) persistToDisk() error {
|
||||
func (r *renderer) persistToDisk(ctx context.Context, out filer.Filer) error {
|
||||
// Accumulate files which we will persist, skipping files whose path matches
|
||||
// any of the skip patterns
|
||||
filesToPersist := make([]file, 0)
|
||||
for _, file := range r.files {
|
||||
match, err := isSkipped(file.DstPath().relPath, r.skipPatterns)
|
||||
match, err := isSkipped(file.RelPath(), r.skipPatterns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if match {
|
||||
log.Infof(r.ctx, "skipping file: %s", file.DstPath())
|
||||
log.Infof(r.ctx, "skipping file: %s", file.RelPath())
|
||||
continue
|
||||
}
|
||||
filesToPersist = append(filesToPersist, file)
|
||||
|
@ -309,8 +305,8 @@ func (r *renderer) persistToDisk() error {
|
|||
|
||||
// Assert no conflicting files exist
|
||||
for _, file := range filesToPersist {
|
||||
path := file.DstPath().absPath()
|
||||
_, err := os.Stat(path)
|
||||
path := file.RelPath()
|
||||
_, err := out.Stat(ctx, path)
|
||||
if err == nil {
|
||||
return fmt.Errorf("failed to initialize template, one or more files already exist: %s", path)
|
||||
}
|
||||
|
@ -321,7 +317,7 @@ func (r *renderer) persistToDisk() error {
|
|||
|
||||
// Persist files to disk
|
||||
for _, file := range filesToPersist {
|
||||
err := file.PersistToDisk()
|
||||
err := file.Write(ctx, out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
@ -3,9 +3,9 @@ package template
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
@ -18,6 +18,7 @@ import (
|
|||
"github.com/databricks/cli/cmd/root"
|
||||
"github.com/databricks/cli/internal/testutil"
|
||||
"github.com/databricks/cli/libs/diag"
|
||||
"github.com/databricks/cli/libs/filer"
|
||||
"github.com/databricks/cli/libs/tags"
|
||||
"github.com/databricks/databricks-sdk-go"
|
||||
workspaceConfig "github.com/databricks/databricks-sdk-go/config"
|
||||
|
@ -41,9 +42,8 @@ func assertFilePermissions(t *testing.T, path string, perm fs.FileMode) {
|
|||
func assertBuiltinTemplateValid(t *testing.T, template string, settings map[string]any, target string, isServicePrincipal bool, build bool, tempDir string) {
|
||||
ctx := context.Background()
|
||||
|
||||
templatePath, err := prepareBuiltinTemplates(template, tempDir)
|
||||
templateFS, err := fs.Sub(builtinTemplates, path.Join("templates", template))
|
||||
require.NoError(t, err)
|
||||
libraryPath := filepath.Join(templatePath, "library")
|
||||
|
||||
w := &databricks.WorkspaceClient{
|
||||
Config: &workspaceConfig.Config{Host: "https://myhost.com"},
|
||||
|
@ -58,16 +58,18 @@ func assertBuiltinTemplateValid(t *testing.T, template string, settings map[stri
|
|||
ctx = root.SetWorkspaceClient(ctx, w)
|
||||
helpers := loadHelpers(ctx)
|
||||
|
||||
renderer, err := newRenderer(ctx, settings, helpers, templatePath, libraryPath, tempDir)
|
||||
renderer, err := newRenderer(ctx, settings, helpers, templateFS, templateDirName, libraryDirName)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Evaluate template
|
||||
err = renderer.walk()
|
||||
require.NoError(t, err)
|
||||
err = renderer.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tempDir)
|
||||
require.NoError(t, err)
|
||||
err = renderer.persistToDisk(ctx, out)
|
||||
require.NoError(t, err)
|
||||
|
||||
b, err := bundle.Load(ctx, filepath.Join(tempDir, "template", "my_project"))
|
||||
b, err := bundle.Load(ctx, filepath.Join(tempDir, "my_project"))
|
||||
require.NoError(t, err)
|
||||
diags := bundle.Apply(ctx, b, phases.LoadNamedTarget(target))
|
||||
require.NoError(t, diags.Error())
|
||||
|
@ -96,18 +98,6 @@ func assertBuiltinTemplateValid(t *testing.T, template string, settings map[stri
|
|||
}
|
||||
}
|
||||
|
||||
func TestPrepareBuiltInTemplatesWithRelativePaths(t *testing.T) {
|
||||
// CWD should not be resolved as a built in template
|
||||
dir, err := prepareBuiltinTemplates(".", t.TempDir())
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, ".", dir)
|
||||
|
||||
// relative path should not be resolved as a built in template
|
||||
dir, err = prepareBuiltinTemplates("./default-python", t.TempDir())
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "./default-python", dir)
|
||||
}
|
||||
|
||||
func TestBuiltinPythonTemplateValid(t *testing.T) {
|
||||
// Test option combinations
|
||||
options := []string{"yes", "no"}
|
||||
|
@ -194,13 +184,14 @@ func TestRendererWithAssociatedTemplateInLibrary(t *testing.T) {
|
|||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/email/template", "./testdata/email/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/email/template", "./testdata/email/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
require.NoError(t, err)
|
||||
|
||||
b, err := os.ReadFile(filepath.Join(tmpDir, "my_email"))
|
||||
|
@ -325,45 +316,34 @@ func TestRendererPersistToDisk(t *testing.T) {
|
|||
|
||||
r := &renderer{
|
||||
ctx: ctx,
|
||||
instanceRoot: tmpDir,
|
||||
skipPatterns: []string{"a/b/c", "mn*"},
|
||||
files: []file{
|
||||
&inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "a/b/c",
|
||||
},
|
||||
perm: 0444,
|
||||
relPath: "a/b/c",
|
||||
content: nil,
|
||||
},
|
||||
&inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "mno",
|
||||
},
|
||||
perm: 0444,
|
||||
relPath: "mno",
|
||||
content: nil,
|
||||
},
|
||||
&inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "a/b/d",
|
||||
},
|
||||
perm: 0444,
|
||||
relPath: "a/b/d",
|
||||
content: []byte("123"),
|
||||
},
|
||||
&inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "mmnn",
|
||||
},
|
||||
perm: 0444,
|
||||
relPath: "mmnn",
|
||||
content: []byte("456"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.NoFileExists(t, filepath.Join(tmpDir, "a", "b", "c"))
|
||||
|
@ -378,10 +358,9 @@ func TestRendererPersistToDisk(t *testing.T) {
|
|||
func TestRendererWalk(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/walk/template", "./testdata/walk/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/walk/template", "./testdata/walk/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -389,21 +368,12 @@ func TestRendererWalk(t *testing.T) {
|
|||
|
||||
getContent := func(r *renderer, path string) string {
|
||||
for _, f := range r.files {
|
||||
if f.DstPath().relPath != path {
|
||||
if f.RelPath() != path {
|
||||
continue
|
||||
}
|
||||
switch v := f.(type) {
|
||||
case *inMemoryFile:
|
||||
return strings.Trim(string(v.content), "\r\n")
|
||||
case *copyFile:
|
||||
r, err := r.templateFiler.Read(context.Background(), v.srcPath)
|
||||
require.NoError(t, err)
|
||||
b, err := io.ReadAll(r)
|
||||
require.NoError(t, err)
|
||||
return strings.Trim(string(b), "\r\n")
|
||||
default:
|
||||
require.FailNow(t, "execution should not reach here")
|
||||
}
|
||||
b, err := f.contents()
|
||||
require.NoError(t, err)
|
||||
return strings.Trim(string(b), "\r\n")
|
||||
}
|
||||
require.FailNow(t, "file is absent: "+path)
|
||||
return ""
|
||||
|
@ -419,10 +389,9 @@ func TestRendererWalk(t *testing.T) {
|
|||
func TestRendererFailFunction(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/fail/template", "./testdata/fail/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/fail/template", "./testdata/fail/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -432,10 +401,9 @@ func TestRendererFailFunction(t *testing.T) {
|
|||
func TestRendererSkipsDirsEagerly(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/skip-dir-eagerly/template", "./testdata/skip-dir-eagerly/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/skip-dir-eagerly/template", "./testdata/skip-dir-eagerly/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -452,7 +420,7 @@ func TestRendererSkipAllFilesInCurrentDirectory(t *testing.T) {
|
|||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/skip-all-files-in-cwd/template", "./testdata/skip-all-files-in-cwd/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/skip-all-files-in-cwd/template", "./testdata/skip-all-files-in-cwd/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -460,7 +428,9 @@ func TestRendererSkipAllFilesInCurrentDirectory(t *testing.T) {
|
|||
// All 3 files are executed and have in memory representations
|
||||
require.Len(t, r.files, 3)
|
||||
|
||||
err = r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
require.NoError(t, err)
|
||||
|
||||
entries, err := os.ReadDir(tmpDir)
|
||||
|
@ -472,10 +442,9 @@ func TestRendererSkipAllFilesInCurrentDirectory(t *testing.T) {
|
|||
func TestRendererSkipPatternsAreRelativeToFileDirectory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/skip-is-relative/template", "./testdata/skip-is-relative/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/skip-is-relative/template", "./testdata/skip-is-relative/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -493,7 +462,7 @@ func TestRendererSkip(t *testing.T) {
|
|||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/skip/template", "./testdata/skip/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/skip/template", "./testdata/skip/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -502,7 +471,9 @@ func TestRendererSkip(t *testing.T) {
|
|||
// This is because "dir2/*" matches the files in dir2, but not dir2 itself
|
||||
assert.Len(t, r.files, 6)
|
||||
|
||||
err = r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.FileExists(t, filepath.Join(tmpDir, "file1"))
|
||||
|
@ -520,12 +491,11 @@ func TestRendererReadsPermissionsBits(t *testing.T) {
|
|||
if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
|
||||
t.SkipNow()
|
||||
}
|
||||
tmpDir := t.TempDir()
|
||||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/executable-bit-read/template", "./testdata/executable-bit-read/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/executable-bit-read/template", "./testdata/executable-bit-read/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -533,7 +503,7 @@ func TestRendererReadsPermissionsBits(t *testing.T) {
|
|||
|
||||
getPermissions := func(r *renderer, path string) fs.FileMode {
|
||||
for _, f := range r.files {
|
||||
if f.DstPath().relPath != path {
|
||||
if f.RelPath() != path {
|
||||
continue
|
||||
}
|
||||
switch v := f.(type) {
|
||||
|
@ -556,6 +526,7 @@ func TestRendererReadsPermissionsBits(t *testing.T) {
|
|||
|
||||
func TestRendererErrorOnConflictingFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
ctx := context.Background()
|
||||
|
||||
f, err := os.Create(filepath.Join(tmpDir, "a"))
|
||||
require.NoError(t, err)
|
||||
|
@ -566,17 +537,16 @@ func TestRendererErrorOnConflictingFile(t *testing.T) {
|
|||
skipPatterns: []string{},
|
||||
files: []file{
|
||||
&inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "a",
|
||||
},
|
||||
perm: 0444,
|
||||
relPath: "a",
|
||||
content: []byte("123"),
|
||||
},
|
||||
},
|
||||
}
|
||||
err = r.persistToDisk()
|
||||
assert.EqualError(t, err, fmt.Sprintf("failed to initialize template, one or more files already exist: %s", filepath.Join(tmpDir, "a")))
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
assert.EqualError(t, err, fmt.Sprintf("failed to initialize template, one or more files already exist: %s", "a"))
|
||||
}
|
||||
|
||||
func TestRendererNoErrorOnConflictingFileIfSkipped(t *testing.T) {
|
||||
|
@ -593,16 +563,15 @@ func TestRendererNoErrorOnConflictingFileIfSkipped(t *testing.T) {
|
|||
skipPatterns: []string{"a"},
|
||||
files: []file{
|
||||
&inMemoryFile{
|
||||
dstPath: &destinationPath{
|
||||
root: tmpDir,
|
||||
relPath: "a",
|
||||
},
|
||||
perm: 0444,
|
||||
relPath: "a",
|
||||
content: []byte("123"),
|
||||
},
|
||||
},
|
||||
}
|
||||
err = r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
// No error is returned even though a conflicting file exists. This is because
|
||||
// the generated file is being skipped
|
||||
assert.NoError(t, err)
|
||||
|
@ -612,10 +581,9 @@ func TestRendererNoErrorOnConflictingFileIfSkipped(t *testing.T) {
|
|||
func TestRendererNonTemplatesAreCreatedAsCopyFiles(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = root.SetWorkspaceClient(ctx, nil)
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
helpers := loadHelpers(ctx)
|
||||
r, err := newRenderer(ctx, nil, helpers, "./testdata/copy-file-walk/template", "./testdata/copy-file-walk/library", tmpDir)
|
||||
r, err := newRenderer(ctx, nil, helpers, os.DirFS("."), "./testdata/copy-file-walk/template", "./testdata/copy-file-walk/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -623,7 +591,7 @@ func TestRendererNonTemplatesAreCreatedAsCopyFiles(t *testing.T) {
|
|||
|
||||
assert.Len(t, r.files, 1)
|
||||
assert.Equal(t, r.files[0].(*copyFile).srcPath, "not-a-template")
|
||||
assert.Equal(t, r.files[0].DstPath().absPath(), filepath.Join(tmpDir, "not-a-template"))
|
||||
assert.Equal(t, r.files[0].RelPath(), "not-a-template")
|
||||
}
|
||||
|
||||
func TestRendererFileTreeRendering(t *testing.T) {
|
||||
|
@ -635,7 +603,7 @@ func TestRendererFileTreeRendering(t *testing.T) {
|
|||
r, err := newRenderer(ctx, map[string]any{
|
||||
"dir_name": "my_directory",
|
||||
"file_name": "my_file",
|
||||
}, helpers, "./testdata/file-tree-rendering/template", "./testdata/file-tree-rendering/library", tmpDir)
|
||||
}, helpers, os.DirFS("."), "./testdata/file-tree-rendering/template", "./testdata/file-tree-rendering/library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -643,9 +611,11 @@ func TestRendererFileTreeRendering(t *testing.T) {
|
|||
|
||||
// Assert in memory representation is created.
|
||||
assert.Len(t, r.files, 1)
|
||||
assert.Equal(t, r.files[0].DstPath().absPath(), filepath.Join(tmpDir, "my_directory", "my_file"))
|
||||
assert.Equal(t, r.files[0].RelPath(), "my_directory/my_file")
|
||||
|
||||
err = r.persistToDisk()
|
||||
out, err := filer.NewLocalClient(tmpDir)
|
||||
require.NoError(t, err)
|
||||
err = r.persistToDisk(ctx, out)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Assert files and directories are correctly materialized.
|
||||
|
@ -667,8 +637,7 @@ func TestRendererSubTemplateInPath(t *testing.T) {
|
|||
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file.
|
||||
testutil.Touch(t, filepath.Join(templateDir, "template/{{template `dir_name`}}/{{template `file_name`}}"))
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
r, err := newRenderer(ctx, nil, nil, filepath.Join(templateDir, "template"), filepath.Join(templateDir, "library"), tmpDir)
|
||||
r, err := newRenderer(ctx, nil, nil, os.DirFS(templateDir), "template", "library")
|
||||
require.NoError(t, err)
|
||||
|
||||
err = r.walk()
|
||||
|
@ -676,7 +645,6 @@ func TestRendererSubTemplateInPath(t *testing.T) {
|
|||
|
||||
if assert.Len(t, r.files, 2) {
|
||||
f := r.files[1]
|
||||
assert.Equal(t, filepath.Join(tmpDir, "my_directory", "my_file"), f.DstPath().absPath())
|
||||
assert.Equal(t, "my_directory/my_file", f.DstPath().relPath)
|
||||
assert.Equal(t, "my_directory/my_file", f.RelPath())
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue