From 325066daa53306730508014fc19be0a7dbefd9a3 Mon Sep 17 00:00:00 2001 From: Denis Bilenko Date: Thu, 12 Dec 2024 09:41:44 +0100 Subject: [PATCH 1/3] Enable gofumpt and apply everywhere --- .golangci.yaml | 1 + bundle/artifacts/all.go | 1 - bundle/artifacts/autodetect.go | 3 +- bundle/artifacts/expand_globs.go | 1 - bundle/artifacts/whl/autodetect.go | 3 +- bundle/bundle.go | 4 +- bundle/config/experimental.go | 6 +- bundle/config/generate/job.go | 6 +- bundle/config/loader/process_root_includes.go | 2 +- bundle/config/mutator/apply_presets_test.go | 1 - bundle/config/mutator/compute_id_compat.go | 1 - .../expand_pipeline_glob_paths_test.go | 2 +- bundle/config/mutator/initialize_urls.go | 3 +- bundle/config/mutator/override_compute.go | 2 +- .../config/mutator/paths/job_paths_visitor.go | 3 +- .../mutator/prepend_workspace_prefix.go | 2 - .../mutator/python/python_diagnostics_test.go | 1 - .../config/mutator/python/python_mutator.go | 10 +-- .../mutator/python/python_mutator_test.go | 11 ++- .../mutator/resolve_variable_references.go | 13 ++-- .../mutator/rewrite_workspace_prefix.go | 1 - .../mutator/rewrite_workspace_prefix_test.go | 1 - bundle/config/mutator/run_as.go | 3 +- bundle/config/mutator/set_variables.go | 1 - bundle/config/mutator/translate_paths.go | 4 +- bundle/config/mutator/translate_paths_test.go | 2 +- bundle/config/mutator/verify_cli_version.go | 3 +- bundle/config/presets.go | 6 +- bundle/config/root_test.go | 2 - bundle/config/validate/files_to_sync.go | 3 +- bundle/config/validate/folder_permissions.go | 3 +- .../validate/job_cluster_key_defined.go | 3 +- .../config/validate/job_task_cluster_spec.go | 3 +- .../validate/single_node_cluster_test.go | 1 - bundle/config/validate/validate.go | 3 +- .../config/validate/validate_sync_patterns.go | 3 +- bundle/config/variable/lookup_test.go | 1 - bundle/config/variable/resolve_cluster.go | 1 - bundle/deploy/state.go | 6 +- bundle/deploy/state_pull.go | 2 +- bundle/deploy/state_pull_test.go | 4 +- bundle/deploy/state_push_test.go | 2 +- bundle/deploy/state_update.go | 5 +- bundle/deploy/state_update_test.go | 2 +- .../check_dashboards_modified_remotely.go | 3 +- .../terraform/check_running_resources.go | 3 +- bundle/deploy/terraform/convert_test.go | 74 +++++++++---------- bundle/deploy/terraform/init_test.go | 4 +- bundle/deploy/terraform/interpolate.go | 3 +- bundle/deploy/terraform/pkg.go | 22 ++++-- bundle/deploy/terraform/state_pull.go | 6 +- .../terraform/tfdyn/convert_cluster_test.go | 3 +- .../terraform/tfdyn/convert_dashboard_test.go | 10 +-- .../tfdyn/convert_experiment_test.go | 2 +- .../terraform/tfdyn/convert_grants_test.go | 6 +- bundle/deploy/terraform/tfdyn/convert_job.go | 1 - .../terraform/tfdyn/convert_job_test.go | 2 +- .../convert_model_serving_endpoint_test.go | 2 +- .../terraform/tfdyn/convert_model_test.go | 2 +- .../tfdyn/convert_permissions_test.go | 6 +- .../terraform/tfdyn/convert_pipeline_test.go | 2 +- .../tfdyn/convert_quality_monitor_test.go | 2 +- .../tfdyn/convert_registered_model_test.go | 2 +- .../terraform/tfdyn/convert_schema_test.go | 2 +- .../terraform/tfdyn/convert_volume_test.go | 2 +- bundle/deploy/terraform/tfdyn/rename_keys.go | 3 +- bundle/internal/schema/main.go | 5 +- bundle/libraries/expand_glob_references.go | 5 +- bundle/libraries/filer_volume_test.go | 6 +- bundle/libraries/upload.go | 3 - bundle/permissions/filter.go | 1 - bundle/permissions/filter_test.go | 1 - bundle/permissions/mutator.go | 73 +++++++++--------- bundle/permissions/validate.go | 3 +- .../workspace_path_permissions_test.go | 1 - bundle/permissions/workspace_root.go | 3 +- bundle/render/render_text_output.go | 2 +- bundle/render/render_text_output_test.go | 3 +- bundle/root_test.go | 2 +- bundle/run/job.go | 1 - bundle/run/job_args.go | 2 +- bundle/run/job_options.go | 2 +- bundle/run/output/task.go | 16 ++-- bundle/run/pipeline.go | 3 +- bundle/tests/run_as_test.go | 2 - bundle/tests/variables_test.go | 2 +- bundle/trampoline/python_dbr_warning.go | 4 +- bundle/trampoline/python_wheel_test.go | 3 +- bundle/trampoline/trampoline.go | 2 +- bundle/trampoline/trampoline_test.go | 3 +- cmd/api/api.go | 2 +- cmd/auth/describe.go | 1 - cmd/auth/login.go | 6 +- cmd/bundle/generate/dashboard.go | 6 +- cmd/bundle/generate/generate_test.go | 2 +- cmd/bundle/generate/utils.go | 2 +- cmd/configure/configure_test.go | 2 +- cmd/labs/github/github.go | 12 ++- cmd/labs/localcache/jsonfile.go | 6 +- cmd/labs/project/entrypoint.go | 10 ++- cmd/labs/project/installer_test.go | 6 +- cmd/root/auth.go | 8 +- cmd/root/auth_test.go | 12 +-- cmd/root/bundle_test.go | 6 +- cmd/root/root.go | 3 +- cmd/root/user_agent_upstream.go | 12 ++- cmd/sync/sync.go | 1 - cmd/workspace/workspace/export_dir.go | 2 +- cmd/workspace/workspace/overrides.go | 3 +- internal/build/variables.go | 34 +++++---- internal/bundle/artifacts_test.go | 2 +- internal/bundle/clusters_test.go | 1 - internal/bundle/deploy_test.go | 1 - internal/bundle/deployment_state_test.go | 8 +- internal/bundle/generate_pipeline_test.go | 2 +- internal/bundle/helpers.go | 2 +- internal/filer_test.go | 1 - internal/fs_rm_test.go | 1 - internal/git_fetch_test.go | 12 +-- internal/helpers.go | 1 - internal/init_test.go | 8 +- internal/testutil/copy.go | 2 +- internal/testutil/file.go | 8 +- libs/cmdio/logger.go | 1 - libs/databrickscfg/cfgpickers/clusters.go | 6 +- libs/dyn/convert/from_typed_test.go | 70 +++++++++--------- libs/dyn/convert/struct_info.go | 4 +- libs/dyn/convert/struct_info_test.go | 4 +- libs/dyn/convert/to_typed_test.go | 20 ++--- libs/dyn/dynassert/assert_test.go | 2 +- libs/dyn/merge/merge.go | 1 + libs/dyn/merge/merge_test.go | 1 - libs/dyn/merge/override.go | 8 -- libs/dyn/value_test.go | 6 +- libs/dyn/visit_map_test.go | 8 +- libs/dyn/yamlloader/loader.go | 4 +- libs/dyn/yamlloader/yaml_spec_test.go | 3 +- libs/dyn/yamlsaver/saver.go | 2 +- libs/dyn/yamlsaver/saver_test.go | 44 +++++------ libs/exec/exec.go | 8 +- libs/filer/filer.go | 3 +- libs/filer/local_client.go | 7 +- libs/filer/slice_test.go | 3 +- .../workspace_files_extensions_client.go | 3 +- .../workspace_files_extensions_client_test.go | 3 +- libs/flags/json_flag_test.go | 2 +- libs/flags/log_file_flag.go | 2 +- libs/git/config_test.go | 4 +- libs/git/ignore_test.go | 2 +- libs/git/info.go | 1 - libs/git/reference.go | 12 ++- libs/git/view.go | 2 +- libs/git/view_test.go | 4 +- libs/jsonschema/validate_type.go | 6 +- libs/locker/locker.go | 2 +- libs/log/context.go | 1 - libs/log/logger.go | 3 +- libs/log/sdk.go | 3 +- libs/notebook/detect.go | 2 +- libs/notebook/detect_jupyter_test.go | 6 +- libs/notebook/detect_test.go | 4 +- libs/python/detect_test.go | 6 +- libs/python/interpreters.go | 6 +- libs/python/interpreters_unix_test.go | 2 +- libs/sync/snapshot.go | 9 +-- libs/sync/snapshot_state.go | 1 - libs/sync/sync.go | 2 +- libs/tags/gcp_test.go | 1 - libs/template/file_test.go | 8 +- libs/template/helpers.go | 8 +- libs/template/helpers_test.go | 2 - libs/template/materialize.go | 8 +- libs/template/renderer_test.go | 24 +++--- libs/textutil/textutil_test.go | 3 +- 174 files changed, 483 insertions(+), 500 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 7598646d35..9af371b717 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -9,6 +9,7 @@ linters: - staticcheck - unused - gofmt + - gofumpt linters-settings: govet: enable-all: true diff --git a/bundle/artifacts/all.go b/bundle/artifacts/all.go index 305193e2eb..768ccdfe3a 100644 --- a/bundle/artifacts/all.go +++ b/bundle/artifacts/all.go @@ -3,7 +3,6 @@ package artifacts import ( "context" "fmt" - "slices" "github.com/databricks/cli/bundle" diff --git a/bundle/artifacts/autodetect.go b/bundle/artifacts/autodetect.go index 569a480f00..c8d2356160 100644 --- a/bundle/artifacts/autodetect.go +++ b/bundle/artifacts/autodetect.go @@ -13,8 +13,7 @@ func DetectPackages() bundle.Mutator { return &autodetect{} } -type autodetect struct { -} +type autodetect struct{} func (m *autodetect) Name() string { return "artifacts.DetectPackages" diff --git a/bundle/artifacts/expand_globs.go b/bundle/artifacts/expand_globs.go index cdf3d45900..7d44db0be9 100644 --- a/bundle/artifacts/expand_globs.go +++ b/bundle/artifacts/expand_globs.go @@ -96,7 +96,6 @@ func (m *expandGlobs) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnost // Set the expanded globs back into the configuration. return dyn.SetByPath(v, base, dyn.V(output)) }) - if err != nil { return diag.FromErr(err) } diff --git a/bundle/artifacts/whl/autodetect.go b/bundle/artifacts/whl/autodetect.go index 3d17a698c0..202ea12bcc 100644 --- a/bundle/artifacts/whl/autodetect.go +++ b/bundle/artifacts/whl/autodetect.go @@ -15,8 +15,7 @@ import ( "github.com/databricks/cli/libs/log" ) -type detectPkg struct { -} +type detectPkg struct{} func DetectPackage() bundle.Mutator { return &detectPkg{} diff --git a/bundle/bundle.go b/bundle/bundle.go index 76c87c24cd..573bcef2f2 100644 --- a/bundle/bundle.go +++ b/bundle/bundle.go @@ -186,7 +186,7 @@ func (b *Bundle) CacheDir(ctx context.Context, paths ...string) (string, error) // Make directory if it doesn't exist yet. dir := filepath.Join(parts...) - err := os.MkdirAll(dir, 0700) + err := os.MkdirAll(dir, 0o700) if err != nil { return "", err } @@ -203,7 +203,7 @@ func (b *Bundle) InternalDir(ctx context.Context) (string, error) { } dir := filepath.Join(cacheDir, internalFolder) - err = os.MkdirAll(dir, 0700) + err = os.MkdirAll(dir, 0o700) if err != nil { return dir, err } diff --git a/bundle/config/experimental.go b/bundle/config/experimental.go index 061bbdae06..4c787168f8 100644 --- a/bundle/config/experimental.go +++ b/bundle/config/experimental.go @@ -47,8 +47,10 @@ type PyDABs struct { Import []string `json:"import,omitempty"` } -type Command string -type ScriptHook string +type ( + Command string + ScriptHook string +) // These hook names are subject to change and currently experimental const ( diff --git a/bundle/config/generate/job.go b/bundle/config/generate/job.go index 6cd7c1b328..0cdcbf3ad4 100644 --- a/bundle/config/generate/job.go +++ b/bundle/config/generate/job.go @@ -6,8 +6,10 @@ import ( "github.com/databricks/databricks-sdk-go/service/jobs" ) -var jobOrder = yamlsaver.NewOrder([]string{"name", "job_clusters", "compute", "tasks"}) -var taskOrder = yamlsaver.NewOrder([]string{"task_key", "depends_on", "existing_cluster_id", "new_cluster", "job_cluster_key"}) +var ( + jobOrder = yamlsaver.NewOrder([]string{"name", "job_clusters", "compute", "tasks"}) + taskOrder = yamlsaver.NewOrder([]string{"task_key", "depends_on", "existing_cluster_id", "new_cluster", "job_cluster_key"}) +) func ConvertJobToValue(job *jobs.Job) (dyn.Value, error) { value := make(map[string]dyn.Value) diff --git a/bundle/config/loader/process_root_includes.go b/bundle/config/loader/process_root_includes.go index c14fb7ce15..c608a3de61 100644 --- a/bundle/config/loader/process_root_includes.go +++ b/bundle/config/loader/process_root_includes.go @@ -27,7 +27,7 @@ func (m *processRootIncludes) Apply(ctx context.Context, b *bundle.Bundle) diag. var out []bundle.Mutator // Map with files we've already seen to avoid loading them twice. - var seen = map[string]bool{} + seen := map[string]bool{} for _, file := range config.FileNames { seen[file] = true diff --git a/bundle/config/mutator/apply_presets_test.go b/bundle/config/mutator/apply_presets_test.go index 91d5b62e5f..c26f203832 100644 --- a/bundle/config/mutator/apply_presets_test.go +++ b/bundle/config/mutator/apply_presets_test.go @@ -481,5 +481,4 @@ func TestApplyPresetsSourceLinkedDeployment(t *testing.T) { require.Equal(t, tt.expectedValue, b.Config.Presets.SourceLinkedDeployment) }) } - } diff --git a/bundle/config/mutator/compute_id_compat.go b/bundle/config/mutator/compute_id_compat.go index 3afe02e9e8..8f1ff5868e 100644 --- a/bundle/config/mutator/compute_id_compat.go +++ b/bundle/config/mutator/compute_id_compat.go @@ -42,7 +42,6 @@ func rewriteComputeIdToClusterId(v dyn.Value, p dyn.Path) (dyn.Value, diag.Diagn var diags diag.Diagnostics computeIdPath := p.Append(dyn.Key("compute_id")) computeId, err := dyn.GetByPath(v, computeIdPath) - // If the "compute_id" key is not set, we don't need to do anything. if err != nil { return v, nil diff --git a/bundle/config/mutator/expand_pipeline_glob_paths_test.go b/bundle/config/mutator/expand_pipeline_glob_paths_test.go index 9f70b74ae4..7cf3c9f3e3 100644 --- a/bundle/config/mutator/expand_pipeline_glob_paths_test.go +++ b/bundle/config/mutator/expand_pipeline_glob_paths_test.go @@ -17,7 +17,7 @@ import ( ) func touchEmptyFile(t *testing.T, path string) { - err := os.MkdirAll(filepath.Dir(path), 0700) + err := os.MkdirAll(filepath.Dir(path), 0o700) require.NoError(t, err) f, err := os.Create(path) require.NoError(t, err) diff --git a/bundle/config/mutator/initialize_urls.go b/bundle/config/mutator/initialize_urls.go index 4cf7ed72c0..25bb2c24a9 100644 --- a/bundle/config/mutator/initialize_urls.go +++ b/bundle/config/mutator/initialize_urls.go @@ -10,8 +10,7 @@ import ( "github.com/databricks/cli/libs/diag" ) -type initializeURLs struct { -} +type initializeURLs struct{} // InitializeURLs makes sure the URL field of each resource is configured. // NOTE: since this depends on an extra API call, this mutator adds some extra diff --git a/bundle/config/mutator/override_compute.go b/bundle/config/mutator/override_compute.go index f3a080ee80..3433034025 100644 --- a/bundle/config/mutator/override_compute.go +++ b/bundle/config/mutator/override_compute.go @@ -23,7 +23,7 @@ func (m *overrideCompute) Name() string { func overrideJobCompute(j *resources.Job, compute string) { for i := range j.Tasks { - var task = &j.Tasks[i] + task := &j.Tasks[i] if task.ForEachTask != nil { task = &task.ForEachTask.Task diff --git a/bundle/config/mutator/paths/job_paths_visitor.go b/bundle/config/mutator/paths/job_paths_visitor.go index 275a8fa536..1d713aaf55 100644 --- a/bundle/config/mutator/paths/job_paths_visitor.go +++ b/bundle/config/mutator/paths/job_paths_visitor.go @@ -95,7 +95,7 @@ func jobRewritePatterns() []jobRewritePattern { // VisitJobPaths visits all paths in job resources and applies a function to each path. func VisitJobPaths(value dyn.Value, fn VisitFunc) (dyn.Value, error) { var err error - var newValue = value + newValue := value for _, rewritePattern := range jobRewritePatterns() { newValue, err = dyn.MapByPattern(newValue, rewritePattern.pattern, func(p dyn.Path, v dyn.Value) (dyn.Value, error) { @@ -105,7 +105,6 @@ func VisitJobPaths(value dyn.Value, fn VisitFunc) (dyn.Value, error) { return fn(p, rewritePattern.kind, v) }) - if err != nil { return dyn.InvalidValue, err } diff --git a/bundle/config/mutator/prepend_workspace_prefix.go b/bundle/config/mutator/prepend_workspace_prefix.go index e0be2572d5..b093ec26a9 100644 --- a/bundle/config/mutator/prepend_workspace_prefix.go +++ b/bundle/config/mutator/prepend_workspace_prefix.go @@ -57,14 +57,12 @@ func (m *prependWorkspacePrefix) Apply(ctx context.Context, b *bundle.Bundle) di return dyn.NewValue(fmt.Sprintf("/Workspace%s", path), v.Locations()), nil }) - if err != nil { return dyn.InvalidValue, err } } return v, nil }) - if err != nil { return diag.FromErr(err) } diff --git a/bundle/config/mutator/python/python_diagnostics_test.go b/bundle/config/mutator/python/python_diagnostics_test.go index b73b0f73cd..fd6def8dad 100644 --- a/bundle/config/mutator/python/python_diagnostics_test.go +++ b/bundle/config/mutator/python/python_diagnostics_test.go @@ -30,7 +30,6 @@ type parsePythonDiagnosticsTest struct { } func TestParsePythonDiagnostics(t *testing.T) { - testCases := []parsePythonDiagnosticsTest{ { name: "short error with location", diff --git a/bundle/config/mutator/python/python_mutator.go b/bundle/config/mutator/python/python_mutator.go index da6c4d2102..8d95a01dc4 100644 --- a/bundle/config/mutator/python/python_mutator.go +++ b/bundle/config/mutator/python/python_mutator.go @@ -9,12 +9,11 @@ import ( "io" "os" "path/filepath" + "strings" "github.com/databricks/databricks-sdk-go/logger" "github.com/fatih/color" - "strings" - "github.com/databricks/cli/libs/python" "github.com/databricks/cli/bundle/env" @@ -94,11 +93,10 @@ func (m *pythonMutator) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagno // mutateDiags is used because Mutate returns 'error' instead of 'diag.Diagnostics' var mutateDiags diag.Diagnostics - var mutateDiagsHasError = errors.New("unexpected error") + mutateDiagsHasError := errors.New("unexpected error") err := b.Config.Mutate(func(leftRoot dyn.Value) (dyn.Value, error) { pythonPath, err := detectExecutable(ctx, experimental.PyDABs.VEnvPath) - if err != nil { return dyn.InvalidValue, fmt.Errorf("failed to get Python interpreter path: %w", err) } @@ -141,7 +139,7 @@ func createCacheDir(ctx context.Context) (string, error) { // use 'default' as target name cacheDir := filepath.Join(tempDir, "default", "pydabs") - err := os.MkdirAll(cacheDir, 0700) + err := os.MkdirAll(cacheDir, 0o700) if err != nil { return "", err } @@ -263,7 +261,7 @@ func writeInputFile(inputPath string, input dyn.Value) error { return fmt.Errorf("failed to marshal input: %w", err) } - return os.WriteFile(inputPath, rootConfigJson, 0600) + return os.WriteFile(inputPath, rootConfigJson, 0o600) } func loadOutputFile(rootPath string, outputPath string) (dyn.Value, diag.Diagnostics) { diff --git a/bundle/config/mutator/python/python_mutator_test.go b/bundle/config/mutator/python/python_mutator_test.go index 7a419d7991..7276a34510 100644 --- a/bundle/config/mutator/python/python_mutator_test.go +++ b/bundle/config/mutator/python/python_mutator_test.go @@ -106,7 +106,6 @@ func TestPythonMutator_load(t *testing.T) { Column: 5, }, }, diags[0].Locations) - } func TestPythonMutator_load_disallowed(t *testing.T) { @@ -611,10 +610,10 @@ func withProcessStub(t *testing.T, args []string, output string, diagnostics str assert.NoError(t, err) if reflect.DeepEqual(actual.Args, args) { - err := os.WriteFile(outputPath, []byte(output), 0600) + err := os.WriteFile(outputPath, []byte(output), 0o600) require.NoError(t, err) - err = os.WriteFile(diagnosticsPath, []byte(diagnostics), 0600) + err = os.WriteFile(diagnosticsPath, []byte(diagnostics), 0o600) require.NoError(t, err) return nil @@ -650,17 +649,17 @@ func withFakeVEnv(t *testing.T, venvPath string) { interpreterPath := interpreterPath(venvPath) - err = os.MkdirAll(filepath.Dir(interpreterPath), 0755) + err = os.MkdirAll(filepath.Dir(interpreterPath), 0o755) if err != nil { panic(err) } - err = os.WriteFile(interpreterPath, []byte(""), 0755) + err = os.WriteFile(interpreterPath, []byte(""), 0o755) if err != nil { panic(err) } - err = os.WriteFile(filepath.Join(venvPath, "pyvenv.cfg"), []byte(""), 0755) + err = os.WriteFile(filepath.Join(venvPath, "pyvenv.cfg"), []byte(""), 0o755) if err != nil { panic(err) } diff --git a/bundle/config/mutator/resolve_variable_references.go b/bundle/config/mutator/resolve_variable_references.go index 5e5b761090..8c207e375e 100644 --- a/bundle/config/mutator/resolve_variable_references.go +++ b/bundle/config/mutator/resolve_variable_references.go @@ -32,11 +32,12 @@ func ResolveVariableReferencesInLookup() bundle.Mutator { } func ResolveVariableReferencesInComplexVariables() bundle.Mutator { - return &resolveVariableReferences{prefixes: []string{ - "bundle", - "workspace", - "variables", - }, + return &resolveVariableReferences{ + prefixes: []string{ + "bundle", + "workspace", + "variables", + }, pattern: dyn.NewPattern(dyn.Key("variables"), dyn.AnyKey(), dyn.Key("value")), lookupFn: lookupForComplexVariables, skipFn: skipResolvingInNonComplexVariables, @@ -173,7 +174,6 @@ func (m *resolveVariableReferences) Apply(ctx context.Context, b *bundle.Bundle) return dyn.InvalidValue, dynvar.ErrSkipResolution }) }) - if err != nil { return dyn.InvalidValue, err } @@ -184,7 +184,6 @@ func (m *resolveVariableReferences) Apply(ctx context.Context, b *bundle.Bundle) diags = diags.Extend(normaliseDiags) return root, nil }) - if err != nil { diags = diags.Extend(diag.FromErr(err)) } diff --git a/bundle/config/mutator/rewrite_workspace_prefix.go b/bundle/config/mutator/rewrite_workspace_prefix.go index 8a39ee8a12..0ccb3314b9 100644 --- a/bundle/config/mutator/rewrite_workspace_prefix.go +++ b/bundle/config/mutator/rewrite_workspace_prefix.go @@ -63,7 +63,6 @@ func (m *rewriteWorkspacePrefix) Apply(ctx context.Context, b *bundle.Bundle) di return v, nil }) }) - if err != nil { return diag.FromErr(err) } diff --git a/bundle/config/mutator/rewrite_workspace_prefix_test.go b/bundle/config/mutator/rewrite_workspace_prefix_test.go index d75ec89dbd..48973a4cf1 100644 --- a/bundle/config/mutator/rewrite_workspace_prefix_test.go +++ b/bundle/config/mutator/rewrite_workspace_prefix_test.go @@ -81,5 +81,4 @@ func TestNoWorkspacePrefixUsed(t *testing.T) { require.Equal(t, "${workspace.artifact_path}/jar1.jar", b.Config.Resources.Jobs["test_job"].JobSettings.Tasks[1].Libraries[0].Jar) require.Equal(t, "${workspace.file_path}/notebook2", b.Config.Resources.Jobs["test_job"].JobSettings.Tasks[2].NotebookTask.NotebookPath) require.Equal(t, "${workspace.artifact_path}/jar2.jar", b.Config.Resources.Jobs["test_job"].JobSettings.Tasks[2].Libraries[0].Jar) - } diff --git a/bundle/config/mutator/run_as.go b/bundle/config/mutator/run_as.go index 0ca71e28e6..7a9e00de80 100644 --- a/bundle/config/mutator/run_as.go +++ b/bundle/config/mutator/run_as.go @@ -12,8 +12,7 @@ import ( "github.com/databricks/databricks-sdk-go/service/jobs" ) -type setRunAs struct { -} +type setRunAs struct{} // This mutator does two things: // diff --git a/bundle/config/mutator/set_variables.go b/bundle/config/mutator/set_variables.go index 47ce2ad03a..9e9f2dcfef 100644 --- a/bundle/config/mutator/set_variables.go +++ b/bundle/config/mutator/set_variables.go @@ -65,7 +65,6 @@ func setVariable(ctx context.Context, v dyn.Value, variable *variable.Variable, // We should have had a value to set for the variable at this point. return dyn.InvalidValue, fmt.Errorf(`no value assigned to required variable %s. Assignment can be done through the "--var" flag or by setting the %s environment variable`, name, bundleVarPrefix+name) - } func (m *setVariables) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { diff --git a/bundle/config/mutator/translate_paths.go b/bundle/config/mutator/translate_paths.go index 5e016d8a1e..af0f941201 100644 --- a/bundle/config/mutator/translate_paths.go +++ b/bundle/config/mutator/translate_paths.go @@ -275,8 +275,8 @@ func (m *translatePaths) Apply(_ context.Context, b *bundle.Bundle) diag.Diagnos } func gatherFallbackPaths(v dyn.Value, typ string) (map[string]string, error) { - var fallback = make(map[string]string) - var pattern = dyn.NewPattern(dyn.Key("resources"), dyn.Key(typ), dyn.AnyKey()) + fallback := make(map[string]string) + pattern := dyn.NewPattern(dyn.Key("resources"), dyn.Key(typ), dyn.AnyKey()) // Previous behavior was to use a resource's location as the base path to resolve // relative paths in its definition. With the introduction of [dyn.Value] throughout, diff --git a/bundle/config/mutator/translate_paths_test.go b/bundle/config/mutator/translate_paths_test.go index 8442ff6cf5..493abb8c5f 100644 --- a/bundle/config/mutator/translate_paths_test.go +++ b/bundle/config/mutator/translate_paths_test.go @@ -34,7 +34,7 @@ func touchNotebookFile(t *testing.T, path string) { } func touchEmptyFile(t *testing.T, path string) { - err := os.MkdirAll(filepath.Dir(path), 0700) + err := os.MkdirAll(filepath.Dir(path), 0o700) require.NoError(t, err) f, err := os.Create(path) require.NoError(t, err) diff --git a/bundle/config/mutator/verify_cli_version.go b/bundle/config/mutator/verify_cli_version.go index 279af44e6a..873e4f7806 100644 --- a/bundle/config/mutator/verify_cli_version.go +++ b/bundle/config/mutator/verify_cli_version.go @@ -15,8 +15,7 @@ func VerifyCliVersion() bundle.Mutator { return &verifyCliVersion{} } -type verifyCliVersion struct { -} +type verifyCliVersion struct{} func (v *verifyCliVersion) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { // No constraints specified, skip the check. diff --git a/bundle/config/presets.go b/bundle/config/presets.go index 30f56c0f85..252c5b5f74 100644 --- a/bundle/config/presets.go +++ b/bundle/config/presets.go @@ -1,7 +1,9 @@ package config -const Paused = "PAUSED" -const Unpaused = "UNPAUSED" +const ( + Paused = "PAUSED" + Unpaused = "UNPAUSED" +) type Presets struct { // NamePrefix to prepend to all resource names. diff --git a/bundle/config/root_test.go b/bundle/config/root_test.go index fc1c148c32..42fae49d98 100644 --- a/bundle/config/root_test.go +++ b/bundle/config/root_test.go @@ -168,7 +168,6 @@ func TestRootMergeTargetOverridesWithVariables(t *testing.T) { "key1": "value1", }, root.Variables["complex"].Default) assert.Equal(t, "complex var", root.Variables["complex"].Description) - } func TestIsFullVariableOverrideDef(t *testing.T) { @@ -252,5 +251,4 @@ func TestIsFullVariableOverrideDef(t *testing.T) { for i, tc := range testCases { assert.Equal(t, tc.expected, isFullVariableOverrideDef(tc.value), "test case %d", i) } - } diff --git a/bundle/config/validate/files_to_sync.go b/bundle/config/validate/files_to_sync.go index a142784828..b4de067730 100644 --- a/bundle/config/validate/files_to_sync.go +++ b/bundle/config/validate/files_to_sync.go @@ -13,8 +13,7 @@ func FilesToSync() bundle.ReadOnlyMutator { return &filesToSync{} } -type filesToSync struct { -} +type filesToSync struct{} func (v *filesToSync) Name() string { return "validate:files_to_sync" diff --git a/bundle/config/validate/folder_permissions.go b/bundle/config/validate/folder_permissions.go index 505e82a1e5..aa89a05519 100644 --- a/bundle/config/validate/folder_permissions.go +++ b/bundle/config/validate/folder_permissions.go @@ -15,8 +15,7 @@ import ( "golang.org/x/sync/errgroup" ) -type folderPermissions struct { -} +type folderPermissions struct{} // Apply implements bundle.ReadOnlyMutator. func (f *folderPermissions) Apply(ctx context.Context, b bundle.ReadOnlyBundle) diag.Diagnostics { diff --git a/bundle/config/validate/job_cluster_key_defined.go b/bundle/config/validate/job_cluster_key_defined.go index 368c3edb13..c3a1ab3df3 100644 --- a/bundle/config/validate/job_cluster_key_defined.go +++ b/bundle/config/validate/job_cluster_key_defined.go @@ -13,8 +13,7 @@ func JobClusterKeyDefined() bundle.ReadOnlyMutator { return &jobClusterKeyDefined{} } -type jobClusterKeyDefined struct { -} +type jobClusterKeyDefined struct{} func (v *jobClusterKeyDefined) Name() string { return "validate:job_cluster_key_defined" diff --git a/bundle/config/validate/job_task_cluster_spec.go b/bundle/config/validate/job_task_cluster_spec.go index b80befcdff..5f532acfe6 100644 --- a/bundle/config/validate/job_task_cluster_spec.go +++ b/bundle/config/validate/job_task_cluster_spec.go @@ -17,8 +17,7 @@ func JobTaskClusterSpec() bundle.ReadOnlyMutator { return &jobTaskClusterSpec{} } -type jobTaskClusterSpec struct { -} +type jobTaskClusterSpec struct{} func (v *jobTaskClusterSpec) Name() string { return "validate:job_task_cluster_spec" diff --git a/bundle/config/validate/single_node_cluster_test.go b/bundle/config/validate/single_node_cluster_test.go index 18771cc00d..c3ead8ef63 100644 --- a/bundle/config/validate/single_node_cluster_test.go +++ b/bundle/config/validate/single_node_cluster_test.go @@ -175,7 +175,6 @@ func TestValidateSingleNodeClusterFailForJobClusters(t *testing.T) { Paths: []dyn.Path{dyn.MustPathFromString("resources.jobs.foo.job_clusters[0].new_cluster")}, }, }, diags) - }) } } diff --git a/bundle/config/validate/validate.go b/bundle/config/validate/validate.go index eb4c3c3cd2..131566fc90 100644 --- a/bundle/config/validate/validate.go +++ b/bundle/config/validate/validate.go @@ -8,8 +8,7 @@ import ( "github.com/databricks/cli/libs/dyn" ) -type validate struct { -} +type validate struct{} type location struct { path string diff --git a/bundle/config/validate/validate_sync_patterns.go b/bundle/config/validate/validate_sync_patterns.go index 52f06835c4..f5787a81d2 100644 --- a/bundle/config/validate/validate_sync_patterns.go +++ b/bundle/config/validate/validate_sync_patterns.go @@ -17,8 +17,7 @@ func ValidateSyncPatterns() bundle.ReadOnlyMutator { return &validateSyncPatterns{} } -type validateSyncPatterns struct { -} +type validateSyncPatterns struct{} func (v *validateSyncPatterns) Name() string { return "validate:validate_sync_patterns" diff --git a/bundle/config/variable/lookup_test.go b/bundle/config/variable/lookup_test.go index a847487512..bd54d89fcd 100644 --- a/bundle/config/variable/lookup_test.go +++ b/bundle/config/variable/lookup_test.go @@ -42,7 +42,6 @@ func TestLookup_Empty(t *testing.T) { // No string representation for an invalid lookup assert.Empty(t, lookup.String()) - } func TestLookup_Multiple(t *testing.T) { diff --git a/bundle/config/variable/resolve_cluster.go b/bundle/config/variable/resolve_cluster.go index 2d68b7fb7b..a8cf3fe7f4 100644 --- a/bundle/config/variable/resolve_cluster.go +++ b/bundle/config/variable/resolve_cluster.go @@ -20,7 +20,6 @@ func (l resolveCluster) Resolve(ctx context.Context, w *databricks.WorkspaceClie ClusterSources: []compute.ClusterSource{compute.ClusterSourceApi, compute.ClusterSourceUi}, }, }) - if err != nil { return "", err } diff --git a/bundle/deploy/state.go b/bundle/deploy/state.go index 4f2bc4ee4c..6dc359087c 100644 --- a/bundle/deploy/state.go +++ b/bundle/deploy/state.go @@ -15,8 +15,10 @@ import ( "github.com/google/uuid" ) -const DeploymentStateFileName = "deployment.json" -const DeploymentStateVersion = 1 +const ( + DeploymentStateFileName = "deployment.json" + DeploymentStateVersion = 1 +) type File struct { LocalPath string `json:"local_path"` diff --git a/bundle/deploy/state_pull.go b/bundle/deploy/state_pull.go index 96f138e9d3..8fffca073d 100644 --- a/bundle/deploy/state_pull.go +++ b/bundle/deploy/state_pull.go @@ -44,7 +44,7 @@ func (s *statePull) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostic return diag.FromErr(err) } - local, err := os.OpenFile(statePath, os.O_CREATE|os.O_RDWR, 0600) + local, err := os.OpenFile(statePath, os.O_CREATE|os.O_RDWR, 0o600) if err != nil { return diag.FromErr(err) } diff --git a/bundle/deploy/state_pull_test.go b/bundle/deploy/state_pull_test.go index 42701eb26f..36c49fb01c 100644 --- a/bundle/deploy/state_pull_test.go +++ b/bundle/deploy/state_pull_test.go @@ -99,7 +99,7 @@ func testStatePull(t *testing.T, opts statePullOpts) { snapshotPath, err := sync.SnapshotPath(opts) require.NoError(t, err) - err = os.WriteFile(snapshotPath, []byte("snapshot"), 0644) + err = os.WriteFile(snapshotPath, []byte("snapshot"), 0o644) require.NoError(t, err) } @@ -110,7 +110,7 @@ func testStatePull(t *testing.T, opts statePullOpts) { data, err := json.Marshal(opts.localState) require.NoError(t, err) - err = os.WriteFile(statePath, data, 0644) + err = os.WriteFile(statePath, data, 0o644) require.NoError(t, err) } diff --git a/bundle/deploy/state_push_test.go b/bundle/deploy/state_push_test.go index 038b753412..3562ec147e 100644 --- a/bundle/deploy/state_push_test.go +++ b/bundle/deploy/state_push_test.go @@ -74,7 +74,7 @@ func TestStatePush(t *testing.T) { data, err := json.Marshal(state) require.NoError(t, err) - err = os.WriteFile(statePath, data, 0644) + err = os.WriteFile(statePath, data, 0o644) require.NoError(t, err) diags := bundle.Apply(ctx, b, s) diff --git a/bundle/deploy/state_update.go b/bundle/deploy/state_update.go index 9ab1bacf13..5488d50ed3 100644 --- a/bundle/deploy/state_update.go +++ b/bundle/deploy/state_update.go @@ -17,8 +17,7 @@ import ( "github.com/google/uuid" ) -type stateUpdate struct { -} +type stateUpdate struct{} func (s *stateUpdate) Name() string { return "deploy:state-update" @@ -57,7 +56,7 @@ func (s *stateUpdate) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnost return diag.FromErr(err) } // Write the state back to the file. - f, err := os.OpenFile(statePath, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600) + f, err := os.OpenFile(statePath, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0o600) if err != nil { log.Infof(ctx, "Unable to open deployment state file: %s", err) return diag.FromErr(err) diff --git a/bundle/deploy/state_update_test.go b/bundle/deploy/state_update_test.go index 1f5010b521..e561f534ea 100644 --- a/bundle/deploy/state_update_test.go +++ b/bundle/deploy/state_update_test.go @@ -119,7 +119,7 @@ func TestStateUpdateWithExistingState(t *testing.T) { data, err := json.Marshal(state) require.NoError(t, err) - err = os.WriteFile(statePath, data, 0644) + err = os.WriteFile(statePath, data, 0o644) require.NoError(t, err) diags := bundle.Apply(ctx, b, s) diff --git a/bundle/deploy/terraform/check_dashboards_modified_remotely.go b/bundle/deploy/terraform/check_dashboards_modified_remotely.go index c884bcb9b4..f263e8a7fe 100644 --- a/bundle/deploy/terraform/check_dashboards_modified_remotely.go +++ b/bundle/deploy/terraform/check_dashboards_modified_remotely.go @@ -42,8 +42,7 @@ func collectDashboardsFromState(ctx context.Context, b *bundle.Bundle) ([]dashbo return dashboards, nil } -type checkDashboardsModifiedRemotely struct { -} +type checkDashboardsModifiedRemotely struct{} func (l *checkDashboardsModifiedRemotely) Name() string { return "CheckDashboardsModifiedRemotely" diff --git a/bundle/deploy/terraform/check_running_resources.go b/bundle/deploy/terraform/check_running_resources.go index 737f773e56..5b3a704083 100644 --- a/bundle/deploy/terraform/check_running_resources.go +++ b/bundle/deploy/terraform/check_running_resources.go @@ -23,8 +23,7 @@ func (e ErrResourceIsRunning) Error() string { return fmt.Sprintf("%s %s is running", e.resourceType, e.resourceId) } -type checkRunningResources struct { -} +type checkRunningResources struct{} func (l *checkRunningResources) Name() string { return "check-running-resources" diff --git a/bundle/deploy/terraform/convert_test.go b/bundle/deploy/terraform/convert_test.go index 076d9b7a05..61f26c0886 100644 --- a/bundle/deploy/terraform/convert_test.go +++ b/bundle/deploy/terraform/convert_test.go @@ -43,7 +43,7 @@ func convertToResourceStruct[T any](t *testing.T, resource *T, data any) { } func TestBundleToTerraformJob(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ JobSettings: &jobs.JobSettings{ Name: "my job", JobClusters: []jobs.JobCluster{ @@ -71,7 +71,7 @@ func TestBundleToTerraformJob(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "my_job": &src, @@ -93,7 +93,7 @@ func TestBundleToTerraformJob(t *testing.T) { } func TestBundleToTerraformJobPermissions(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ Permissions: []resources.Permission{ { Level: "CAN_VIEW", @@ -102,7 +102,7 @@ func TestBundleToTerraformJobPermissions(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "my_job": &src, @@ -121,7 +121,7 @@ func TestBundleToTerraformJobPermissions(t *testing.T) { } func TestBundleToTerraformJobTaskLibraries(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ JobSettings: &jobs.JobSettings{ Name: "my job", Tasks: []jobs.Task{ @@ -139,7 +139,7 @@ func TestBundleToTerraformJobTaskLibraries(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "my_job": &src, @@ -158,7 +158,7 @@ func TestBundleToTerraformJobTaskLibraries(t *testing.T) { } func TestBundleToTerraformForEachTaskLibraries(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ JobSettings: &jobs.JobSettings{ Name: "my job", Tasks: []jobs.Task{ @@ -182,7 +182,7 @@ func TestBundleToTerraformForEachTaskLibraries(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "my_job": &src, @@ -201,7 +201,7 @@ func TestBundleToTerraformForEachTaskLibraries(t *testing.T) { } func TestBundleToTerraformPipeline(t *testing.T) { - var src = resources.Pipeline{ + src := resources.Pipeline{ PipelineSpec: &pipelines.PipelineSpec{ Name: "my pipeline", Libraries: []pipelines.PipelineLibrary{ @@ -239,7 +239,7 @@ func TestBundleToTerraformPipeline(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Pipelines: map[string]*resources.Pipeline{ "my_pipeline": &src, @@ -262,7 +262,7 @@ func TestBundleToTerraformPipeline(t *testing.T) { } func TestBundleToTerraformPipelinePermissions(t *testing.T) { - var src = resources.Pipeline{ + src := resources.Pipeline{ Permissions: []resources.Permission{ { Level: "CAN_VIEW", @@ -271,7 +271,7 @@ func TestBundleToTerraformPipelinePermissions(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Pipelines: map[string]*resources.Pipeline{ "my_pipeline": &src, @@ -290,7 +290,7 @@ func TestBundleToTerraformPipelinePermissions(t *testing.T) { } func TestBundleToTerraformModel(t *testing.T) { - var src = resources.MlflowModel{ + src := resources.MlflowModel{ Model: &ml.Model{ Name: "name", Description: "description", @@ -307,7 +307,7 @@ func TestBundleToTerraformModel(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Models: map[string]*resources.MlflowModel{ "my_model": &src, @@ -330,7 +330,7 @@ func TestBundleToTerraformModel(t *testing.T) { } func TestBundleToTerraformModelPermissions(t *testing.T) { - var src = resources.MlflowModel{ + src := resources.MlflowModel{ Model: &ml.Model{ Name: "name", }, @@ -342,7 +342,7 @@ func TestBundleToTerraformModelPermissions(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Models: map[string]*resources.MlflowModel{ "my_model": &src, @@ -361,13 +361,13 @@ func TestBundleToTerraformModelPermissions(t *testing.T) { } func TestBundleToTerraformExperiment(t *testing.T) { - var src = resources.MlflowExperiment{ + src := resources.MlflowExperiment{ Experiment: &ml.Experiment{ Name: "name", }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Experiments: map[string]*resources.MlflowExperiment{ "my_experiment": &src, @@ -384,7 +384,7 @@ func TestBundleToTerraformExperiment(t *testing.T) { } func TestBundleToTerraformExperimentPermissions(t *testing.T) { - var src = resources.MlflowExperiment{ + src := resources.MlflowExperiment{ Experiment: &ml.Experiment{ Name: "name", }, @@ -396,7 +396,7 @@ func TestBundleToTerraformExperimentPermissions(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Experiments: map[string]*resources.MlflowExperiment{ "my_experiment": &src, @@ -415,7 +415,7 @@ func TestBundleToTerraformExperimentPermissions(t *testing.T) { } func TestBundleToTerraformModelServing(t *testing.T) { - var src = resources.ModelServingEndpoint{ + src := resources.ModelServingEndpoint{ CreateServingEndpoint: &serving.CreateServingEndpoint{ Name: "name", Config: serving.EndpointCoreConfigInput{ @@ -439,7 +439,7 @@ func TestBundleToTerraformModelServing(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ ModelServingEndpoints: map[string]*resources.ModelServingEndpoint{ "my_model_serving_endpoint": &src, @@ -462,7 +462,7 @@ func TestBundleToTerraformModelServing(t *testing.T) { } func TestBundleToTerraformModelServingPermissions(t *testing.T) { - var src = resources.ModelServingEndpoint{ + src := resources.ModelServingEndpoint{ CreateServingEndpoint: &serving.CreateServingEndpoint{ Name: "name", @@ -492,7 +492,7 @@ func TestBundleToTerraformModelServingPermissions(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ ModelServingEndpoints: map[string]*resources.ModelServingEndpoint{ "my_model_serving_endpoint": &src, @@ -511,7 +511,7 @@ func TestBundleToTerraformModelServingPermissions(t *testing.T) { } func TestBundleToTerraformRegisteredModel(t *testing.T) { - var src = resources.RegisteredModel{ + src := resources.RegisteredModel{ CreateRegisteredModelRequest: &catalog.CreateRegisteredModelRequest{ Name: "name", CatalogName: "catalog", @@ -520,7 +520,7 @@ func TestBundleToTerraformRegisteredModel(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ RegisteredModels: map[string]*resources.RegisteredModel{ "my_registered_model": &src, @@ -540,7 +540,7 @@ func TestBundleToTerraformRegisteredModel(t *testing.T) { } func TestBundleToTerraformRegisteredModelGrants(t *testing.T) { - var src = resources.RegisteredModel{ + src := resources.RegisteredModel{ CreateRegisteredModelRequest: &catalog.CreateRegisteredModelRequest{ Name: "name", CatalogName: "catalog", @@ -554,7 +554,7 @@ func TestBundleToTerraformRegisteredModelGrants(t *testing.T) { }, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ RegisteredModels: map[string]*resources.RegisteredModel{ "my_registered_model": &src, @@ -573,14 +573,14 @@ func TestBundleToTerraformRegisteredModelGrants(t *testing.T) { } func TestBundleToTerraformDeletedResources(t *testing.T) { - var job1 = resources.Job{ + job1 := resources.Job{ JobSettings: &jobs.JobSettings{}, } - var job2 = resources.Job{ + job2 := resources.Job{ ModifiedStatus: resources.ModifiedStatusDeleted, JobSettings: &jobs.JobSettings{}, } - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "my_job1": &job1, @@ -601,10 +601,10 @@ func TestBundleToTerraformDeletedResources(t *testing.T) { } func TestTerraformToBundleEmptyLocalResources(t *testing.T) { - var config = config.Root{ + config := config.Root{ Resources: config.Resources{}, } - var tfState = resourcesState{ + tfState := resourcesState{ Resources: []stateResource{ { Type: "databricks_job", @@ -736,7 +736,7 @@ func TestTerraformToBundleEmptyLocalResources(t *testing.T) { } func TestTerraformToBundleEmptyRemoteResources(t *testing.T) { - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "test_job": { @@ -817,7 +817,7 @@ func TestTerraformToBundleEmptyRemoteResources(t *testing.T) { }, }, } - var tfState = resourcesState{ + tfState := resourcesState{ Resources: nil, } err := TerraformToBundle(&tfState, &config) @@ -860,7 +860,7 @@ func TestTerraformToBundleEmptyRemoteResources(t *testing.T) { } func TestTerraformToBundleModifiedResources(t *testing.T) { - var config = config.Root{ + config := config.Root{ Resources: config.Resources{ Jobs: map[string]*resources.Job{ "test_job": { @@ -996,7 +996,7 @@ func TestTerraformToBundleModifiedResources(t *testing.T) { }, }, } - var tfState = resourcesState{ + tfState := resourcesState{ Resources: []stateResource{ { Type: "databricks_job", diff --git a/bundle/deploy/terraform/init_test.go b/bundle/deploy/terraform/init_test.go index e3621c6c33..72218d5e27 100644 --- a/bundle/deploy/terraform/init_test.go +++ b/bundle/deploy/terraform/init_test.go @@ -409,7 +409,7 @@ func createTempFile(t *testing.T, dest string, name string, executable bool) str require.NoError(t, err) }() if executable { - err = f.Chmod(0777) + err = f.Chmod(0o777) require.NoError(t, err) } return binPath @@ -422,7 +422,7 @@ func TestGetEnvVarWithMatchingVersion(t *testing.T) { tmp := t.TempDir() file := testutil.Touch(t, tmp, "bar") - var tc = []struct { + tc := []struct { envValue string versionValue string currentVersion string diff --git a/bundle/deploy/terraform/interpolate.go b/bundle/deploy/terraform/interpolate.go index 9c2126aeca..813e6bbb7a 100644 --- a/bundle/deploy/terraform/interpolate.go +++ b/bundle/deploy/terraform/interpolate.go @@ -10,8 +10,7 @@ import ( "github.com/databricks/cli/libs/dyn/dynvar" ) -type interpolateMutator struct { -} +type interpolateMutator struct{} func Interpolate() bundle.Mutator { return &interpolateMutator{} diff --git a/bundle/deploy/terraform/pkg.go b/bundle/deploy/terraform/pkg.go index cad7540240..bd636639fb 100644 --- a/bundle/deploy/terraform/pkg.go +++ b/bundle/deploy/terraform/pkg.go @@ -5,15 +5,19 @@ import ( "github.com/hashicorp/go-version" ) -const TerraformStateFileName = "terraform.tfstate" -const TerraformConfigFileName = "bundle.tf.json" +const ( + TerraformStateFileName = "terraform.tfstate" + TerraformConfigFileName = "bundle.tf.json" +) // Users can provide their own terraform binary and databricks terraform provider by setting the following environment variables. // This allows users to use the CLI in an air-gapped environments. See the `debug terraform` command. -const TerraformExecPathEnv = "DATABRICKS_TF_EXEC_PATH" -const TerraformVersionEnv = "DATABRICKS_TF_VERSION" -const TerraformCliConfigPathEnv = "DATABRICKS_TF_CLI_CONFIG_FILE" -const TerraformProviderVersionEnv = "DATABRICKS_TF_PROVIDER_VERSION" +const ( + TerraformExecPathEnv = "DATABRICKS_TF_EXEC_PATH" + TerraformVersionEnv = "DATABRICKS_TF_VERSION" + TerraformCliConfigPathEnv = "DATABRICKS_TF_CLI_CONFIG_FILE" + TerraformProviderVersionEnv = "DATABRICKS_TF_PROVIDER_VERSION" +) // Terraform CLI version to use and the corresponding checksums for it. The // checksums are used to verify the integrity of the downloaded binary. Please @@ -26,8 +30,10 @@ const TerraformProviderVersionEnv = "DATABRICKS_TF_PROVIDER_VERSION" // downloaded Terraform archive. var TerraformVersion = version.Must(version.NewVersion("1.5.5")) -const checksumLinuxArm64 = "b055aefe343d0b710d8a7afd31aeb702b37bbf4493bb9385a709991e48dfbcd2" -const checksumLinuxAmd64 = "ad0c696c870c8525357b5127680cd79c0bdf58179af9acd091d43b1d6482da4a" +const ( + checksumLinuxArm64 = "b055aefe343d0b710d8a7afd31aeb702b37bbf4493bb9385a709991e48dfbcd2" + checksumLinuxAmd64 = "ad0c696c870c8525357b5127680cd79c0bdf58179af9acd091d43b1d6482da4a" +) type Checksum struct { LinuxArm64 string `json:"linux_arm64"` diff --git a/bundle/deploy/terraform/state_pull.go b/bundle/deploy/terraform/state_pull.go index 9a5b910076..4e1e2b1c57 100644 --- a/bundle/deploy/terraform/state_pull.go +++ b/bundle/deploy/terraform/state_pull.go @@ -104,7 +104,7 @@ func (l *statePull) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostic localState, err := l.localState(ctx, b) if errors.Is(err, fs.ErrNotExist) { log.Infof(ctx, "Local state file does not exist. Using remote Terraform state.") - err := os.WriteFile(localStatePath, remoteContent, 0600) + err := os.WriteFile(localStatePath, remoteContent, 0o600) return diag.FromErr(err) } if err != nil { @@ -114,14 +114,14 @@ func (l *statePull) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostic // If the lineage does not match, the Terraform state files do not correspond to the same deployment. if localState.Lineage != remoteState.Lineage { log.Infof(ctx, "Remote and local state lineages do not match. Using remote Terraform state. Invalidating local Terraform state.") - err := os.WriteFile(localStatePath, remoteContent, 0600) + err := os.WriteFile(localStatePath, remoteContent, 0o600) return diag.FromErr(err) } // If the remote state is newer than the local state, we should use the remote state. if remoteState.Serial > localState.Serial { log.Infof(ctx, "Remote state is newer than local state. Using remote Terraform state.") - err := os.WriteFile(localStatePath, remoteContent, 0600) + err := os.WriteFile(localStatePath, remoteContent, 0o600) return diag.FromErr(err) } diff --git a/bundle/deploy/terraform/tfdyn/convert_cluster_test.go b/bundle/deploy/terraform/tfdyn/convert_cluster_test.go index e6d2620c6a..330720a7cc 100644 --- a/bundle/deploy/terraform/tfdyn/convert_cluster_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_cluster_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertCluster(t *testing.T) { - var src = resources.Cluster{ + src := resources.Cluster{ ClusterSpec: &compute.ClusterSpec{ NumWorkers: 3, SparkVersion: "13.3.x-scala2.12", @@ -93,5 +93,4 @@ func TestConvertCluster(t *testing.T) { }, }, }, out.Permissions["cluster_my_cluster"]) - } diff --git a/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go b/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go index 539ba21aab..6f5d365041 100644 --- a/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_dashboard_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertDashboard(t *testing.T) { - var src = resources.Dashboard{ + src := resources.Dashboard{ Dashboard: &dashboards.Dashboard{ DisplayName: "my dashboard", WarehouseId: "f00dcafe", @@ -60,7 +60,7 @@ func TestConvertDashboard(t *testing.T) { } func TestConvertDashboardFilePath(t *testing.T) { - var src = resources.Dashboard{ + src := resources.Dashboard{ FilePath: "some/path", } @@ -84,7 +84,7 @@ func TestConvertDashboardFilePath(t *testing.T) { } func TestConvertDashboardFilePathQuoted(t *testing.T) { - var src = resources.Dashboard{ + src := resources.Dashboard{ FilePath: `C:\foo\bar\baz\dashboard.lvdash.json`, } @@ -108,7 +108,7 @@ func TestConvertDashboardFilePathQuoted(t *testing.T) { } func TestConvertDashboardSerializedDashboardString(t *testing.T) { - var src = resources.Dashboard{ + src := resources.Dashboard{ SerializedDashboard: `{ "json": true }`, } @@ -127,7 +127,7 @@ func TestConvertDashboardSerializedDashboardString(t *testing.T) { } func TestConvertDashboardSerializedDashboardAny(t *testing.T) { - var src = resources.Dashboard{ + src := resources.Dashboard{ SerializedDashboard: map[string]any{ "pages": []map[string]any{ { diff --git a/bundle/deploy/terraform/tfdyn/convert_experiment_test.go b/bundle/deploy/terraform/tfdyn/convert_experiment_test.go index 63add43681..3ef3963f26 100644 --- a/bundle/deploy/terraform/tfdyn/convert_experiment_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_experiment_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertExperiment(t *testing.T) { - var src = resources.MlflowExperiment{ + src := resources.MlflowExperiment{ Experiment: &ml.Experiment{ Name: "name", }, diff --git a/bundle/deploy/terraform/tfdyn/convert_grants_test.go b/bundle/deploy/terraform/tfdyn/convert_grants_test.go index a486bc36f3..0a263b493d 100644 --- a/bundle/deploy/terraform/tfdyn/convert_grants_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_grants_test.go @@ -13,7 +13,7 @@ import ( ) func TestConvertGrants(t *testing.T) { - var src = resources.RegisteredModel{ + src := resources.RegisteredModel{ Grants: []resources.Grant{ { Privileges: []string{"EXECUTE", "FOO"}, @@ -45,7 +45,7 @@ func TestConvertGrants(t *testing.T) { } func TestConvertGrantsNil(t *testing.T) { - var src = resources.RegisteredModel{ + src := resources.RegisteredModel{ Grants: nil, } @@ -58,7 +58,7 @@ func TestConvertGrantsNil(t *testing.T) { } func TestConvertGrantsEmpty(t *testing.T) { - var src = resources.RegisteredModel{ + src := resources.RegisteredModel{ Grants: []resources.Grant{}, } diff --git a/bundle/deploy/terraform/tfdyn/convert_job.go b/bundle/deploy/terraform/tfdyn/convert_job.go index 8948e3bafd..bb2f8cd0fe 100644 --- a/bundle/deploy/terraform/tfdyn/convert_job.go +++ b/bundle/deploy/terraform/tfdyn/convert_job.go @@ -83,7 +83,6 @@ func convertJobResource(ctx context.Context, vin dyn.Value) (dyn.Value, error) { "libraries": "library", }) }) - if err != nil { return dyn.InvalidValue, err } diff --git a/bundle/deploy/terraform/tfdyn/convert_job_test.go b/bundle/deploy/terraform/tfdyn/convert_job_test.go index 695b9ba249..c73e530d48 100644 --- a/bundle/deploy/terraform/tfdyn/convert_job_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_job_test.go @@ -15,7 +15,7 @@ import ( ) func TestConvertJob(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ JobSettings: &jobs.JobSettings{ Name: "my job", JobClusters: []jobs.JobCluster{ diff --git a/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go b/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go index 63b75e9ab3..d46350bb71 100644 --- a/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_model_serving_endpoint_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertModelServingEndpoint(t *testing.T) { - var src = resources.ModelServingEndpoint{ + src := resources.ModelServingEndpoint{ CreateServingEndpoint: &serving.CreateServingEndpoint{ Name: "name", Config: serving.EndpointCoreConfigInput{ diff --git a/bundle/deploy/terraform/tfdyn/convert_model_test.go b/bundle/deploy/terraform/tfdyn/convert_model_test.go index 542caa878b..4c4e62c5b6 100644 --- a/bundle/deploy/terraform/tfdyn/convert_model_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_model_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertModel(t *testing.T) { - var src = resources.MlflowModel{ + src := resources.MlflowModel{ Model: &ml.Model{ Name: "name", Description: "description", diff --git a/bundle/deploy/terraform/tfdyn/convert_permissions_test.go b/bundle/deploy/terraform/tfdyn/convert_permissions_test.go index ba389020f9..ba04384b57 100644 --- a/bundle/deploy/terraform/tfdyn/convert_permissions_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_permissions_test.go @@ -13,7 +13,7 @@ import ( ) func TestConvertPermissions(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ Permissions: []resources.Permission{ { Level: "CAN_VIEW", @@ -59,7 +59,7 @@ func TestConvertPermissions(t *testing.T) { } func TestConvertPermissionsNil(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ Permissions: nil, } @@ -72,7 +72,7 @@ func TestConvertPermissionsNil(t *testing.T) { } func TestConvertPermissionsEmpty(t *testing.T) { - var src = resources.Job{ + src := resources.Job{ Permissions: []resources.Permission{}, } diff --git a/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go b/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go index 7010d463a8..0239bad188 100644 --- a/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_pipeline_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertPipeline(t *testing.T) { - var src = resources.Pipeline{ + src := resources.Pipeline{ PipelineSpec: &pipelines.PipelineSpec{ Name: "my pipeline", Libraries: []pipelines.PipelineLibrary{ diff --git a/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go b/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go index f71abf43cc..16b30de71e 100644 --- a/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_quality_monitor_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertQualityMonitor(t *testing.T) { - var src = resources.QualityMonitor{ + src := resources.QualityMonitor{ TableName: "test_table_name", CreateMonitor: &catalog.CreateMonitor{ AssetsDir: "assets_dir", diff --git a/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go b/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go index 77096e8d09..bf2a5ab640 100644 --- a/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_registered_model_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertRegisteredModel(t *testing.T) { - var src = resources.RegisteredModel{ + src := resources.RegisteredModel{ CreateRegisteredModelRequest: &catalog.CreateRegisteredModelRequest{ Name: "name", CatalogName: "catalog", diff --git a/bundle/deploy/terraform/tfdyn/convert_schema_test.go b/bundle/deploy/terraform/tfdyn/convert_schema_test.go index 2efbf3e430..12822bb3ce 100644 --- a/bundle/deploy/terraform/tfdyn/convert_schema_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_schema_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertSchema(t *testing.T) { - var src = resources.Schema{ + src := resources.Schema{ CreateSchema: &catalog.CreateSchema{ Name: "name", CatalogName: "catalog", diff --git a/bundle/deploy/terraform/tfdyn/convert_volume_test.go b/bundle/deploy/terraform/tfdyn/convert_volume_test.go index c897ae69a8..09b69489e3 100644 --- a/bundle/deploy/terraform/tfdyn/convert_volume_test.go +++ b/bundle/deploy/terraform/tfdyn/convert_volume_test.go @@ -14,7 +14,7 @@ import ( ) func TestConvertVolume(t *testing.T) { - var src = resources.Volume{ + src := resources.Volume{ CreateVolumeRequestContent: &catalog.CreateVolumeRequestContent{ CatalogName: "catalog", Comment: "comment", diff --git a/bundle/deploy/terraform/tfdyn/rename_keys.go b/bundle/deploy/terraform/tfdyn/rename_keys.go index 650ffb8900..95904575f8 100644 --- a/bundle/deploy/terraform/tfdyn/rename_keys.go +++ b/bundle/deploy/terraform/tfdyn/rename_keys.go @@ -11,7 +11,7 @@ import ( // definition uses the plural name. This function can convert between the two. func renameKeys(v dyn.Value, rename map[string]string) (dyn.Value, error) { var err error - var acc = dyn.V(map[string]dyn.Value{}) + acc := dyn.V(map[string]dyn.Value{}) nv, err := dyn.Walk(v, func(p dyn.Path, v dyn.Value) (dyn.Value, error) { if len(p) == 0 { @@ -36,7 +36,6 @@ func renameKeys(v dyn.Value, rename map[string]string) (dyn.Value, error) { // Pass through all other values. return v, dyn.ErrSkip }) - if err != nil { return dyn.InvalidValue, err } diff --git a/bundle/internal/schema/main.go b/bundle/internal/schema/main.go index 881ce3496c..cc06f0bbee 100644 --- a/bundle/internal/schema/main.go +++ b/bundle/internal/schema/main.go @@ -48,7 +48,8 @@ func addInterpolationPatterns(typ reflect.Type, s jsonschema.Schema) jsonschema. { Type: jsonschema.StringType, Pattern: interpolationPattern("var"), - }}, + }, + }, } case jsonschema.IntegerType, jsonschema.NumberType, jsonschema.BooleanType: // primitives can have variable values, or references like ${bundle.xyz} @@ -149,7 +150,7 @@ func main() { } // Write the schema descriptions to the output file. - err = os.WriteFile(outputFile, b, 0644) + err = os.WriteFile(outputFile, b, 0o644) if err != nil { log.Fatal(err) } diff --git a/bundle/libraries/expand_glob_references.go b/bundle/libraries/expand_glob_references.go index c71615e0e2..bb19050452 100644 --- a/bundle/libraries/expand_glob_references.go +++ b/bundle/libraries/expand_glob_references.go @@ -11,8 +11,7 @@ import ( "github.com/databricks/cli/libs/dyn" ) -type expand struct { -} +type expand struct{} func matchError(p dyn.Path, l []dyn.Location, message string) diag.Diagnostic { return diag.Diagnostic{ @@ -189,7 +188,6 @@ func (e *expand) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { diags = diags.Extend(d) return dyn.V(output), nil }) - if err != nil { return dyn.InvalidValue, err } @@ -197,7 +195,6 @@ func (e *expand) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { return v, nil }) - if err != nil { diags = diags.Extend(diag.FromErr(err)) } diff --git a/bundle/libraries/filer_volume_test.go b/bundle/libraries/filer_volume_test.go index 870dce97cc..7b2f5c5ba9 100644 --- a/bundle/libraries/filer_volume_test.go +++ b/bundle/libraries/filer_volume_test.go @@ -110,7 +110,8 @@ func TestFilerForVolumeForErrorFromAPI(t *testing.T) { Summary: "unable to determine if volume at /Volumes/main/my_schema/my_volume exists: error from API", Locations: []dyn.Location{{File: "config.yml", Line: 1, Column: 2}}, Paths: []dyn.Path{dyn.MustPathFromString("workspace.artifact_path")}, - }}, diags) + }, + }, diags) } func TestFilerForVolumeWithVolumeNotFound(t *testing.T) { @@ -136,7 +137,8 @@ func TestFilerForVolumeWithVolumeNotFound(t *testing.T) { Summary: "volume /Volumes/main/my_schema/doesnotexist does not exist: some error message", Locations: []dyn.Location{{File: "config.yml", Line: 1, Column: 2}}, Paths: []dyn.Path{dyn.MustPathFromString("workspace.artifact_path")}, - }}, diags) + }, + }, diags) } func TestFilerForVolumeNotFoundAndInBundle(t *testing.T) { diff --git a/bundle/libraries/upload.go b/bundle/libraries/upload.go index 4b6f43701b..a2162fb7b5 100644 --- a/bundle/libraries/upload.go +++ b/bundle/libraries/upload.go @@ -81,7 +81,6 @@ func collectLocalLibraries(b *bundle.Bundle) (map[string][]configLocation, error return v, nil }) }) - if err != nil { return nil, err } @@ -119,7 +118,6 @@ func collectLocalLibraries(b *bundle.Bundle) (map[string][]configLocation, error return v, nil }) }) - if err != nil { return nil, err } @@ -175,7 +173,6 @@ func (u *upload) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { return v, nil }) - if err != nil { diags = diags.Extend(diag.FromErr(err)) } diff --git a/bundle/permissions/filter.go b/bundle/permissions/filter.go index 60264f6eae..6fa8d1374b 100644 --- a/bundle/permissions/filter.go +++ b/bundle/permissions/filter.go @@ -56,7 +56,6 @@ func filter(currentUser string) dyn.WalkValueFunc { } return v, nil - } } diff --git a/bundle/permissions/filter_test.go b/bundle/permissions/filter_test.go index 121ce10dc9..e6e5a3799d 100644 --- a/bundle/permissions/filter_test.go +++ b/bundle/permissions/filter_test.go @@ -90,7 +90,6 @@ func testFixture(userName string) *bundle.Bundle { }, }, } - } func TestFilterCurrentUser(t *testing.T) { diff --git a/bundle/permissions/mutator.go b/bundle/permissions/mutator.go index c4b9708571..cd7cbf40c8 100644 --- a/bundle/permissions/mutator.go +++ b/bundle/permissions/mutator.go @@ -13,42 +13,46 @@ import ( "github.com/databricks/cli/libs/dyn/convert" ) -const CAN_MANAGE = "CAN_MANAGE" -const CAN_VIEW = "CAN_VIEW" -const CAN_RUN = "CAN_RUN" +const ( + CAN_MANAGE = "CAN_MANAGE" + CAN_VIEW = "CAN_VIEW" + CAN_RUN = "CAN_RUN" +) var unsupportedResources = []string{"clusters", "volumes", "schemas", "quality_monitors", "registered_models"} -var allowedLevels = []string{CAN_MANAGE, CAN_VIEW, CAN_RUN} -var levelsMap = map[string](map[string]string){ - "jobs": { - CAN_MANAGE: "CAN_MANAGE", - CAN_VIEW: "CAN_VIEW", - CAN_RUN: "CAN_MANAGE_RUN", - }, - "pipelines": { - CAN_MANAGE: "CAN_MANAGE", - CAN_VIEW: "CAN_VIEW", - CAN_RUN: "CAN_RUN", - }, - "experiments": { - CAN_MANAGE: "CAN_MANAGE", - CAN_VIEW: "CAN_READ", - }, - "models": { - CAN_MANAGE: "CAN_MANAGE", - CAN_VIEW: "CAN_READ", - }, - "model_serving_endpoints": { - CAN_MANAGE: "CAN_MANAGE", - CAN_VIEW: "CAN_VIEW", - CAN_RUN: "CAN_QUERY", - }, - "dashboards": { - CAN_MANAGE: "CAN_MANAGE", - CAN_VIEW: "CAN_READ", - }, -} +var ( + allowedLevels = []string{CAN_MANAGE, CAN_VIEW, CAN_RUN} + levelsMap = map[string](map[string]string){ + "jobs": { + CAN_MANAGE: "CAN_MANAGE", + CAN_VIEW: "CAN_VIEW", + CAN_RUN: "CAN_MANAGE_RUN", + }, + "pipelines": { + CAN_MANAGE: "CAN_MANAGE", + CAN_VIEW: "CAN_VIEW", + CAN_RUN: "CAN_RUN", + }, + "experiments": { + CAN_MANAGE: "CAN_MANAGE", + CAN_VIEW: "CAN_READ", + }, + "models": { + CAN_MANAGE: "CAN_MANAGE", + CAN_VIEW: "CAN_READ", + }, + "model_serving_endpoints": { + CAN_MANAGE: "CAN_MANAGE", + CAN_VIEW: "CAN_VIEW", + CAN_RUN: "CAN_QUERY", + }, + "dashboards": { + CAN_MANAGE: "CAN_MANAGE", + CAN_VIEW: "CAN_READ", + }, + } +) type bundlePermissions struct{} @@ -76,7 +80,6 @@ func (m *bundlePermissions) Apply(ctx context.Context, b *bundle.Bundle) diag.Di v, err = dyn.MapByPattern(v, pattern, func(p dyn.Path, v dyn.Value) (dyn.Value, error) { var permissions []resources.Permission pv, err := dyn.Get(v, "permissions") - // If the permissions field is not found, we set to an empty array if err != nil { pv = dyn.V([]dyn.Value{}) @@ -102,7 +105,6 @@ func (m *bundlePermissions) Apply(ctx context.Context, b *bundle.Bundle) diag.Di return dyn.Set(v, "permissions", pv) }) - if err != nil { return dyn.InvalidValue, err } @@ -110,7 +112,6 @@ func (m *bundlePermissions) Apply(ctx context.Context, b *bundle.Bundle) diag.Di return v, nil }) - if err != nil { return diag.FromErr(err) } diff --git a/bundle/permissions/validate.go b/bundle/permissions/validate.go index f1a18f4309..dee7326cfa 100644 --- a/bundle/permissions/validate.go +++ b/bundle/permissions/validate.go @@ -9,8 +9,7 @@ import ( "github.com/databricks/cli/libs/diag" ) -type validateSharedRootPermissions struct { -} +type validateSharedRootPermissions struct{} func ValidateSharedRootPermissions() bundle.Mutator { return &validateSharedRootPermissions{} diff --git a/bundle/permissions/workspace_path_permissions_test.go b/bundle/permissions/workspace_path_permissions_test.go index 0bb00474c8..eaefad906c 100644 --- a/bundle/permissions/workspace_path_permissions_test.go +++ b/bundle/permissions/workspace_path_permissions_test.go @@ -117,5 +117,4 @@ func TestWorkspacePathPermissionsCompare(t *testing.T) { diags := wp.Compare(tc.perms) require.Equal(t, tc.expected, diags) } - } diff --git a/bundle/permissions/workspace_root.go b/bundle/permissions/workspace_root.go index de4f3a7fe3..4ac0d38a5d 100644 --- a/bundle/permissions/workspace_root.go +++ b/bundle/permissions/workspace_root.go @@ -12,8 +12,7 @@ import ( "golang.org/x/sync/errgroup" ) -type workspaceRootPermissions struct { -} +type workspaceRootPermissions struct{} func ApplyWorkspaceRootPermissions() bundle.Mutator { return &workspaceRootPermissions{} diff --git a/bundle/render/render_text_output.go b/bundle/render/render_text_output.go index bf7c9a53a9..bacb85735a 100644 --- a/bundle/render/render_text_output.go +++ b/bundle/render/render_text_output.go @@ -110,7 +110,7 @@ func renderSummaryHeaderTemplate(out io.Writer, b *bundle.Bundle) error { return renderSummaryHeaderTemplate(out, &bundle.Bundle{}) } - var currentUser = &iam.User{} + currentUser := &iam.User{} if b.Config.Workspace.CurrentUser != nil { if b.Config.Workspace.CurrentUser.User != nil { diff --git a/bundle/render/render_text_output_test.go b/bundle/render/render_text_output_test.go index 2b7f0e8254..506756f708 100644 --- a/bundle/render/render_text_output_test.go +++ b/bundle/render/render_text_output_test.go @@ -376,7 +376,8 @@ func TestRenderDiagnostics(t *testing.T) { Locations: []dyn.Location{{ File: "foo.yaml", Line: 1, - Column: 2}}, + Column: 2, + }}, }, }, expected: "Error: failed to load xxx\n" + diff --git a/bundle/root_test.go b/bundle/root_test.go index 99bf58a00a..0752427109 100644 --- a/bundle/root_test.go +++ b/bundle/root_test.go @@ -71,7 +71,7 @@ func TestRootLookup(t *testing.T) { defer f.Close() // Create directory tree. - err = os.MkdirAll("./a/b/c", 0755) + err = os.MkdirAll("./a/b/c", 0o755) require.NoError(t, err) // It should find the project root from $PWD. diff --git a/bundle/run/job.go b/bundle/run/job.go index 35a6ef4ffc..b43db91842 100644 --- a/bundle/run/job.go +++ b/bundle/run/job.go @@ -289,7 +289,6 @@ func (r *jobRunner) Cancel(ctx context.Context) error { ActiveOnly: true, JobId: jobID, }) - if err != nil { return err } diff --git a/bundle/run/job_args.go b/bundle/run/job_args.go index 85cf96efbd..b1596bbb01 100644 --- a/bundle/run/job_args.go +++ b/bundle/run/job_args.go @@ -131,7 +131,7 @@ func (r *jobRunner) posArgsHandler() argsHandler { } // Handle task parameters otherwise. - var seen = make(map[jobTaskType]bool) + seen := make(map[jobTaskType]bool) for _, t := range job.Tasks { if t.NotebookTask != nil { seen[jobTaskTypeNotebook] = true diff --git a/bundle/run/job_options.go b/bundle/run/job_options.go index c359e79eb9..6a03dff953 100644 --- a/bundle/run/job_options.go +++ b/bundle/run/job_options.go @@ -80,7 +80,7 @@ func (o *JobOptions) validatePipelineParams() (*jobs.PipelineParams, error) { return nil, nil } - var defaultErr = fmt.Errorf("job run argument --pipeline-params only supports `full_refresh=`") + defaultErr := fmt.Errorf("job run argument --pipeline-params only supports `full_refresh=`") v, ok := o.pipelineParams["full_refresh"] if !ok { return nil, defaultErr diff --git a/bundle/run/output/task.go b/bundle/run/output/task.go index 402e4d66ab..1ef78a8c3a 100644 --- a/bundle/run/output/task.go +++ b/bundle/run/output/task.go @@ -7,13 +7,15 @@ import ( "github.com/databricks/databricks-sdk-go/service/jobs" ) -type NotebookOutput jobs.NotebookOutput -type DbtOutput jobs.DbtOutput -type SqlOutput jobs.SqlOutput -type LogsOutput struct { - Logs string `json:"logs"` - LogsTruncated bool `json:"logs_truncated"` -} +type ( + NotebookOutput jobs.NotebookOutput + DbtOutput jobs.DbtOutput + SqlOutput jobs.SqlOutput + LogsOutput struct { + Logs string `json:"logs"` + LogsTruncated bool `json:"logs_truncated"` + } +) func structToString(val any) (string, error) { b, err := json.MarshalIndent(val, "", " ") diff --git a/bundle/run/pipeline.go b/bundle/run/pipeline.go index 6db80a71ba..e8eb90b830 100644 --- a/bundle/run/pipeline.go +++ b/bundle/run/pipeline.go @@ -85,7 +85,7 @@ func (r *pipelineRunner) Name() string { } func (r *pipelineRunner) Run(ctx context.Context, opts *Options) (output.RunOutput, error) { - var pipelineID = r.pipeline.ID + pipelineID := r.pipeline.ID // Include resource key in logger. ctx = log.NewContext(ctx, log.GetLogger(ctx).With("resource", r.Key())) @@ -173,7 +173,6 @@ func (r *pipelineRunner) Cancel(ctx context.Context) error { wait, err := w.Pipelines.Stop(ctx, pipelines.StopRequest{ PipelineId: r.pipeline.ID, }) - if err != nil { return err } diff --git a/bundle/tests/run_as_test.go b/bundle/tests/run_as_test.go index 920577146d..113a6140b0 100644 --- a/bundle/tests/run_as_test.go +++ b/bundle/tests/run_as_test.go @@ -93,7 +93,6 @@ func TestRunAsForAllowedWithTargetOverride(t *testing.T) { assert.Equal(t, ml.Model{Name: "skynet"}, *b.Config.Resources.Models["model_one"].Model) assert.Equal(t, catalog.CreateRegisteredModelRequest{Name: "skynet (in UC)"}, *b.Config.Resources.RegisteredModels["model_two"].CreateRegisteredModelRequest) assert.Equal(t, ml.Experiment{Name: "experiment_one"}, *b.Config.Resources.Experiments["experiment_one"].Experiment) - } func TestRunAsErrorForPipelines(t *testing.T) { @@ -220,7 +219,6 @@ func TestRunAsErrorNeitherUserOrSpSpecified(t *testing.T) { for _, tc := range tcases { t.Run(tc.name, func(t *testing.T) { - bundlePath := fmt.Sprintf("./run_as/not_allowed/neither_sp_nor_user/%s", tc.name) b := load(t, bundlePath) diff --git a/bundle/tests/variables_test.go b/bundle/tests/variables_test.go index 9451c5a042..37d488fad5 100644 --- a/bundle/tests/variables_test.go +++ b/bundle/tests/variables_test.go @@ -151,7 +151,7 @@ func TestVariablesWithTargetLookupOverrides(t *testing.T) { } func TestVariableTargetOverrides(t *testing.T) { - var tcases = []struct { + tcases := []struct { targetName string pipelineName string pipelineContinuous bool diff --git a/bundle/trampoline/python_dbr_warning.go b/bundle/trampoline/python_dbr_warning.go index cf3e9aeb3b..0318df7c9f 100644 --- a/bundle/trampoline/python_dbr_warning.go +++ b/bundle/trampoline/python_dbr_warning.go @@ -14,8 +14,7 @@ import ( "golang.org/x/mod/semver" ) -type wrapperWarning struct { -} +type wrapperWarning struct{} func WrapperWarning() bundle.Mutator { return &wrapperWarning{} @@ -62,7 +61,6 @@ func hasIncompatibleWheelTasks(ctx context.Context, b *bundle.Bundle) bool { if task.ExistingClusterId != "" { version, err := getSparkVersionForCluster(ctx, b.WorkspaceClient(), task.ExistingClusterId) - // If there's error getting spark version for cluster, do not mark it as incompatible if err != nil { log.Warnf(ctx, "unable to get spark version for cluster %s, err: %s", task.ExistingClusterId, err.Error()) diff --git a/bundle/trampoline/python_wheel_test.go b/bundle/trampoline/python_wheel_test.go index 517be35e4c..d75a3eca35 100644 --- a/bundle/trampoline/python_wheel_test.go +++ b/bundle/trampoline/python_wheel_test.go @@ -127,7 +127,8 @@ func TestNoPanicWithNoPythonWheelTasks(t *testing.T) { Tasks: []jobs.Task{ { TaskKey: "notebook_task", - NotebookTask: &jobs.NotebookTask{}}, + NotebookTask: &jobs.NotebookTask{}, + }, }, }, }, diff --git a/bundle/trampoline/trampoline.go b/bundle/trampoline/trampoline.go index 1dc1c4463f..600ce3d9c6 100644 --- a/bundle/trampoline/trampoline.go +++ b/bundle/trampoline/trampoline.go @@ -62,7 +62,7 @@ func (m *trampoline) generateNotebookWrapper(ctx context.Context, b *bundle.Bund notebookName := fmt.Sprintf("notebook_%s_%s", task.JobKey, task.Task.TaskKey) localNotebookPath := filepath.Join(internalDir, notebookName+".py") - err = os.MkdirAll(filepath.Dir(localNotebookPath), 0755) + err = os.MkdirAll(filepath.Dir(localNotebookPath), 0o755) if err != nil { return err } diff --git a/bundle/trampoline/trampoline_test.go b/bundle/trampoline/trampoline_test.go index 4682d8fa03..3c5d185707 100644 --- a/bundle/trampoline/trampoline_test.go +++ b/bundle/trampoline/trampoline_test.go @@ -52,7 +52,8 @@ func TestGenerateTrampoline(t *testing.T) { PythonWheelTask: &jobs.PythonWheelTask{ PackageName: "test", EntryPoint: "run", - }}, + }, + }, } b := &bundle.Bundle{ diff --git a/cmd/api/api.go b/cmd/api/api.go index d33939a521..c3a3eb0b60 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -39,7 +39,7 @@ func makeCommand(method string) *cobra.Command { Args: root.ExactArgs(1), Short: fmt.Sprintf("Perform %s request", method), RunE: func(cmd *cobra.Command, args []string) error { - var path = args[0] + path := args[0] var request any diags := payload.Unmarshal(&request) diff --git a/cmd/auth/describe.go b/cmd/auth/describe.go index c5fa8d26bf..faaf64f8fd 100644 --- a/cmd/auth/describe.go +++ b/cmd/auth/describe.go @@ -59,7 +59,6 @@ func newDescribeCommand() *cobra.Command { isAccount, err := root.MustAnyClient(cmd, args) return root.ConfigUsed(cmd.Context()), isAccount, err }) - if err != nil { return err } diff --git a/cmd/auth/login.go b/cmd/auth/login.go index 79b7954680..c986765994 100644 --- a/cmd/auth/login.go +++ b/cmd/auth/login.go @@ -29,8 +29,10 @@ func promptForProfile(ctx context.Context, defaultValue string) (string, error) return prompt.Run() } -const minimalDbConnectVersion = "13.1" -const defaultTimeout = 1 * time.Hour +const ( + minimalDbConnectVersion = "13.1" + defaultTimeout = 1 * time.Hour +) func newLoginCommand(persistentAuth *auth.PersistentAuth) *cobra.Command { defaultConfigPath := "~/.databrickscfg" diff --git a/cmd/bundle/generate/dashboard.go b/cmd/bundle/generate/dashboard.go index 4a538a2937..f196bbe629 100644 --- a/cmd/bundle/generate/dashboard.go +++ b/cmd/bundle/generate/dashboard.go @@ -158,7 +158,7 @@ func (d *dashboard) saveSerializedDashboard(_ context.Context, b *bundle.Bundle, } // Make sure the output directory exists. - if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil { return err } @@ -183,7 +183,7 @@ func (d *dashboard) saveSerializedDashboard(_ context.Context, b *bundle.Bundle, } fmt.Printf("Writing dashboard to %q\n", rel) - return os.WriteFile(filename, data, 0644) + return os.WriteFile(filename, data, 0o644) } func (d *dashboard) saveConfiguration(ctx context.Context, b *bundle.Bundle, dashboard *dashboards.Dashboard, key string) error { @@ -210,7 +210,7 @@ func (d *dashboard) saveConfiguration(ctx context.Context, b *bundle.Bundle, das } // Make sure the output directory exists. - if err := os.MkdirAll(d.resourceDir, 0755); err != nil { + if err := os.MkdirAll(d.resourceDir, 0o755); err != nil { return err } diff --git a/cmd/bundle/generate/generate_test.go b/cmd/bundle/generate/generate_test.go index 33f1661586..896b7de51c 100644 --- a/cmd/bundle/generate/generate_test.go +++ b/cmd/bundle/generate/generate_test.go @@ -217,7 +217,7 @@ func TestGenerateJobCommand(t *testing.T) { } func touchEmptyFile(t *testing.T, path string) { - err := os.MkdirAll(filepath.Dir(path), 0700) + err := os.MkdirAll(filepath.Dir(path), 0o700) require.NoError(t, err) f, err := os.Create(path) require.NoError(t, err) diff --git a/cmd/bundle/generate/utils.go b/cmd/bundle/generate/utils.go index 65f6924193..e69df9506b 100644 --- a/cmd/bundle/generate/utils.go +++ b/cmd/bundle/generate/utils.go @@ -87,7 +87,7 @@ func (n *downloader) markNotebookForDownload(ctx context.Context, notebookPath * } func (n *downloader) FlushToDisk(ctx context.Context, force bool) error { - err := os.MkdirAll(n.sourceDir, 0755) + err := os.MkdirAll(n.sourceDir, 0o755) if err != nil { return err } diff --git a/cmd/configure/configure_test.go b/cmd/configure/configure_test.go index a127fe57aa..f4a369c0cf 100644 --- a/cmd/configure/configure_test.go +++ b/cmd/configure/configure_test.go @@ -75,7 +75,7 @@ func TestDefaultConfigureNoInteractive(t *testing.T) { } func TestConfigFileFromEnvNoInteractive(t *testing.T) { - //TODO: Replace with similar test code from go SDK, once we start using it directly + // TODO: Replace with similar test code from go SDK, once we start using it directly ctx := context.Background() tempHomeDir := setup(t) defaultCfgPath := filepath.Join(tempHomeDir, ".databrickscfg") diff --git a/cmd/labs/github/github.go b/cmd/labs/github/github.go index 1dd9fae5eb..a67df10224 100644 --- a/cmd/labs/github/github.go +++ b/cmd/labs/github/github.go @@ -12,12 +12,16 @@ import ( "github.com/databricks/cli/libs/log" ) -const gitHubAPI = "https://api.github.com" -const gitHubUserContent = "https://raw.githubusercontent.com" +const ( + gitHubAPI = "https://api.github.com" + gitHubUserContent = "https://raw.githubusercontent.com" +) // Placeholders to use as unique keys in context.Context. -var apiOverride int -var userContentOverride int +var ( + apiOverride int + userContentOverride int +) func WithApiOverride(ctx context.Context, override string) context.Context { return context.WithValue(ctx, &apiOverride, override) diff --git a/cmd/labs/localcache/jsonfile.go b/cmd/labs/localcache/jsonfile.go index 495743a576..6540e4ac27 100644 --- a/cmd/labs/localcache/jsonfile.go +++ b/cmd/labs/localcache/jsonfile.go @@ -14,8 +14,10 @@ import ( "github.com/databricks/cli/libs/log" ) -const userRW = 0o600 -const ownerRWXworldRX = 0o755 +const ( + userRW = 0o600 + ownerRWXworldRX = 0o755 +) func NewLocalCache[T any](dir, name string, validity time.Duration) LocalCache[T] { return LocalCache[T]{ diff --git a/cmd/labs/project/entrypoint.go b/cmd/labs/project/entrypoint.go index 5210c85f95..2bed49145f 100644 --- a/cmd/labs/project/entrypoint.go +++ b/cmd/labs/project/entrypoint.go @@ -30,10 +30,12 @@ type Entrypoint struct { IsBundleAware bool `yaml:"is_bundle_aware,omitempty"` } -var ErrNoLoginConfig = errors.New("no login configuration found") -var ErrMissingClusterID = errors.New("missing a cluster compatible with Databricks Connect") -var ErrMissingWarehouseID = errors.New("missing a SQL warehouse") -var ErrNotInTTY = errors.New("not in an interactive terminal") +var ( + ErrNoLoginConfig = errors.New("no login configuration found") + ErrMissingClusterID = errors.New("missing a cluster compatible with Databricks Connect") + ErrMissingWarehouseID = errors.New("missing a SQL warehouse") + ErrNotInTTY = errors.New("not in an interactive terminal") +) func (e *Entrypoint) NeedsCluster() bool { if e.Installer == nil { diff --git a/cmd/labs/project/installer_test.go b/cmd/labs/project/installer_test.go index c62d546b76..63c984bcb6 100644 --- a/cmd/labs/project/installer_test.go +++ b/cmd/labs/project/installer_test.go @@ -29,8 +29,10 @@ import ( "github.com/stretchr/testify/require" ) -const ownerRWXworldRX = 0o755 -const ownerRW = 0o600 +const ( + ownerRWXworldRX = 0o755 + ownerRW = 0o600 +) func zipballFromFolder(src string) ([]byte, error) { var buf bytes.Buffer diff --git a/cmd/root/auth.go b/cmd/root/auth.go index 107679105b..07ab483990 100644 --- a/cmd/root/auth.go +++ b/cmd/root/auth.go @@ -15,9 +15,11 @@ import ( ) // Placeholders to use as unique keys in context.Context. -var workspaceClient int -var accountClient int -var configUsed int +var ( + workspaceClient int + accountClient int + configUsed int +) type ErrNoWorkspaceProfiles struct { path string diff --git a/cmd/root/auth_test.go b/cmd/root/auth_test.go index 92f028514e..7845987968 100644 --- a/cmd/root/auth_test.go +++ b/cmd/root/auth_test.go @@ -84,7 +84,7 @@ func TestAccountClientOrPrompt(t *testing.T) { account_id = 1112 token = foobar `), - 0755) + 0o755) require.NoError(t, err) t.Setenv("DATABRICKS_CONFIG_FILE", configFile) t.Setenv("PATH", "/nothing") @@ -150,7 +150,7 @@ func TestWorkspaceClientOrPrompt(t *testing.T) { host = https://adb-1112.12.azuredatabricks.net/ token = foobar `), - 0755) + 0o755) require.NoError(t, err) t.Setenv("DATABRICKS_CONFIG_FILE", configFile) t.Setenv("PATH", "/nothing") @@ -204,7 +204,7 @@ func TestMustAccountClientWorksWithDatabricksCfg(t *testing.T) { account_id = 1111 token = foobar `), - 0755) + 0o755) require.NoError(t, err) cmd := New(context.Background()) @@ -251,7 +251,7 @@ func TestMustAnyClientCanCreateWorkspaceClient(t *testing.T) { host = https://adb-1111.11.azuredatabricks.net/ token = foobar `), - 0755) + 0o755) require.NoError(t, err) ctx, tt := cmdio.SetupTest(context.Background()) @@ -280,7 +280,7 @@ func TestMustAnyClientCanCreateAccountClient(t *testing.T) { account_id = 1111 token = foobar `), - 0755) + 0o755) require.NoError(t, err) ctx, tt := cmdio.SetupTest(context.Background()) @@ -304,7 +304,7 @@ func TestMustAnyClientWithEmptyDatabricksCfg(t *testing.T) { err := os.WriteFile( configFile, []byte(""), // empty file - 0755) + 0o755) require.NoError(t, err) ctx, tt := cmdio.SetupTest(context.Background()) diff --git a/cmd/root/bundle_test.go b/cmd/root/bundle_test.go index 72e0bef556..1998b19e61 100644 --- a/cmd/root/bundle_test.go +++ b/cmd/root/bundle_test.go @@ -23,7 +23,7 @@ func setupDatabricksCfg(t *testing.T) { } cfg := []byte("[PROFILE-1]\nhost = https://a.com\ntoken = a\n[PROFILE-2]\nhost = https://a.com\ntoken = b\n") - err := os.WriteFile(filepath.Join(tempHomeDir, ".databrickscfg"), cfg, 0644) + err := os.WriteFile(filepath.Join(tempHomeDir, ".databrickscfg"), cfg, 0o644) assert.NoError(t, err) t.Setenv("DATABRICKS_CONFIG_FILE", "") @@ -48,7 +48,7 @@ func setupWithHost(t *testing.T, cmd *cobra.Command, host string) *bundle.Bundle workspace: host: %q `, host) - err := os.WriteFile(filepath.Join(rootPath, "databricks.yml"), []byte(contents), 0644) + err := os.WriteFile(filepath.Join(rootPath, "databricks.yml"), []byte(contents), 0o644) require.NoError(t, err) b, diags := MustConfigureBundle(cmd) @@ -66,7 +66,7 @@ func setupWithProfile(t *testing.T, cmd *cobra.Command, profile string) *bundle. workspace: profile: %q `, profile) - err := os.WriteFile(filepath.Join(rootPath, "databricks.yml"), []byte(contents), 0644) + err := os.WriteFile(filepath.Join(rootPath, "databricks.yml"), []byte(contents), 0o644) require.NoError(t, err) b, diags := MustConfigureBundle(cmd) diff --git a/cmd/root/root.go b/cmd/root/root.go index e6f66f126f..3b37d01769 100644 --- a/cmd/root/root.go +++ b/cmd/root/root.go @@ -4,11 +4,10 @@ import ( "context" "errors" "fmt" + "log/slog" "os" "strings" - "log/slog" - "github.com/databricks/cli/internal/build" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/dbr" diff --git a/cmd/root/user_agent_upstream.go b/cmd/root/user_agent_upstream.go index f580b42630..a813e8ee74 100644 --- a/cmd/root/user_agent_upstream.go +++ b/cmd/root/user_agent_upstream.go @@ -8,12 +8,16 @@ import ( ) // Environment variables that caller can set to convey what is upstream to this CLI. -const upstreamEnvVar = "DATABRICKS_CLI_UPSTREAM" -const upstreamVersionEnvVar = "DATABRICKS_CLI_UPSTREAM_VERSION" +const ( + upstreamEnvVar = "DATABRICKS_CLI_UPSTREAM" + upstreamVersionEnvVar = "DATABRICKS_CLI_UPSTREAM_VERSION" +) // Keys in the user agent. -const upstreamKey = "upstream" -const upstreamVersionKey = "upstream-version" +const ( + upstreamKey = "upstream" + upstreamVersionKey = "upstream-version" +) func withUpstreamInUserAgent(ctx context.Context) context.Context { value := env.Get(ctx, upstreamEnvVar) diff --git a/cmd/sync/sync.go b/cmd/sync/sync.go index 6d722fb08a..cd2167a198 100644 --- a/cmd/sync/sync.go +++ b/cmd/sync/sync.go @@ -68,7 +68,6 @@ func (f *syncFlags) syncOptionsFromArgs(cmd *cobra.Command, args []string) (*syn localRoot := vfs.MustNew(args[0]) info, err := git.FetchRepositoryInfo(ctx, localRoot.Native(), client) - if err != nil { log.Warnf(ctx, "Failed to read git info: %s", err) } diff --git a/cmd/workspace/workspace/export_dir.go b/cmd/workspace/workspace/export_dir.go index 0046f46ef9..febe4c3e10 100644 --- a/cmd/workspace/workspace/export_dir.go +++ b/cmd/workspace/workspace/export_dir.go @@ -39,7 +39,7 @@ func (opts exportDirOptions) callback(ctx context.Context, workspaceFiler filer. // create directory and return early if d.IsDir() { - return os.MkdirAll(targetPath, 0755) + return os.MkdirAll(targetPath, 0o755) } // Add extension to local file path if the file is a notebook diff --git a/cmd/workspace/workspace/overrides.go b/cmd/workspace/workspace/overrides.go index cfed0a6eec..216e9b5d81 100644 --- a/cmd/workspace/workspace/overrides.go +++ b/cmd/workspace/workspace/overrides.go @@ -52,7 +52,7 @@ func exportOverride(exportCmd *cobra.Command, exportReq *workspace.ExportRequest if err != nil { return err } - return os.WriteFile(filePath, b, 0755) + return os.WriteFile(filePath, b, 0o755) } } @@ -88,7 +88,6 @@ func importOverride(importCmd *cobra.Command, importReq *workspace.Import) { err := originalRunE(cmd, args) return wrapImportAPIErrors(err, importReq) } - } func init() { diff --git a/internal/build/variables.go b/internal/build/variables.go index 197dee9c30..80c4683aba 100644 --- a/internal/build/variables.go +++ b/internal/build/variables.go @@ -1,21 +1,27 @@ package build -var buildProjectName string = "cli" -var buildVersion string = "" +var ( + buildProjectName string = "cli" + buildVersion string = "" +) -var buildBranch string = "undefined" -var buildTag string = "undefined" -var buildShortCommit string = "00000000" -var buildFullCommit string = "0000000000000000000000000000000000000000" -var buildCommitTimestamp string = "0" -var buildSummary string = "v0.0.0" +var ( + buildBranch string = "undefined" + buildTag string = "undefined" + buildShortCommit string = "00000000" + buildFullCommit string = "0000000000000000000000000000000000000000" + buildCommitTimestamp string = "0" + buildSummary string = "v0.0.0" +) -var buildMajor string = "0" -var buildMinor string = "0" -var buildPatch string = "0" -var buildPrerelease string = "" -var buildIsSnapshot string = "false" -var buildTimestamp string = "0" +var ( + buildMajor string = "0" + buildMinor string = "0" + buildPatch string = "0" + buildPrerelease string = "" + buildIsSnapshot string = "false" + buildTimestamp string = "0" +) // This function is used to set the build version for testing purposes. func SetBuildVersion(version string) { diff --git a/internal/bundle/artifacts_test.go b/internal/bundle/artifacts_test.go index 34d101e4f8..f5eec32e06 100644 --- a/internal/bundle/artifacts_test.go +++ b/internal/bundle/artifacts_test.go @@ -23,7 +23,7 @@ import ( ) func touchEmptyFile(t *testing.T, path string) { - err := os.MkdirAll(filepath.Dir(path), 0700) + err := os.MkdirAll(filepath.Dir(path), 0o700) require.NoError(t, err) f, err := os.Create(path) require.NoError(t, err) diff --git a/internal/bundle/clusters_test.go b/internal/bundle/clusters_test.go index a961f3ea8f..b46bec97ec 100644 --- a/internal/bundle/clusters_test.go +++ b/internal/bundle/clusters_test.go @@ -39,7 +39,6 @@ func TestAccDeployBundleWithCluster(t *testing.T) { } else { require.Contains(t, []compute.State{compute.StateTerminated, compute.StateTerminating}, cluster.State) } - }) err = deployBundle(t, ctx, root) diff --git a/internal/bundle/deploy_test.go b/internal/bundle/deploy_test.go index f4c6a440c3..283b05f7ab 100644 --- a/internal/bundle/deploy_test.go +++ b/internal/bundle/deploy_test.go @@ -174,7 +174,6 @@ restore the defined STs and MVs through full refresh. Note that recreation is ne properties such as the 'catalog' or 'storage' are changed: delete pipeline bar`) assert.Contains(t, stdout.String(), "the deployment requires destructive actions, but current console does not support prompting. Please specify --auto-approve if you would like to skip prompts and proceed") - } func TestAccBundlePipelineRecreateWithoutAutoApprove(t *testing.T) { diff --git a/internal/bundle/deployment_state_test.go b/internal/bundle/deployment_state_test.go index 0ab99aeb38..0facd9eb04 100644 --- a/internal/bundle/deployment_state_test.go +++ b/internal/bundle/deployment_state_test.go @@ -32,14 +32,14 @@ func TestAccFilesAreSyncedCorrectlyWhenNoSnapshot(t *testing.T) { t.Setenv("BUNDLE_ROOT", bundleRoot) // Add some test file to the bundle - err = os.WriteFile(filepath.Join(bundleRoot, "test.py"), []byte("print('Hello, World!')"), 0644) + err = os.WriteFile(filepath.Join(bundleRoot, "test.py"), []byte("print('Hello, World!')"), 0o644) require.NoError(t, err) - err = os.WriteFile(filepath.Join(bundleRoot, "test_to_modify.py"), []byte("print('Hello, World!')"), 0644) + err = os.WriteFile(filepath.Join(bundleRoot, "test_to_modify.py"), []byte("print('Hello, World!')"), 0o644) require.NoError(t, err) // Add notebook to the bundle - err = os.WriteFile(filepath.Join(bundleRoot, "notebook.py"), []byte("# Databricks notebook source\nHello, World!"), 0644) + err = os.WriteFile(filepath.Join(bundleRoot, "notebook.py"), []byte("# Databricks notebook source\nHello, World!"), 0o644) require.NoError(t, err) err = deployBundle(t, ctx, bundleRoot) @@ -79,7 +79,7 @@ func TestAccFilesAreSyncedCorrectlyWhenNoSnapshot(t *testing.T) { require.NoError(t, err) // Modify the content of another file - err = os.WriteFile(filepath.Join(bundleRoot, "test_to_modify.py"), []byte("print('Modified!')"), 0644) + err = os.WriteFile(filepath.Join(bundleRoot, "test_to_modify.py"), []byte("print('Modified!')"), 0o644) require.NoError(t, err) err = deployBundle(t, ctx, bundleRoot) diff --git a/internal/bundle/generate_pipeline_test.go b/internal/bundle/generate_pipeline_test.go index 82467952d1..b4a53aaaab 100644 --- a/internal/bundle/generate_pipeline_test.go +++ b/internal/bundle/generate_pipeline_test.go @@ -59,7 +59,7 @@ func TestAccGenerateFromExistingPipelineAndDeploy(t *testing.T) { // Replace pipeline name generatedYaml = strings.ReplaceAll(generatedYaml, name, internal.RandomName("copy-generated-pipeline-")) - err = os.WriteFile(fileName, []byte(generatedYaml), 0644) + err = os.WriteFile(fileName, []byte(generatedYaml), 0o644) require.NoError(t, err) require.Contains(t, generatedYaml, "libraries:") diff --git a/internal/bundle/helpers.go b/internal/bundle/helpers.go index 00a941c952..2d8435168b 100644 --- a/internal/bundle/helpers.go +++ b/internal/bundle/helpers.go @@ -59,7 +59,7 @@ func writeConfigFile(t *testing.T, config map[string]any) (string, error) { filepath := filepath.Join(dir, "config.json") t.Log("Configuration for template: ", string(bytes)) - err = os.WriteFile(filepath, bytes, 0644) + err = os.WriteFile(filepath, bytes, 0o644) return filepath, err } diff --git a/internal/filer_test.go b/internal/filer_test.go index 4e6a156711..62bea03efa 100644 --- a/internal/filer_test.go +++ b/internal/filer_test.go @@ -468,7 +468,6 @@ func TestAccFilerWorkspaceNotebook(t *testing.T) { filerTest{t, f}.assertContents(ctx, tc.nameWithoutExt, tc.expected2) }) } - } func TestAccFilerWorkspaceFilesExtensionsReadDir(t *testing.T) { diff --git a/internal/fs_rm_test.go b/internal/fs_rm_test.go index e86f5713bb..d49813a340 100644 --- a/internal/fs_rm_test.go +++ b/internal/fs_rm_test.go @@ -118,7 +118,6 @@ func TestAccFsRmForNonExistentFile(t *testing.T) { assert.ErrorIs(t, err, fs.ErrNotExist) }) } - } func TestAccFsRmDirRecursively(t *testing.T) { diff --git a/internal/git_fetch_test.go b/internal/git_fetch_test.go index 3da024a3a3..3b234ec147 100644 --- a/internal/git_fetch_test.go +++ b/internal/git_fetch_test.go @@ -14,8 +14,10 @@ import ( "github.com/stretchr/testify/require" ) -const examplesRepoUrl = "https://github.com/databricks/bundle-examples" -const examplesRepoProvider = "gitHub" +const ( + examplesRepoUrl = "https://github.com/databricks/bundle-examples" + examplesRepoProvider = "gitHub" +) func assertFullGitInfo(t *testing.T, expectedRoot string, info git.RepositoryInfo) { assert.Equal(t, "main", info.CurrentBranch) @@ -140,7 +142,7 @@ func TestAccFetchRepositoryInfoDotGit_FromNonGitRepo(t *testing.T) { tempDir := t.TempDir() root := filepath.Join(tempDir, "repo") - require.NoError(t, os.MkdirAll(filepath.Join(root, "a/b/c"), 0700)) + require.NoError(t, os.MkdirAll(filepath.Join(root, "a/b/c"), 0o700)) tests := []string{ filepath.Join(root, "a/b/c"), @@ -163,8 +165,8 @@ func TestAccFetchRepositoryInfoDotGit_FromBrokenGitRepo(t *testing.T) { tempDir := t.TempDir() root := filepath.Join(tempDir, "repo") path := filepath.Join(root, "a/b/c") - require.NoError(t, os.MkdirAll(path, 0700)) - require.NoError(t, os.WriteFile(filepath.Join(root, ".git"), []byte(""), 0000)) + require.NoError(t, os.MkdirAll(path, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(root, ".git"), []byte(""), 0o000)) info, err := git.FetchRepositoryInfo(ctx, path, wt.W) assert.NoError(t, err) diff --git a/internal/helpers.go b/internal/helpers.go index a76ea92b5b..55aeb6275c 100644 --- a/internal/helpers.go +++ b/internal/helpers.go @@ -521,7 +521,6 @@ func TemporaryUcVolume(t *testing.T, w *databricks.WorkspaceClient) string { }) return path.Join("/Volumes", "main", schema.Name, volume.Name) - } func TemporaryRepo(t *testing.T, w *databricks.WorkspaceClient) string { diff --git a/internal/init_test.go b/internal/init_test.go index 08a808f458..36b789d91f 100644 --- a/internal/init_test.go +++ b/internal/init_test.go @@ -58,7 +58,7 @@ func TestAccBundleInitOnMlopsStacks(t *testing.T) { } b, err := json.Marshal(initConfig) require.NoError(t, err) - err = os.WriteFile(filepath.Join(tmpDir1, "config.json"), b, 0644) + err = os.WriteFile(filepath.Join(tmpDir1, "config.json"), b, 0o644) require.NoError(t, err) // Run bundle init @@ -151,11 +151,11 @@ func TestAccBundleInitHelpers(t *testing.T) { tmpDir := t.TempDir() tmpDir2 := t.TempDir() - err := os.Mkdir(filepath.Join(tmpDir, "template"), 0755) + err := os.Mkdir(filepath.Join(tmpDir, "template"), 0o755) require.NoError(t, err) - err = os.WriteFile(filepath.Join(tmpDir, "template", "foo.txt.tmpl"), []byte(test.funcName), 0644) + err = os.WriteFile(filepath.Join(tmpDir, "template", "foo.txt.tmpl"), []byte(test.funcName), 0o644) require.NoError(t, err) - err = os.WriteFile(filepath.Join(tmpDir, "databricks_template_schema.json"), []byte("{}"), 0644) + err = os.WriteFile(filepath.Join(tmpDir, "databricks_template_schema.json"), []byte("{}"), 0o644) require.NoError(t, err) // Run bundle init. diff --git a/internal/testutil/copy.go b/internal/testutil/copy.go index 21faece003..9fd8539925 100644 --- a/internal/testutil/copy.go +++ b/internal/testutil/copy.go @@ -22,7 +22,7 @@ func CopyDirectory(t *testing.T, src, dst string) { require.NoError(t, err) if d.IsDir() { - return os.MkdirAll(filepath.Join(dst, rel), 0755) + return os.MkdirAll(filepath.Join(dst, rel), 0o755) } // Copy the file to the temporary directory diff --git a/internal/testutil/file.go b/internal/testutil/file.go index ba2c3280e2..59c640fbeb 100644 --- a/internal/testutil/file.go +++ b/internal/testutil/file.go @@ -10,17 +10,17 @@ import ( func TouchNotebook(t *testing.T, elems ...string) string { path := filepath.Join(elems...) - err := os.MkdirAll(filepath.Dir(path), 0755) + err := os.MkdirAll(filepath.Dir(path), 0o755) require.NoError(t, err) - err = os.WriteFile(path, []byte("# Databricks notebook source"), 0644) + err = os.WriteFile(path, []byte("# Databricks notebook source"), 0o644) require.NoError(t, err) return path } func Touch(t *testing.T, elems ...string) string { path := filepath.Join(elems...) - err := os.MkdirAll(filepath.Dir(path), 0755) + err := os.MkdirAll(filepath.Dir(path), 0o755) require.NoError(t, err) f, err := os.Create(path) @@ -33,7 +33,7 @@ func Touch(t *testing.T, elems ...string) string { func WriteFile(t *testing.T, content string, elems ...string) string { path := filepath.Join(elems...) - err := os.MkdirAll(filepath.Dir(path), 0755) + err := os.MkdirAll(filepath.Dir(path), 0o755) require.NoError(t, err) f, err := os.Create(path) diff --git a/libs/cmdio/logger.go b/libs/cmdio/logger.go index 5e89b3a34f..279a5006aa 100644 --- a/libs/cmdio/logger.go +++ b/libs/cmdio/logger.go @@ -234,5 +234,4 @@ func (l *Logger) Log(event Event) { // jobs.RunNowAndWait panic("unknown progress logger mode: " + l.Mode.String()) } - } diff --git a/libs/databrickscfg/cfgpickers/clusters.go b/libs/databrickscfg/cfgpickers/clusters.go index cac1b08a7c..6ae7d99c63 100644 --- a/libs/databrickscfg/cfgpickers/clusters.go +++ b/libs/databrickscfg/cfgpickers/clusters.go @@ -18,8 +18,10 @@ import ( var minUcRuntime = canonicalVersion("v12.0") -var dbrVersionRegex = regexp.MustCompile(`^(\d+\.\d+)\.x-.*`) -var dbrSnapshotVersionRegex = regexp.MustCompile(`^(\d+)\.x-snapshot.*`) +var ( + dbrVersionRegex = regexp.MustCompile(`^(\d+\.\d+)\.x-.*`) + dbrSnapshotVersionRegex = regexp.MustCompile(`^(\d+)\.x-snapshot.*`) +) func canonicalVersion(v string) string { return semver.Canonical("v" + strings.TrimPrefix(v, "v")) diff --git a/libs/dyn/convert/from_typed_test.go b/libs/dyn/convert/from_typed_test.go index 0cddff3be0..8a05bfb38a 100644 --- a/libs/dyn/convert/from_typed_test.go +++ b/libs/dyn/convert/from_typed_test.go @@ -325,7 +325,7 @@ func TestFromTypedMapNil(t *testing.T) { } func TestFromTypedMapEmpty(t *testing.T) { - var src = map[string]string{} + src := map[string]string{} ref := dyn.V(map[string]dyn.Value{ "foo": dyn.V("bar"), @@ -338,7 +338,7 @@ func TestFromTypedMapEmpty(t *testing.T) { } func TestFromTypedMapNonEmpty(t *testing.T) { - var src = map[string]string{ + src := map[string]string{ "foo": "foo", "bar": "bar", } @@ -353,7 +353,7 @@ func TestFromTypedMapNonEmpty(t *testing.T) { } func TestFromTypedMapNonEmptyRetainLocation(t *testing.T) { - var src = map[string]string{ + src := map[string]string{ "foo": "bar", "bar": "qux", } @@ -372,7 +372,7 @@ func TestFromTypedMapNonEmptyRetainLocation(t *testing.T) { } func TestFromTypedMapFieldWithZeroValue(t *testing.T) { - var src = map[string]string{ + src := map[string]string{ "foo": "", } @@ -398,7 +398,7 @@ func TestFromTypedSliceNil(t *testing.T) { } func TestFromTypedSliceEmpty(t *testing.T) { - var src = []string{} + src := []string{} ref := dyn.V([]dyn.Value{ dyn.V("bar"), @@ -411,7 +411,7 @@ func TestFromTypedSliceEmpty(t *testing.T) { } func TestFromTypedSliceNonEmpty(t *testing.T) { - var src = []string{ + src := []string{ "foo", "bar", } @@ -426,7 +426,7 @@ func TestFromTypedSliceNonEmpty(t *testing.T) { } func TestFromTypedSliceNonEmptyRetainLocation(t *testing.T) { - var src = []string{ + src := []string{ "foo", "bar", } @@ -446,7 +446,7 @@ func TestFromTypedSliceNonEmptyRetainLocation(t *testing.T) { func TestFromTypedStringEmpty(t *testing.T) { var src string - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.NilValue, nv) @@ -454,7 +454,7 @@ func TestFromTypedStringEmpty(t *testing.T) { func TestFromTypedStringEmptyOverwrite(t *testing.T) { var src string - var ref = dyn.V("old") + ref := dyn.V("old") nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(""), nv) @@ -462,7 +462,7 @@ func TestFromTypedStringEmptyOverwrite(t *testing.T) { func TestFromTypedStringNonEmpty(t *testing.T) { var src string = "new" - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V("new"), nv) @@ -470,14 +470,14 @@ func TestFromTypedStringNonEmpty(t *testing.T) { func TestFromTypedStringNonEmptyOverwrite(t *testing.T) { var src string = "new" - var ref = dyn.V("old") + ref := dyn.V("old") nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V("new"), nv) } func TestFromTypedStringRetainsLocations(t *testing.T) { - var ref = dyn.NewValue("foo", []dyn.Location{{File: "foo"}}) + ref := dyn.NewValue("foo", []dyn.Location{{File: "foo"}}) // case: value has not been changed var src string = "foo" @@ -494,14 +494,14 @@ func TestFromTypedStringRetainsLocations(t *testing.T) { func TestFromTypedStringTypeError(t *testing.T) { var src string = "foo" - var ref = dyn.V(1234) + ref := dyn.V(1234) _, err := FromTyped(src, ref) require.Error(t, err) } func TestFromTypedBoolEmpty(t *testing.T) { var src bool - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.NilValue, nv) @@ -509,7 +509,7 @@ func TestFromTypedBoolEmpty(t *testing.T) { func TestFromTypedBoolEmptyOverwrite(t *testing.T) { var src bool - var ref = dyn.V(true) + ref := dyn.V(true) nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(false), nv) @@ -517,7 +517,7 @@ func TestFromTypedBoolEmptyOverwrite(t *testing.T) { func TestFromTypedBoolNonEmpty(t *testing.T) { var src bool = true - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(true), nv) @@ -525,14 +525,14 @@ func TestFromTypedBoolNonEmpty(t *testing.T) { func TestFromTypedBoolNonEmptyOverwrite(t *testing.T) { var src bool = true - var ref = dyn.V(false) + ref := dyn.V(false) nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(true), nv) } func TestFromTypedBoolRetainsLocations(t *testing.T) { - var ref = dyn.NewValue(true, []dyn.Location{{File: "foo"}}) + ref := dyn.NewValue(true, []dyn.Location{{File: "foo"}}) // case: value has not been changed var src bool = true @@ -549,7 +549,7 @@ func TestFromTypedBoolRetainsLocations(t *testing.T) { func TestFromTypedBoolVariableReference(t *testing.T) { var src bool = true - var ref = dyn.V("${var.foo}") + ref := dyn.V("${var.foo}") nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V("${var.foo}"), nv) @@ -557,14 +557,14 @@ func TestFromTypedBoolVariableReference(t *testing.T) { func TestFromTypedBoolTypeError(t *testing.T) { var src bool = true - var ref = dyn.V("string") + ref := dyn.V("string") _, err := FromTyped(src, ref) require.Error(t, err) } func TestFromTypedIntEmpty(t *testing.T) { var src int - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.NilValue, nv) @@ -572,7 +572,7 @@ func TestFromTypedIntEmpty(t *testing.T) { func TestFromTypedIntEmptyOverwrite(t *testing.T) { var src int - var ref = dyn.V(1234) + ref := dyn.V(1234) nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(int64(0)), nv) @@ -580,7 +580,7 @@ func TestFromTypedIntEmptyOverwrite(t *testing.T) { func TestFromTypedIntNonEmpty(t *testing.T) { var src int = 1234 - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(int64(1234)), nv) @@ -588,14 +588,14 @@ func TestFromTypedIntNonEmpty(t *testing.T) { func TestFromTypedIntNonEmptyOverwrite(t *testing.T) { var src int = 1234 - var ref = dyn.V(1233) + ref := dyn.V(1233) nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(int64(1234)), nv) } func TestFromTypedIntRetainsLocations(t *testing.T) { - var ref = dyn.NewValue(1234, []dyn.Location{{File: "foo"}}) + ref := dyn.NewValue(1234, []dyn.Location{{File: "foo"}}) // case: value has not been changed var src int = 1234 @@ -612,7 +612,7 @@ func TestFromTypedIntRetainsLocations(t *testing.T) { func TestFromTypedIntVariableReference(t *testing.T) { var src int = 1234 - var ref = dyn.V("${var.foo}") + ref := dyn.V("${var.foo}") nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V("${var.foo}"), nv) @@ -620,14 +620,14 @@ func TestFromTypedIntVariableReference(t *testing.T) { func TestFromTypedIntTypeError(t *testing.T) { var src int = 1234 - var ref = dyn.V("string") + ref := dyn.V("string") _, err := FromTyped(src, ref) require.Error(t, err) } func TestFromTypedFloatEmpty(t *testing.T) { var src float64 - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.NilValue, nv) @@ -635,7 +635,7 @@ func TestFromTypedFloatEmpty(t *testing.T) { func TestFromTypedFloatEmptyOverwrite(t *testing.T) { var src float64 - var ref = dyn.V(1.23) + ref := dyn.V(1.23) nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(0.0), nv) @@ -643,7 +643,7 @@ func TestFromTypedFloatEmptyOverwrite(t *testing.T) { func TestFromTypedFloatNonEmpty(t *testing.T) { var src float64 = 1.23 - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(1.23), nv) @@ -651,7 +651,7 @@ func TestFromTypedFloatNonEmpty(t *testing.T) { func TestFromTypedFloatNonEmptyOverwrite(t *testing.T) { var src float64 = 1.23 - var ref = dyn.V(1.24) + ref := dyn.V(1.24) nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V(1.23), nv) @@ -659,7 +659,7 @@ func TestFromTypedFloatNonEmptyOverwrite(t *testing.T) { func TestFromTypedFloatRetainsLocations(t *testing.T) { var src float64 - var ref = dyn.NewValue(1.23, []dyn.Location{{File: "foo"}}) + ref := dyn.NewValue(1.23, []dyn.Location{{File: "foo"}}) // case: value has not been changed src = 1.23 @@ -676,7 +676,7 @@ func TestFromTypedFloatRetainsLocations(t *testing.T) { func TestFromTypedFloatVariableReference(t *testing.T) { var src float64 = 1.23 - var ref = dyn.V("${var.foo}") + ref := dyn.V("${var.foo}") nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.V("${var.foo}"), nv) @@ -684,7 +684,7 @@ func TestFromTypedFloatVariableReference(t *testing.T) { func TestFromTypedFloatTypeError(t *testing.T) { var src float64 = 1.23 - var ref = dyn.V("string") + ref := dyn.V("string") _, err := FromTyped(src, ref) require.Error(t, err) } @@ -727,7 +727,7 @@ func TestFromTypedAny(t *testing.T) { func TestFromTypedAnyNil(t *testing.T) { var src any = nil - var ref = dyn.NilValue + ref := dyn.NilValue nv, err := FromTyped(src, ref) require.NoError(t, err) assert.Equal(t, dyn.NilValue, nv) diff --git a/libs/dyn/convert/struct_info.go b/libs/dyn/convert/struct_info.go index dc3ed4da40..f5fd29cb98 100644 --- a/libs/dyn/convert/struct_info.go +++ b/libs/dyn/convert/struct_info.go @@ -43,7 +43,7 @@ func getStructInfo(typ reflect.Type) structInfo { // buildStructInfo populates a new [structInfo] for the given type. func buildStructInfo(typ reflect.Type) structInfo { - var out = structInfo{ + out := structInfo{ Fields: make(map[string][]int), } @@ -102,7 +102,7 @@ func buildStructInfo(typ reflect.Type) structInfo { } func (s *structInfo) FieldValues(v reflect.Value) map[string]reflect.Value { - var out = make(map[string]reflect.Value) + out := make(map[string]reflect.Value) for k, index := range s.Fields { fv := v diff --git a/libs/dyn/convert/struct_info_test.go b/libs/dyn/convert/struct_info_test.go index 20348ff601..bc10db9daf 100644 --- a/libs/dyn/convert/struct_info_test.go +++ b/libs/dyn/convert/struct_info_test.go @@ -95,7 +95,7 @@ func TestStructInfoFieldValues(t *testing.T) { Bar string `json:"bar"` } - var src = Tmp{ + src := Tmp{ Foo: "foo", Bar: "bar", } @@ -121,7 +121,7 @@ func TestStructInfoFieldValuesAnonymousByValue(t *testing.T) { Foo } - var src = Tmp{ + src := Tmp{ Foo: Foo{ Foo: "foo", Bar: Bar{ diff --git a/libs/dyn/convert/to_typed_test.go b/libs/dyn/convert/to_typed_test.go index 78221c2991..4a56dd4fc0 100644 --- a/libs/dyn/convert/to_typed_test.go +++ b/libs/dyn/convert/to_typed_test.go @@ -44,7 +44,7 @@ func TestToTypedStructOverwrite(t *testing.T) { Qux string `json:"-"` } - var out = Tmp{ + out := Tmp{ Foo: "baz", Bar: "qux", } @@ -66,7 +66,7 @@ func TestToTypedStructClearFields(t *testing.T) { } // Struct value with non-empty fields. - var out = Tmp{ + out := Tmp{ Foo: "baz", Bar: "qux", } @@ -137,7 +137,7 @@ func TestToTypedStructNil(t *testing.T) { Foo string `json:"foo"` } - var out = Tmp{} + out := Tmp{} err := ToTyped(&out, dyn.NilValue) require.NoError(t, err) assert.Equal(t, Tmp{}, out) @@ -148,7 +148,7 @@ func TestToTypedStructNilOverwrite(t *testing.T) { Foo string `json:"foo"` } - var out = Tmp{"bar"} + out := Tmp{"bar"} err := ToTyped(&out, dyn.NilValue) require.NoError(t, err) assert.Equal(t, Tmp{}, out) @@ -173,7 +173,7 @@ func TestToTypedStructWithValueField(t *testing.T) { } func TestToTypedMap(t *testing.T) { - var out = map[string]string{} + out := map[string]string{} v := dyn.V(map[string]dyn.Value{ "key": dyn.V("value"), @@ -186,7 +186,7 @@ func TestToTypedMap(t *testing.T) { } func TestToTypedMapOverwrite(t *testing.T) { - var out = map[string]string{ + out := map[string]string{ "foo": "bar", } @@ -214,14 +214,14 @@ func TestToTypedMapWithPointerElement(t *testing.T) { } func TestToTypedMapNil(t *testing.T) { - var out = map[string]string{} + out := map[string]string{} err := ToTyped(&out, dyn.NilValue) require.NoError(t, err) assert.Nil(t, out) } func TestToTypedMapNilOverwrite(t *testing.T) { - var out = map[string]string{ + out := map[string]string{ "foo": "bar", } err := ToTyped(&out, dyn.NilValue) @@ -245,7 +245,7 @@ func TestToTypedSlice(t *testing.T) { } func TestToTypedSliceOverwrite(t *testing.T) { - var out = []string{"qux"} + out := []string{"qux"} v := dyn.V([]dyn.Value{ dyn.V("foo"), @@ -282,7 +282,7 @@ func TestToTypedSliceNil(t *testing.T) { } func TestToTypedSliceNilOverwrite(t *testing.T) { - var out = []string{"foo"} + out := []string{"foo"} err := ToTyped(&out, dyn.NilValue) require.NoError(t, err) assert.Nil(t, out) diff --git a/libs/dyn/dynassert/assert_test.go b/libs/dyn/dynassert/assert_test.go index 43258bd205..c8c2d69609 100644 --- a/libs/dyn/dynassert/assert_test.go +++ b/libs/dyn/dynassert/assert_test.go @@ -13,7 +13,7 @@ import ( ) func TestThatThisTestPackageIsUsed(t *testing.T) { - var base = ".." + base := ".." var files []string err := fs.WalkDir(os.DirFS(base), ".", func(path string, d fs.DirEntry, err error) error { if d.IsDir() { diff --git a/libs/dyn/merge/merge.go b/libs/dyn/merge/merge.go index a83bbc1527..72d9a7d28a 100644 --- a/libs/dyn/merge/merge.go +++ b/libs/dyn/merge/merge.go @@ -111,6 +111,7 @@ func mergeSequence(a, b dyn.Value) (dyn.Value, error) { // Preserve the location of the first value. Accumulate the locations of the second value. return dyn.NewValue(out, a.Locations()).AppendLocationsFromValue(b), nil } + func mergePrimitive(a, b dyn.Value) (dyn.Value, error) { // Merging primitive values means using the incoming value. return b.AppendLocationsFromValue(a), nil diff --git a/libs/dyn/merge/merge_test.go b/libs/dyn/merge/merge_test.go index 4a4bf9e6c0..bfe7720164 100644 --- a/libs/dyn/merge/merge_test.go +++ b/libs/dyn/merge/merge_test.go @@ -75,7 +75,6 @@ func TestMergeMaps(t *testing.T) { assert.Equal(t, l1, out.Get("foo").Location()) assert.Equal(t, l2, out.Get("qux").Location()) } - } func TestMergeMapsNil(t *testing.T) { diff --git a/libs/dyn/merge/override.go b/libs/dyn/merge/override.go index 7a8667cd69..10a5f1a4e7 100644 --- a/libs/dyn/merge/override.go +++ b/libs/dyn/merge/override.go @@ -46,7 +46,6 @@ func override(basePath dyn.Path, left dyn.Value, right dyn.Value, visitor Overri switch left.Kind() { case dyn.KindMap: merged, err := overrideMapping(basePath, left.MustMap(), right.MustMap(), visitor) - if err != nil { return dyn.InvalidValue, err } @@ -57,7 +56,6 @@ func override(basePath dyn.Path, left dyn.Value, right dyn.Value, visitor Overri // some sequences are keyed, and we can detect which elements are added/removed/updated, // but we don't have this information merged, err := overrideSequence(basePath, left.MustSequence(), right.MustSequence(), visitor) - if err != nil { return dyn.InvalidValue, err } @@ -136,14 +134,12 @@ func overrideMapping(basePath dyn.Path, leftMapping dyn.Mapping, rightMapping dy if leftPair, ok := leftMapping.GetPair(rightPair.Key); ok { path := basePath.Append(dyn.Key(rightPair.Key.MustString())) newValue, err := override(path, leftPair.Value, rightPair.Value, visitor) - if err != nil { return dyn.NewMapping(), err } // key was there before, so keep its location err = out.Set(leftPair.Key, newValue) - if err != nil { return dyn.NewMapping(), err } @@ -151,13 +147,11 @@ func overrideMapping(basePath dyn.Path, leftMapping dyn.Mapping, rightMapping dy path := basePath.Append(dyn.Key(rightPair.Key.MustString())) newValue, err := visitor.VisitInsert(path, rightPair.Value) - if err != nil { return dyn.NewMapping(), err } err = out.Set(rightPair.Key, newValue) - if err != nil { return dyn.NewMapping(), err } @@ -174,7 +168,6 @@ func overrideSequence(basePath dyn.Path, left []dyn.Value, right []dyn.Value, vi for i := 0; i < minLen; i++ { path := basePath.Append(dyn.Index(i)) merged, err := override(path, left[i], right[i], visitor) - if err != nil { return nil, err } @@ -186,7 +179,6 @@ func overrideSequence(basePath dyn.Path, left []dyn.Value, right []dyn.Value, vi for i := minLen; i < len(right); i++ { path := basePath.Append(dyn.Index(i)) newValue, err := visitor.VisitInsert(path, right[i]) - if err != nil { return nil, err } diff --git a/libs/dyn/value_test.go b/libs/dyn/value_test.go index 6a0a27b8dc..86e65858ee 100644 --- a/libs/dyn/value_test.go +++ b/libs/dyn/value_test.go @@ -25,11 +25,11 @@ func TestValueAsMap(t *testing.T) { _, ok := zeroValue.AsMap() assert.False(t, ok) - var intValue = dyn.V(1) + intValue := dyn.V(1) _, ok = intValue.AsMap() assert.False(t, ok) - var mapValue = dyn.NewValue( + mapValue := dyn.NewValue( map[string]dyn.Value{ "key": dyn.NewValue( "value", @@ -46,6 +46,6 @@ func TestValueAsMap(t *testing.T) { func TestValueIsValid(t *testing.T) { var zeroValue dyn.Value assert.False(t, zeroValue.IsValid()) - var intValue = dyn.V(1) + intValue := dyn.V(1) assert.True(t, intValue.IsValid()) } diff --git a/libs/dyn/visit_map_test.go b/libs/dyn/visit_map_test.go index 2cea0913be..d62327d6f5 100644 --- a/libs/dyn/visit_map_test.go +++ b/libs/dyn/visit_map_test.go @@ -71,7 +71,7 @@ func TestMapFuncOnMap(t *testing.T) { }, vbar.AsAny()) // Return error from map function. - var ref = fmt.Errorf("error") + ref := fmt.Errorf("error") verr, err := dyn.MapByPath(vin, dyn.NewPath(dyn.Key("foo")), func(_ dyn.Path, v dyn.Value) (dyn.Value, error) { return dyn.InvalidValue, ref }) @@ -137,7 +137,7 @@ func TestMapFuncOnSequence(t *testing.T) { assert.Equal(t, []any{42, 45}, v1.AsAny()) // Return error from map function. - var ref = fmt.Errorf("error") + ref := fmt.Errorf("error") verr, err := dyn.MapByPath(vin, dyn.NewPath(dyn.Index(0)), func(_ dyn.Path, v dyn.Value) (dyn.Value, error) { return dyn.InvalidValue, ref }) @@ -211,7 +211,7 @@ func TestMapForeachOnMapError(t *testing.T) { }) // Check that an error from the map function propagates. - var ref = fmt.Errorf("error") + ref := fmt.Errorf("error") _, err := dyn.Map(vin, ".", dyn.Foreach(func(_ dyn.Path, v dyn.Value) (dyn.Value, error) { return dyn.InvalidValue, ref })) @@ -255,7 +255,7 @@ func TestMapForeachOnSequenceError(t *testing.T) { }) // Check that an error from the map function propagates. - var ref = fmt.Errorf("error") + ref := fmt.Errorf("error") _, err := dyn.Map(vin, ".", dyn.Foreach(func(_ dyn.Path, v dyn.Value) (dyn.Value, error) { return dyn.InvalidValue, ref })) diff --git a/libs/dyn/yamlloader/loader.go b/libs/dyn/yamlloader/loader.go index 965753ccd4..fe58d6dfb4 100644 --- a/libs/dyn/yamlloader/loader.go +++ b/libs/dyn/yamlloader/loader.go @@ -137,8 +137,8 @@ func (d *loader) loadMapping(node *yaml.Node, loc dyn.Location) (dyn.Value, erro } // Build location for the merge node. - var mloc = d.location(merge) - var merr = errorf(mloc, "map merge requires map or sequence of maps as the value") + mloc := d.location(merge) + merr := errorf(mloc, "map merge requires map or sequence of maps as the value") // Flatten the merge node into a slice of nodes. // It can be either a single node or a sequence of nodes. diff --git a/libs/dyn/yamlloader/yaml_spec_test.go b/libs/dyn/yamlloader/yaml_spec_test.go index 2a5ae817fd..d9997f702c 100644 --- a/libs/dyn/yamlloader/yaml_spec_test.go +++ b/libs/dyn/yamlloader/yaml_spec_test.go @@ -777,7 +777,8 @@ func TestYAMLSpecExample_2_27(t *testing.T) { ), }, []dyn.Location{{File: file, Line: 22, Column: 3}}, - )}, + ), + }, []dyn.Location{{File: file, Line: 18, Column: 1}}, ), "tax": dyn.NewValue( diff --git a/libs/dyn/yamlsaver/saver.go b/libs/dyn/yamlsaver/saver.go index 0fd81d5341..7398e2594c 100644 --- a/libs/dyn/yamlsaver/saver.go +++ b/libs/dyn/yamlsaver/saver.go @@ -27,7 +27,7 @@ func NewSaverWithStyle(nodesWithStyle map[string]yaml.Style) *saver { } func (s *saver) SaveAsYAML(data any, filename string, force bool) error { - err := os.MkdirAll(filepath.Dir(filename), 0755) + err := os.MkdirAll(filepath.Dir(filename), 0o755) if err != nil { return err } diff --git a/libs/dyn/yamlsaver/saver_test.go b/libs/dyn/yamlsaver/saver_test.go index aa481c20b7..89bd5c31eb 100644 --- a/libs/dyn/yamlsaver/saver_test.go +++ b/libs/dyn/yamlsaver/saver_test.go @@ -11,7 +11,7 @@ import ( func TestMarshalNilValue(t *testing.T) { s := NewSaver() - var nilValue = dyn.NilValue + nilValue := dyn.NilValue v, err := s.toYamlNode(nilValue) assert.NoError(t, err) assert.Equal(t, "null", v.Value) @@ -19,7 +19,7 @@ func TestMarshalNilValue(t *testing.T) { func TestMarshalIntValue(t *testing.T) { s := NewSaver() - var intValue = dyn.V(1) + intValue := dyn.V(1) v, err := s.toYamlNode(intValue) assert.NoError(t, err) assert.Equal(t, "1", v.Value) @@ -28,7 +28,7 @@ func TestMarshalIntValue(t *testing.T) { func TestMarshalFloatValue(t *testing.T) { s := NewSaver() - var floatValue = dyn.V(1.0) + floatValue := dyn.V(1.0) v, err := s.toYamlNode(floatValue) assert.NoError(t, err) assert.Equal(t, "1", v.Value) @@ -37,7 +37,7 @@ func TestMarshalFloatValue(t *testing.T) { func TestMarshalBoolValue(t *testing.T) { s := NewSaver() - var boolValue = dyn.V(true) + boolValue := dyn.V(true) v, err := s.toYamlNode(boolValue) assert.NoError(t, err) assert.Equal(t, "true", v.Value) @@ -49,7 +49,7 @@ func TestMarshalTimeValue(t *testing.T) { require.NoError(t, err) s := NewSaver() - var timeValue = dyn.V(tm) + timeValue := dyn.V(tm) v, err := s.toYamlNode(timeValue) assert.NoError(t, err) assert.Equal(t, "1970-01-01", v.Value) @@ -58,7 +58,7 @@ func TestMarshalTimeValue(t *testing.T) { func TestMarshalSequenceValue(t *testing.T) { s := NewSaver() - var sequenceValue = dyn.NewValue( + sequenceValue := dyn.NewValue( []dyn.Value{ dyn.NewValue("value1", []dyn.Location{{File: "file", Line: 1, Column: 2}}), dyn.NewValue("value2", []dyn.Location{{File: "file", Line: 2, Column: 2}}), @@ -74,7 +74,7 @@ func TestMarshalSequenceValue(t *testing.T) { func TestMarshalStringValue(t *testing.T) { s := NewSaver() - var stringValue = dyn.V("value") + stringValue := dyn.V("value") v, err := s.toYamlNode(stringValue) assert.NoError(t, err) assert.Equal(t, "value", v.Value) @@ -83,7 +83,7 @@ func TestMarshalStringValue(t *testing.T) { func TestMarshalMapValue(t *testing.T) { s := NewSaver() - var mapValue = dyn.NewValue( + mapValue := dyn.NewValue( map[string]dyn.Value{ "key3": dyn.NewValue("value3", []dyn.Location{{File: "file", Line: 3, Column: 2}}), "key2": dyn.NewValue("value2", []dyn.Location{{File: "file", Line: 2, Column: 2}}), @@ -107,7 +107,7 @@ func TestMarshalMapValue(t *testing.T) { func TestMarshalNestedValues(t *testing.T) { s := NewSaver() - var mapValue = dyn.NewValue( + mapValue := dyn.NewValue( map[string]dyn.Value{ "key1": dyn.NewValue( map[string]dyn.Value{ @@ -129,14 +129,14 @@ func TestMarshalNestedValues(t *testing.T) { func TestMarshalHexadecimalValueIsQuoted(t *testing.T) { s := NewSaver() - var hexValue = dyn.V(0x123) + hexValue := dyn.V(0x123) v, err := s.toYamlNode(hexValue) assert.NoError(t, err) assert.Equal(t, "291", v.Value) assert.Equal(t, yaml.Style(0), v.Style) assert.Equal(t, yaml.ScalarNode, v.Kind) - var stringValue = dyn.V("0x123") + stringValue := dyn.V("0x123") v, err = s.toYamlNode(stringValue) assert.NoError(t, err) assert.Equal(t, "0x123", v.Value) @@ -146,14 +146,14 @@ func TestMarshalHexadecimalValueIsQuoted(t *testing.T) { func TestMarshalBinaryValueIsQuoted(t *testing.T) { s := NewSaver() - var binaryValue = dyn.V(0b101) + binaryValue := dyn.V(0b101) v, err := s.toYamlNode(binaryValue) assert.NoError(t, err) assert.Equal(t, "5", v.Value) assert.Equal(t, yaml.Style(0), v.Style) assert.Equal(t, yaml.ScalarNode, v.Kind) - var stringValue = dyn.V("0b101") + stringValue := dyn.V("0b101") v, err = s.toYamlNode(stringValue) assert.NoError(t, err) assert.Equal(t, "0b101", v.Value) @@ -163,14 +163,14 @@ func TestMarshalBinaryValueIsQuoted(t *testing.T) { func TestMarshalOctalValueIsQuoted(t *testing.T) { s := NewSaver() - var octalValue = dyn.V(0123) + octalValue := dyn.V(0o123) v, err := s.toYamlNode(octalValue) assert.NoError(t, err) assert.Equal(t, "83", v.Value) assert.Equal(t, yaml.Style(0), v.Style) assert.Equal(t, yaml.ScalarNode, v.Kind) - var stringValue = dyn.V("0123") + stringValue := dyn.V("0123") v, err = s.toYamlNode(stringValue) assert.NoError(t, err) assert.Equal(t, "0123", v.Value) @@ -180,14 +180,14 @@ func TestMarshalOctalValueIsQuoted(t *testing.T) { func TestMarshalFloatValueIsQuoted(t *testing.T) { s := NewSaver() - var floatValue = dyn.V(1.0) + floatValue := dyn.V(1.0) v, err := s.toYamlNode(floatValue) assert.NoError(t, err) assert.Equal(t, "1", v.Value) assert.Equal(t, yaml.Style(0), v.Style) assert.Equal(t, yaml.ScalarNode, v.Kind) - var stringValue = dyn.V("1.0") + stringValue := dyn.V("1.0") v, err = s.toYamlNode(stringValue) assert.NoError(t, err) assert.Equal(t, "1.0", v.Value) @@ -197,14 +197,14 @@ func TestMarshalFloatValueIsQuoted(t *testing.T) { func TestMarshalBoolValueIsQuoted(t *testing.T) { s := NewSaver() - var boolValue = dyn.V(true) + boolValue := dyn.V(true) v, err := s.toYamlNode(boolValue) assert.NoError(t, err) assert.Equal(t, "true", v.Value) assert.Equal(t, yaml.Style(0), v.Style) assert.Equal(t, yaml.ScalarNode, v.Kind) - var stringValue = dyn.V("true") + stringValue := dyn.V("true") v, err = s.toYamlNode(stringValue) assert.NoError(t, err) assert.Equal(t, "true", v.Value) @@ -217,7 +217,7 @@ func TestCustomStylingWithNestedMap(t *testing.T) { "styled": yaml.DoubleQuotedStyle, }) - var styledMap = dyn.NewValue( + styledMap := dyn.NewValue( map[string]dyn.Value{ "key1": dyn.NewValue("value1", []dyn.Location{{File: "file", Line: 1, Column: 2}}), "key2": dyn.NewValue("value2", []dyn.Location{{File: "file", Line: 2, Column: 2}}), @@ -225,7 +225,7 @@ func TestCustomStylingWithNestedMap(t *testing.T) { []dyn.Location{{File: "file", Line: -2, Column: 2}}, ) - var unstyledMap = dyn.NewValue( + unstyledMap := dyn.NewValue( map[string]dyn.Value{ "key3": dyn.NewValue("value3", []dyn.Location{{File: "file", Line: 1, Column: 2}}), "key4": dyn.NewValue("value4", []dyn.Location{{File: "file", Line: 2, Column: 2}}), @@ -233,7 +233,7 @@ func TestCustomStylingWithNestedMap(t *testing.T) { []dyn.Location{{File: "file", Line: -1, Column: 2}}, ) - var val = dyn.NewValue( + val := dyn.NewValue( map[string]dyn.Value{ "styled": styledMap, "unstyled": unstyledMap, diff --git a/libs/exec/exec.go b/libs/exec/exec.go index 8e4633271a..466117e601 100644 --- a/libs/exec/exec.go +++ b/libs/exec/exec.go @@ -10,9 +10,11 @@ import ( type ExecutableType string -const BashExecutable ExecutableType = `bash` -const ShExecutable ExecutableType = `sh` -const CmdExecutable ExecutableType = `cmd` +const ( + BashExecutable ExecutableType = `bash` + ShExecutable ExecutableType = `sh` + CmdExecutable ExecutableType = `cmd` +) var finders map[ExecutableType](func() (shell, error)) = map[ExecutableType](func() (shell, error)){ BashExecutable: newBashShell, diff --git a/libs/filer/filer.go b/libs/filer/filer.go index b5be4c3c2f..83dc560cb0 100644 --- a/libs/filer/filer.go +++ b/libs/filer/filer.go @@ -103,8 +103,7 @@ func (err DirectoryNotEmptyError) Is(other error) bool { return other == fs.ErrInvalid } -type CannotDeleteRootError struct { -} +type CannotDeleteRootError struct{} func (err CannotDeleteRootError) Error() string { return "unable to delete filer root" diff --git a/libs/filer/local_client.go b/libs/filer/local_client.go index 8b25345fc9..385aa69247 100644 --- a/libs/filer/local_client.go +++ b/libs/filer/local_client.go @@ -29,7 +29,7 @@ func (w *LocalClient) Write(ctx context.Context, name string, reader io.Reader, } // Retrieve permission mask from the [WriteMode], if present. - perm := fs.FileMode(0644) + perm := fs.FileMode(0o644) for _, m := range mode { bits := m & writeModePerm if bits != 0 { @@ -47,7 +47,7 @@ func (w *LocalClient) Write(ctx context.Context, name string, reader io.Reader, 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) + err = os.MkdirAll(filepath.Dir(absPath), 0o755) if err != nil { return err } @@ -73,7 +73,6 @@ func (w *LocalClient) Write(ctx context.Context, name string, reader io.Reader, } return err - } func (w *LocalClient) Read(ctx context.Context, name string) (io.ReadCloser, error) { @@ -159,7 +158,7 @@ func (w *LocalClient) Mkdir(ctx context.Context, name string) error { return err } - return os.MkdirAll(dirPath, 0755) + return os.MkdirAll(dirPath, 0o755) } func (w *LocalClient) Stat(ctx context.Context, name string) (fs.FileInfo, error) { diff --git a/libs/filer/slice_test.go b/libs/filer/slice_test.go index 21d7834838..2bdb3f7f5f 100644 --- a/libs/filer/slice_test.go +++ b/libs/filer/slice_test.go @@ -12,11 +12,10 @@ func TestSliceWithout(t *testing.T) { assert.Equal(t, []int{2, 3}, sliceWithout([]int{1, 2, 3}, 1)) assert.Equal(t, []int{1, 3}, sliceWithout([]int{1, 2, 3}, 2)) assert.Equal(t, []int{1, 2}, sliceWithout([]int{1, 2, 3}, 3)) - } func TestSliceWithoutReturnsClone(t *testing.T) { - var ints = []int{1, 2, 3} + ints := []int{1, 2, 3} assert.Equal(t, []int{2, 3}, sliceWithout(ints, 1)) assert.Equal(t, []int{1, 2, 3}, ints) } diff --git a/libs/filer/workspace_files_extensions_client.go b/libs/filer/workspace_files_extensions_client.go index 2a60520911..9ee2722e17 100644 --- a/libs/filer/workspace_files_extensions_client.go +++ b/libs/filer/workspace_files_extensions_client.go @@ -52,7 +52,8 @@ func (w *workspaceFilesExtensionsClient) getNotebookStatByNameWithExt(ctx contex notebook.ExtensionR, notebook.ExtensionScala, notebook.ExtensionSql, - notebook.ExtensionJupyter}, ext) { + notebook.ExtensionJupyter, + }, ext) { return nil, nil } diff --git a/libs/filer/workspace_files_extensions_client_test.go b/libs/filer/workspace_files_extensions_client_test.go index 10c176b315..9e14ce3ea1 100644 --- a/libs/filer/workspace_files_extensions_client_test.go +++ b/libs/filer/workspace_files_extensions_client_test.go @@ -18,7 +18,8 @@ type mockApiClient struct { func (m *mockApiClient) Do(ctx context.Context, method, path string, headers map[string]string, request any, response any, - visitors ...func(*http.Request) error) error { + visitors ...func(*http.Request) error, +) error { args := m.Called(ctx, method, path, headers, request, response, visitors) // Set the http response from a value provided in the mock call. diff --git a/libs/flags/json_flag_test.go b/libs/flags/json_flag_test.go index 564d4f813c..b31324011a 100644 --- a/libs/flags/json_flag_test.go +++ b/libs/flags/json_flag_test.go @@ -57,7 +57,7 @@ func TestJsonFlagFile(t *testing.T) { var request any var fpath string - var payload = []byte(`{"foo": "bar"}`) + payload := []byte(`{"foo": "bar"}`) { f, err := os.Create(path.Join(t.TempDir(), "file")) diff --git a/libs/flags/log_file_flag.go b/libs/flags/log_file_flag.go index 9e60353f00..d2fe51d917 100644 --- a/libs/flags/log_file_flag.go +++ b/libs/flags/log_file_flag.go @@ -48,7 +48,7 @@ func (f *realLogFile) Writer() io.Writer { } func (f *realLogFile) Open() error { - file, err := os.OpenFile(f.s, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + file, err := os.OpenFile(f.s, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) if err != nil { return err } diff --git a/libs/git/config_test.go b/libs/git/config_test.go index 3e6edf765e..73f3431c94 100644 --- a/libs/git/config_test.go +++ b/libs/git/config_test.go @@ -113,7 +113,7 @@ func (h *testCoreExcludesHelper) initialize(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", h.xdgConfigHome) xdgConfigHomeGit := filepath.Join(h.xdgConfigHome, "git") - err := os.MkdirAll(xdgConfigHomeGit, 0755) + err := os.MkdirAll(xdgConfigHomeGit, 0o755) require.NoError(t, err) } @@ -124,7 +124,7 @@ func (h *testCoreExcludesHelper) coreExcludesFile() (string, error) { } func (h *testCoreExcludesHelper) writeConfig(path, contents string) { - err := os.WriteFile(path, []byte(contents), 0644) + err := os.WriteFile(path, []byte(contents), 0o644) require.NoError(h, err) } diff --git a/libs/git/ignore_test.go b/libs/git/ignore_test.go index 057c0cb2e5..9e2713608f 100644 --- a/libs/git/ignore_test.go +++ b/libs/git/ignore_test.go @@ -48,7 +48,7 @@ func TestIgnoreFileTaint(t *testing.T) { assert.False(t, ign) // Now create the .gitignore file. - err = os.WriteFile(gitIgnorePath, []byte("hello"), 0644) + err = os.WriteFile(gitIgnorePath, []byte("hello"), 0o644) require.NoError(t, err) // Verify that the match still doesn't happen (no spontaneous reload). diff --git a/libs/git/info.go b/libs/git/info.go index ce9c70a5c1..46e57be488 100644 --- a/libs/git/info.go +++ b/libs/git/info.go @@ -72,7 +72,6 @@ func fetchRepositoryInfoAPI(ctx context.Context, path string, w *databricks.Work }, &response, ) - if err != nil { return result, err } diff --git a/libs/git/reference.go b/libs/git/reference.go index 2165a9cdad..e1126d4f24 100644 --- a/libs/git/reference.go +++ b/libs/git/reference.go @@ -12,8 +12,10 @@ import ( type ReferenceType string -var ErrNotAReferencePointer = fmt.Errorf("HEAD does not point to another reference") -var ErrNotABranch = fmt.Errorf("HEAD is not a reference to a git branch") +var ( + ErrNotAReferencePointer = fmt.Errorf("HEAD does not point to another reference") + ErrNotABranch = fmt.Errorf("HEAD is not a reference to a git branch") +) const ( // pointer to a secondary reference file path containing sha-1 object ID. @@ -30,8 +32,10 @@ type Reference struct { Content string } -const ReferencePrefix = "ref: " -const HeadPathPrefix = "refs/heads/" +const ( + ReferencePrefix = "ref: " + HeadPathPrefix = "refs/heads/" +) // asserts if a string is a 40 character hexadecimal encoded string func isSHA1(s string) bool { diff --git a/libs/git/view.go b/libs/git/view.go index 2eaba1f8b4..db22dfc5d4 100644 --- a/libs/git/view.go +++ b/libs/git/view.go @@ -113,7 +113,7 @@ func (v *View) EnsureValidGitIgnoreExists() error { // Create .gitignore with .databricks entry gitIgnorePath := filepath.Join(v.repo.Root(), v.targetPath, ".gitignore") - file, err := os.OpenFile(gitIgnorePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) + file, err := os.OpenFile(gitIgnorePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644) if err != nil { return err } diff --git a/libs/git/view_test.go b/libs/git/view_test.go index 06f6f94194..96881fdeee 100644 --- a/libs/git/view_test.go +++ b/libs/git/view_test.go @@ -20,7 +20,7 @@ func copyTestdata(t *testing.T, name string) string { require.NoError(t, err) if d.IsDir() { - err := os.MkdirAll(filepath.Join(tempDir, path), 0755) + err := os.MkdirAll(filepath.Join(tempDir, path), 0o755) require.NoError(t, err) return nil } @@ -46,7 +46,7 @@ func createFakeRepo(t *testing.T, testdataName string) string { absPath := copyTestdata(t, testdataName) // Add .git directory to make it look like a Git repository. - err := os.Mkdir(filepath.Join(absPath, ".git"), 0755) + err := os.Mkdir(filepath.Join(absPath, ".git"), 0o755) require.NoError(t, err) return absPath } diff --git a/libs/jsonschema/validate_type.go b/libs/jsonschema/validate_type.go index 125d6b20b2..9f70498bae 100644 --- a/libs/jsonschema/validate_type.go +++ b/libs/jsonschema/validate_type.go @@ -39,9 +39,11 @@ func validateNumber(v any) error { } func validateInteger(v any) error { - if !slices.Contains([]reflect.Kind{reflect.Int, reflect.Int8, reflect.Int16, + if !slices.Contains([]reflect.Kind{ + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, - reflect.Uint32, reflect.Uint64}, + reflect.Uint32, reflect.Uint64, + }, reflect.TypeOf(v).Kind()) { return fmt.Errorf("expected type integer, but value is %#v", v) } diff --git a/libs/locker/locker.go b/libs/locker/locker.go index b0d65c42ee..4547a4d8fe 100644 --- a/libs/locker/locker.go +++ b/libs/locker/locker.go @@ -140,7 +140,7 @@ func (locker *Locker) Lock(ctx context.Context, isForced bool) error { return err } - var modes = []filer.WriteMode{ + modes := []filer.WriteMode{ // Always create parent directory if it doesn't yet exist. filer.CreateParentDirectories, } diff --git a/libs/log/context.go b/libs/log/context.go index d9e31d1161..5e3e8ccb65 100644 --- a/libs/log/context.go +++ b/libs/log/context.go @@ -2,7 +2,6 @@ package log import ( "context" - "log/slog" ) diff --git a/libs/log/logger.go b/libs/log/logger.go index 794a7e8655..c1d307c899 100644 --- a/libs/log/logger.go +++ b/libs/log/logger.go @@ -3,10 +3,9 @@ package log import ( "context" "fmt" + "log/slog" "runtime" "time" - - "log/slog" ) // GetLogger returns either the logger configured on the context, diff --git a/libs/log/sdk.go b/libs/log/sdk.go index e1b1ffed46..086f80f504 100644 --- a/libs/log/sdk.go +++ b/libs/log/sdk.go @@ -3,11 +3,10 @@ package log import ( "context" "fmt" + "log/slog" "runtime" "time" - "log/slog" - sdk "github.com/databricks/databricks-sdk-go/logger" ) diff --git a/libs/notebook/detect.go b/libs/notebook/detect.go index cd8680bfa4..40c850945f 100644 --- a/libs/notebook/detect.go +++ b/libs/notebook/detect.go @@ -46,7 +46,7 @@ func (f file) close() error { func (f file) readHeader() (string, error) { // Scan header line with some padding. - var buf = make([]byte, headerLength) + buf := make([]byte, headerLength) n, err := f.f.Read([]byte(buf)) if err != nil && err != io.EOF { return "", err diff --git a/libs/notebook/detect_jupyter_test.go b/libs/notebook/detect_jupyter_test.go index 4ff2aeff62..af29a22149 100644 --- a/libs/notebook/detect_jupyter_test.go +++ b/libs/notebook/detect_jupyter_test.go @@ -41,7 +41,7 @@ func TestDetectJupyterInvalidJSON(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "file.ipynb") buf := make([]byte, 128) - err := os.WriteFile(path, buf, 0644) + err := os.WriteFile(path, buf, 0o644) require.NoError(t, err) // Garbage contents means not a notebook. @@ -55,7 +55,7 @@ func TestDetectJupyterNoCells(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "file.ipynb") buf := []byte("{}") - err := os.WriteFile(path, buf, 0644) + err := os.WriteFile(path, buf, 0o644) require.NoError(t, err) // Garbage contents means not a notebook. @@ -69,7 +69,7 @@ func TestDetectJupyterOldVersion(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "file.ipynb") buf := []byte(`{ "cells": [], "metadata": {}, "nbformat": 3 }`) - err := os.WriteFile(path, buf, 0644) + err := os.WriteFile(path, buf, 0o644) require.NoError(t, err) // Garbage contents means not a notebook. diff --git a/libs/notebook/detect_test.go b/libs/notebook/detect_test.go index 786c7e394a..4ede7bf9bd 100644 --- a/libs/notebook/detect_test.go +++ b/libs/notebook/detect_test.go @@ -78,7 +78,7 @@ func TestDetectEmptyFile(t *testing.T) { // Create empty file. dir := t.TempDir() path := filepath.Join(dir, "file.py") - err := os.WriteFile(path, nil, 0644) + err := os.WriteFile(path, nil, 0o644) require.NoError(t, err) // No contents means not a notebook. @@ -92,7 +92,7 @@ func TestDetectFileWithLongHeader(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "file.py") buf := make([]byte, 128*1024) - err := os.WriteFile(path, buf, 0644) + err := os.WriteFile(path, buf, 0o644) require.NoError(t, err) // Garbage contents means not a notebook. diff --git a/libs/python/detect_test.go b/libs/python/detect_test.go index 78c7067f7e..485aa1875c 100644 --- a/libs/python/detect_test.go +++ b/libs/python/detect_test.go @@ -14,13 +14,13 @@ func TestDetectVEnvExecutable(t *testing.T) { dir := t.TempDir() interpreterPath := interpreterPath(dir) - err := os.Mkdir(filepath.Dir(interpreterPath), 0755) + err := os.Mkdir(filepath.Dir(interpreterPath), 0o755) require.NoError(t, err) - err = os.WriteFile(interpreterPath, []byte(""), 0755) + err = os.WriteFile(interpreterPath, []byte(""), 0o755) require.NoError(t, err) - err = os.WriteFile(filepath.Join(dir, "pyvenv.cfg"), []byte(""), 0755) + err = os.WriteFile(filepath.Join(dir, "pyvenv.cfg"), []byte(""), 0o755) require.NoError(t, err) executable, err := DetectVEnvExecutable(dir) diff --git a/libs/python/interpreters.go b/libs/python/interpreters.go index 94f5074dec..6071309a81 100644 --- a/libs/python/interpreters.go +++ b/libs/python/interpreters.go @@ -18,8 +18,10 @@ import ( var ErrNoPythonInterpreters = errors.New("no python3 interpreters found") -const officialMswinPython = "(Python Official) https://python.org/downloads/windows" -const microsoftStorePython = "(Microsoft Store) https://apps.microsoft.com/store/search?publisher=Python%20Software%20Foundation" +const ( + officialMswinPython = "(Python Official) https://python.org/downloads/windows" + microsoftStorePython = "(Microsoft Store) https://apps.microsoft.com/store/search?publisher=Python%20Software%20Foundation" +) const worldWriteable = 0o002 diff --git a/libs/python/interpreters_unix_test.go b/libs/python/interpreters_unix_test.go index b5229c2ace..8471644a13 100644 --- a/libs/python/interpreters_unix_test.go +++ b/libs/python/interpreters_unix_test.go @@ -41,7 +41,7 @@ func TestFilteringInterpreters(t *testing.T) { assert.NoError(t, err) injectedBinary := filepath.Join(rogueBin, "python8.4") - err = os.WriteFile(injectedBinary, raw, 00777) + err = os.WriteFile(injectedBinary, raw, 0o0777) assert.NoError(t, err) t.Setenv("PATH", "testdata/other-binaries-filtered:"+rogueBin) diff --git a/libs/sync/snapshot.go b/libs/sync/snapshot.go index f2920d8c22..a596531b93 100644 --- a/libs/sync/snapshot.go +++ b/libs/sync/snapshot.go @@ -2,6 +2,8 @@ package sync import ( "context" + "crypto/md5" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -10,9 +12,6 @@ import ( "path/filepath" "time" - "crypto/md5" - "encoding/hex" - "github.com/databricks/cli/libs/fileset" "github.com/databricks/cli/libs/log" ) @@ -91,7 +90,7 @@ func GetFileName(host, remotePath string) string { func SnapshotPath(opts *SyncOptions) (string, error) { snapshotDir := filepath.Join(opts.SnapshotBasePath, syncSnapshotDirName) if _, err := os.Stat(snapshotDir); errors.Is(err, fs.ErrNotExist) { - err = os.MkdirAll(snapshotDir, 0755) + err = os.MkdirAll(snapshotDir, 0o755) if err != nil { return "", fmt.Errorf("failed to create config directory: %s", err) } @@ -122,7 +121,7 @@ func newSnapshot(ctx context.Context, opts *SyncOptions) (*Snapshot, error) { } func (s *Snapshot) Save(ctx context.Context) error { - f, err := os.OpenFile(s.snapshotPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) + f, err := os.OpenFile(s.snapshotPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) if err != nil { return fmt.Errorf("failed to create/open persisted sync snapshot file: %s", err) } diff --git a/libs/sync/snapshot_state.go b/libs/sync/snapshot_state.go index 09bb5b63e6..d8660ee6ac 100644 --- a/libs/sync/snapshot_state.go +++ b/libs/sync/snapshot_state.go @@ -51,7 +51,6 @@ func NewSnapshotState(localFiles []fileset.File) (*SnapshotState, error) { // Compute the remote name the file will have in WSFS remoteName := f.Relative isNotebook, err := f.IsNotebook() - if err != nil { // Ignore this file if we're unable to determine the notebook type. // Trying to upload such a file to the workspace would fail anyway. diff --git a/libs/sync/sync.go b/libs/sync/sync.go index 6bd26f2241..dc2c8992ad 100644 --- a/libs/sync/sync.go +++ b/libs/sync/sync.go @@ -117,7 +117,7 @@ func New(ctx context.Context, opts SyncOptions) (*Sync, error) { } var notifier EventNotifier - var outputWaitGroup = &stdsync.WaitGroup{} + outputWaitGroup := &stdsync.WaitGroup{} if opts.OutputHandler != nil { ch := make(chan Event, MaxRequestsInFlight) notifier = &ChannelNotifier{ch} diff --git a/libs/tags/gcp_test.go b/libs/tags/gcp_test.go index 89f4fd8e6b..7c960acbbf 100644 --- a/libs/tags/gcp_test.go +++ b/libs/tags/gcp_test.go @@ -38,7 +38,6 @@ func TestGcpNormalizeKey(t *testing.T) { assert.Equal(t, "test", gcpTag.NormalizeKey("test")) assert.Equal(t, "cafe", gcpTag.NormalizeKey("café 🍎?")) assert.Equal(t, "cafe_foo", gcpTag.NormalizeKey("__café_foo__")) - } func TestGcpNormalizeValue(t *testing.T) { diff --git a/libs/template/file_test.go b/libs/template/file_test.go index bd5f6d632e..ced38c2848 100644 --- a/libs/template/file_test.go +++ b/libs/template/file_test.go @@ -57,7 +57,7 @@ func TestTemplateInMemoryFilePersistToDisk(t *testing.T) { t.SkipNow() } ctx := context.Background() - testInMemoryFile(t, ctx, 0755) + testInMemoryFile(t, ctx, 0o755) } func TestTemplateInMemoryFilePersistToDiskForWindows(t *testing.T) { @@ -67,7 +67,7 @@ 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. ctx := context.Background() - testInMemoryFile(t, ctx, 0666) + testInMemoryFile(t, ctx, 0o666) } func TestTemplateCopyFilePersistToDisk(t *testing.T) { @@ -75,7 +75,7 @@ func TestTemplateCopyFilePersistToDisk(t *testing.T) { t.SkipNow() } ctx := context.Background() - testCopyFile(t, ctx, 0644) + testCopyFile(t, ctx, 0o644) } func TestTemplateCopyFilePersistToDiskForWindows(t *testing.T) { @@ -85,5 +85,5 @@ 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. ctx := context.Background() - testCopyFile(t, ctx, 0666) + testCopyFile(t, ctx, 0o666) } diff --git a/libs/template/helpers.go b/libs/template/helpers.go index 7f7acbd24a..4550e5fa2b 100644 --- a/libs/template/helpers.go +++ b/libs/template/helpers.go @@ -31,9 +31,11 @@ type pair struct { v any } -var cachedUser *iam.User -var cachedIsServicePrincipal *bool -var cachedCatalog *string +var ( + cachedUser *iam.User + cachedIsServicePrincipal *bool + cachedCatalog *string +) // UUID that is stable for the duration of the template execution. This can be used // to populate the `bundle.uuid` field in databricks.yml by template authors. diff --git a/libs/template/helpers_test.go b/libs/template/helpers_test.go index 6c476c658a..a2e8269d28 100644 --- a/libs/template/helpers_test.go +++ b/libs/template/helpers_test.go @@ -158,7 +158,6 @@ func TestWorkspaceHost(t *testing.T) { assert.Len(t, r.files, 1) assert.Contains(t, string(r.files[0].(*inMemoryFile).content), "https://myhost.com") assert.Contains(t, string(r.files[0].(*inMemoryFile).content), "i3.xlarge") - } func TestWorkspaceHostNotConfigured(t *testing.T) { @@ -178,5 +177,4 @@ func TestWorkspaceHostNotConfigured(t *testing.T) { err = r.walk() require.ErrorContains(t, err, "cannot determine target workspace") - } diff --git a/libs/template/materialize.go b/libs/template/materialize.go index ee30444a5e..86a6a8c37a 100644 --- a/libs/template/materialize.go +++ b/libs/template/materialize.go @@ -10,9 +10,11 @@ import ( "github.com/databricks/cli/libs/filer" ) -const libraryDirName = "library" -const templateDirName = "template" -const schemaFileName = "databricks_template_schema.json" +const ( + libraryDirName = "library" + templateDirName = "template" + schemaFileName = "databricks_template_schema.json" +) // This function materializes the input templates as a project, using user defined // configurations. diff --git a/libs/template/renderer_test.go b/libs/template/renderer_test.go index a4b9166dad..d1ce0fa779 100644 --- a/libs/template/renderer_test.go +++ b/libs/template/renderer_test.go @@ -200,8 +200,7 @@ func TestRendererWithAssociatedTemplateInLibrary(t *testing.T) { } func TestRendererExecuteTemplate(t *testing.T) { - templateText := - `"{{.count}} items are made of {{.Material}}". + templateText := `"{{.count}} items are made of {{.Material}}". {{if eq .Animal "sheep" }} Sheep wool is the best! {{else}} @@ -256,7 +255,6 @@ func TestRendererExecuteTemplateWithUnknownProperty(t *testing.T) { } func TestRendererIsSkipped(t *testing.T) { - skipPatterns := []string{"a*", "*yz", "def", "a/b/*"} // skipped paths @@ -319,22 +317,22 @@ func TestRendererPersistToDisk(t *testing.T) { skipPatterns: []string{"a/b/c", "mn*"}, files: []file{ &inMemoryFile{ - perm: 0444, + perm: 0o444, relPath: "a/b/c", content: nil, }, &inMemoryFile{ - perm: 0444, + perm: 0o444, relPath: "mno", content: nil, }, &inMemoryFile{ - perm: 0444, + perm: 0o444, relPath: "a/b/d", content: []byte("123"), }, &inMemoryFile{ - perm: 0444, + perm: 0o444, relPath: "mmnn", content: []byte("456"), }, @@ -350,9 +348,9 @@ func TestRendererPersistToDisk(t *testing.T) { assert.NoFileExists(t, filepath.Join(tmpDir, "mno")) assertFileContent(t, filepath.Join(tmpDir, "a", "b", "d"), "123") - assertFilePermissions(t, filepath.Join(tmpDir, "a", "b", "d"), 0444) + assertFilePermissions(t, filepath.Join(tmpDir, "a", "b", "d"), 0o444) assertFileContent(t, filepath.Join(tmpDir, "mmnn"), "456") - assertFilePermissions(t, filepath.Join(tmpDir, "mmnn"), 0444) + assertFilePermissions(t, filepath.Join(tmpDir, "mmnn"), 0o444) } func TestRendererWalk(t *testing.T) { @@ -520,8 +518,8 @@ func TestRendererReadsPermissionsBits(t *testing.T) { } assert.Len(t, r.files, 2) - assert.Equal(t, getPermissions(r, "script.sh"), fs.FileMode(0755)) - assert.Equal(t, getPermissions(r, "not-a-script"), fs.FileMode(0644)) + assert.Equal(t, getPermissions(r, "script.sh"), fs.FileMode(0o755)) + assert.Equal(t, getPermissions(r, "not-a-script"), fs.FileMode(0o644)) } func TestRendererErrorOnConflictingFile(t *testing.T) { @@ -537,7 +535,7 @@ func TestRendererErrorOnConflictingFile(t *testing.T) { skipPatterns: []string{}, files: []file{ &inMemoryFile{ - perm: 0444, + perm: 0o444, relPath: "a", content: []byte("123"), }, @@ -563,7 +561,7 @@ func TestRendererNoErrorOnConflictingFileIfSkipped(t *testing.T) { skipPatterns: []string{"a"}, files: []file{ &inMemoryFile{ - perm: 0444, + perm: 0o444, relPath: "a", content: []byte("123"), }, diff --git a/libs/textutil/textutil_test.go b/libs/textutil/textutil_test.go index f6834a1ef3..b9268c98b8 100644 --- a/libs/textutil/textutil_test.go +++ b/libs/textutil/textutil_test.go @@ -50,7 +50,8 @@ func TestNormalizeString(t *testing.T) { { input: ".test//test..test", expected: "test_test_test", - }} + }, + } for _, c := range cases { assert.Equal(t, c.expected, NormalizeString(c.input)) From 68d71b6662f496d77b87e48ca80b981e3bf3407d Mon Sep 17 00:00:00 2001 From: Denis Bilenko Date: Thu, 12 Dec 2024 09:51:12 +0100 Subject: [PATCH 2/3] update .golangci.yaml --- .golangci.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.golangci.yaml b/.golangci.yaml index 9af371b717..6df1af7cdf 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -10,6 +10,7 @@ linters: - unused - gofmt - gofumpt + #- goimports linters-settings: govet: enable-all: true @@ -28,5 +29,12 @@ linters-settings: - (*github.com/spf13/cobra.Command).MarkFlagRequired - (*github.com/spf13/pflag.FlagSet).MarkDeprecated - (*github.com/spf13/pflag.FlagSet).MarkHidden + gofumpt: + module-path: github.com/databricks/cli + # Choose whether to use the extra rules. + # Default: false + #extra-rules: true + goimports: + local-prefixes: github.com/databricks/cli issues: exclude-dirs-use-default: false # recommended by docs https://golangci-lint.run/usage/false-positives/ From 9e750b3200b9454208afb440ec6e872ef5450882 Mon Sep 17 00:00:00 2001 From: Denis Bilenko Date: Thu, 12 Dec 2024 09:54:31 +0100 Subject: [PATCH 3/3] Enable extra rules and goimports --- .golangci.yaml | 10 ++++------ bundle/config/mutator/initialize_urls.go | 2 +- bundle/config/mutator/python/python_mutator.go | 8 ++++---- bundle/config/mutator/python/python_mutator_test.go | 4 ++-- bundle/config/mutator/run_as.go | 2 +- bundle/config/mutator/sync_infer_root.go | 2 +- bundle/deferred.go | 2 +- bundle/deploy/state.go | 2 +- bundle/deploy/terraform/init.go | 2 +- bundle/deploy/terraform/init_test.go | 2 +- bundle/deploy/terraform/pkg_test.go | 2 +- bundle/deploy/terraform/tfdyn/convert_dashboard.go | 2 +- bundle/deploy/terraform/unbind.go | 2 +- bundle/permissions/workspace_path_permissions.go | 2 +- bundle/phases/bind.go | 2 +- bundle/run/pipeline.go | 2 +- bundle/run/progress/pipeline.go | 2 +- cmd/bundle/generate/utils.go | 2 +- cmd/configure/configure_test.go | 2 +- internal/bundle/helpers.go | 6 +++--- internal/bundle/python_wheel_test.go | 2 +- internal/bundle/spark_jar_test.go | 2 +- internal/dashboard_assumptions_test.go | 2 +- internal/filer_test.go | 4 ++-- internal/helpers.go | 4 ++-- internal/sync_test.go | 6 +++--- internal/workspace_test.go | 4 ++-- libs/cmdio/io.go | 2 +- libs/cmdio/logger.go | 2 +- libs/dyn/dynassert/assert.go | 10 +++++----- libs/dyn/mapping.go | 2 +- libs/dyn/merge/override.go | 10 +++++----- libs/dyn/merge/override_test.go | 2 +- libs/exec/shell.go | 2 +- libs/filer/workspace_files_extensions_client_test.go | 2 +- libs/folders/folders.go | 2 +- libs/git/repository_test.go | 2 +- libs/locker/locker.go | 2 +- libs/sync/diff.go | 10 +++++----- libs/sync/event.go | 4 ++-- libs/template/renderer_test.go | 4 ++-- 41 files changed, 69 insertions(+), 71 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 6df1af7cdf..9e69e51463 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -10,7 +10,7 @@ linters: - unused - gofmt - gofumpt - #- goimports + - goimports linters-settings: govet: enable-all: true @@ -31,10 +31,8 @@ linters-settings: - (*github.com/spf13/pflag.FlagSet).MarkHidden gofumpt: module-path: github.com/databricks/cli - # Choose whether to use the extra rules. - # Default: false - #extra-rules: true - goimports: - local-prefixes: github.com/databricks/cli + extra-rules: true + #goimports: + # local-prefixes: github.com/databricks/cli issues: exclude-dirs-use-default: false # recommended by docs https://golangci-lint.run/usage/false-positives/ diff --git a/bundle/config/mutator/initialize_urls.go b/bundle/config/mutator/initialize_urls.go index 25bb2c24a9..35ff53d0b6 100644 --- a/bundle/config/mutator/initialize_urls.go +++ b/bundle/config/mutator/initialize_urls.go @@ -38,7 +38,7 @@ func (m *initializeURLs) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagn return nil } -func initializeForWorkspace(b *bundle.Bundle, orgId string, host string) error { +func initializeForWorkspace(b *bundle.Bundle, orgId, host string) error { baseURL, err := url.Parse(host) if err != nil { return err diff --git a/bundle/config/mutator/python/python_mutator.go b/bundle/config/mutator/python/python_mutator.go index 8d95a01dc4..69c1a5dd6b 100644 --- a/bundle/config/mutator/python/python_mutator.go +++ b/bundle/config/mutator/python/python_mutator.go @@ -150,7 +150,7 @@ 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) { +func (m *pythonMutator) runPythonMutator(ctx context.Context, cacheDir, rootPath, 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") @@ -264,7 +264,7 @@ func writeInputFile(inputPath string, input dyn.Value) error { return os.WriteFile(inputPath, rootConfigJson, 0o600) } -func loadOutputFile(rootPath string, outputPath string) (dyn.Value, diag.Diagnostics) { +func loadOutputFile(rootPath, outputPath string) (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)) @@ -379,7 +379,7 @@ func createLoadOverrideVisitor(ctx context.Context) merge.OverrideVisitor { return right, nil }, - VisitUpdate: func(valuePath dyn.Path, left dyn.Value, right dyn.Value) (dyn.Value, error) { + VisitUpdate: func(valuePath dyn.Path, left, right dyn.Value) (dyn.Value, error) { return dyn.InvalidValue, fmt.Errorf("unexpected change at %q (update)", valuePath.String()) }, } @@ -428,7 +428,7 @@ func createInitOverrideVisitor(ctx context.Context) merge.OverrideVisitor { return right, nil }, - VisitUpdate: func(valuePath dyn.Path, left dyn.Value, right dyn.Value) (dyn.Value, error) { + VisitUpdate: func(valuePath dyn.Path, left, right dyn.Value) (dyn.Value, error) { if !valuePath.HasPrefix(jobsPath) { return dyn.InvalidValue, fmt.Errorf("unexpected change at %q (update)", valuePath.String()) } diff --git a/bundle/config/mutator/python/python_mutator_test.go b/bundle/config/mutator/python/python_mutator_test.go index 7276a34510..0c6df98334 100644 --- a/bundle/config/mutator/python/python_mutator_test.go +++ b/bundle/config/mutator/python/python_mutator_test.go @@ -587,7 +587,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, diagnostics string) context.Context { ctx := context.Background() ctx, stub := process.WithStub(ctx) @@ -625,7 +625,7 @@ func withProcessStub(t *testing.T, args []string, output string, diagnostics str return ctx } -func loadYaml(name string, content string) *bundle.Bundle { +func loadYaml(name, content string) *bundle.Bundle { v, diag := config.LoadFromBytes(name, []byte(content)) if diag.Error() != nil { diff --git a/bundle/config/mutator/run_as.go b/bundle/config/mutator/run_as.go index 7a9e00de80..7ffd782c2b 100644 --- a/bundle/config/mutator/run_as.go +++ b/bundle/config/mutator/run_as.go @@ -29,7 +29,7 @@ func (m *setRunAs) Name() string { return "SetRunAs" } -func reportRunAsNotSupported(resourceType string, location dyn.Location, currentUser string, runAsUser string) diag.Diagnostics { +func reportRunAsNotSupported(resourceType string, location dyn.Location, currentUser, runAsUser string) diag.Diagnostics { return diag.Diagnostics{{ Summary: fmt.Sprintf("%s do not support a setting a run_as user that is different from the owner.\n"+ "Current identity: %s. Run as identity: %s.\n"+ diff --git a/bundle/config/mutator/sync_infer_root.go b/bundle/config/mutator/sync_infer_root.go index 512adcdbf6..160fcc908a 100644 --- a/bundle/config/mutator/sync_infer_root.go +++ b/bundle/config/mutator/sync_infer_root.go @@ -35,7 +35,7 @@ func (m *syncInferRoot) Name() string { // If the path does not exist, it returns an empty string. // // See "sync_infer_root_internal_test.go" for examples. -func (m *syncInferRoot) computeRoot(path string, root string) string { +func (m *syncInferRoot) computeRoot(path, root string) string { for !filepath.IsLocal(path) { // Break if we have reached the root of the filesystem. dir := filepath.Dir(root) diff --git a/bundle/deferred.go b/bundle/deferred.go index 56c2bdca21..e7e0c2aeb0 100644 --- a/bundle/deferred.go +++ b/bundle/deferred.go @@ -15,7 +15,7 @@ func (d *DeferredMutator) Name() string { return "deferred" } -func Defer(mutator Mutator, finally Mutator) Mutator { +func Defer(mutator, finally Mutator) Mutator { return &DeferredMutator{ mutator: mutator, finally: finally, diff --git a/bundle/deploy/state.go b/bundle/deploy/state.go index 6dc359087c..a131ab9c3f 100644 --- a/bundle/deploy/state.go +++ b/bundle/deploy/state.go @@ -134,7 +134,7 @@ func (f Filelist) ToSlice(root vfs.Path) []fileset.File { return files } -func isLocalStateStale(local io.Reader, remote io.Reader) bool { +func isLocalStateStale(local, remote io.Reader) bool { localState, err := loadState(local) if err != nil { return true diff --git a/bundle/deploy/terraform/init.go b/bundle/deploy/terraform/init.go index 7d75ee8a81..366f0be8c0 100644 --- a/bundle/deploy/terraform/init.go +++ b/bundle/deploy/terraform/init.go @@ -145,7 +145,7 @@ func inheritEnvVars(ctx context.Context, environ map[string]string) error { // This function is used for env vars set by the Databricks VSCode extension. The variables are intended to be used by the CLI // bundled with the Databricks VSCode extension, but users can use different CLI versions in the VSCode terminals, in which case we want to ignore // the variables if that CLI uses different versions of the dependencies. -func getEnvVarWithMatchingVersion(ctx context.Context, envVarName string, versionVarName string, currentVersion string) (string, error) { +func getEnvVarWithMatchingVersion(ctx context.Context, envVarName, versionVarName, currentVersion string) (string, error) { envValue := env.Get(ctx, envVarName) versionValue := env.Get(ctx, versionVarName) diff --git a/bundle/deploy/terraform/init_test.go b/bundle/deploy/terraform/init_test.go index 72218d5e27..a1ffc5a1ab 100644 --- a/bundle/deploy/terraform/init_test.go +++ b/bundle/deploy/terraform/init_test.go @@ -400,7 +400,7 @@ func TestFindExecPathFromEnvironmentWithCorrectVersionAndBinary(t *testing.T) { require.Equal(t, tmpBinPath, b.Config.Bundle.Terraform.ExecPath) } -func createTempFile(t *testing.T, dest string, name string, executable bool) string { +func createTempFile(t *testing.T, dest, name string, executable bool) string { binPath := filepath.Join(dest, name) f, err := os.Create(binPath) require.NoError(t, err) diff --git a/bundle/deploy/terraform/pkg_test.go b/bundle/deploy/terraform/pkg_test.go index b8dcb9e089..08ec3de758 100644 --- a/bundle/deploy/terraform/pkg_test.go +++ b/bundle/deploy/terraform/pkg_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" ) -func downloadAndChecksum(t *testing.T, url string, expectedChecksum string) { +func downloadAndChecksum(t *testing.T, url, expectedChecksum string) { resp, err := http.Get(url) require.NoError(t, err) defer resp.Body.Close() diff --git a/bundle/deploy/terraform/tfdyn/convert_dashboard.go b/bundle/deploy/terraform/tfdyn/convert_dashboard.go index 3ba7e19a2d..3ec8b489f5 100644 --- a/bundle/deploy/terraform/tfdyn/convert_dashboard.go +++ b/bundle/deploy/terraform/tfdyn/convert_dashboard.go @@ -17,7 +17,7 @@ const ( ) // Marshal "serialized_dashboard" as JSON if it is set in the input but not in the output. -func marshalSerializedDashboard(vin dyn.Value, vout dyn.Value) (dyn.Value, error) { +func marshalSerializedDashboard(vin, vout dyn.Value) (dyn.Value, error) { // Skip if the "serialized_dashboard" field is already set. if v := vout.Get(serializedDashboardFieldName); v.IsValid() { return vout, nil diff --git a/bundle/deploy/terraform/unbind.go b/bundle/deploy/terraform/unbind.go index 49d65615ed..494cb7ef1f 100644 --- a/bundle/deploy/terraform/unbind.go +++ b/bundle/deploy/terraform/unbind.go @@ -37,6 +37,6 @@ func (*unbind) Name() string { return "terraform.Unbind" } -func Unbind(resourceType string, resourceKey string) bundle.Mutator { +func Unbind(resourceType, resourceKey string) bundle.Mutator { return &unbind{resourceType: resourceType, resourceKey: resourceKey} } diff --git a/bundle/permissions/workspace_path_permissions.go b/bundle/permissions/workspace_path_permissions.go index a3b4424c1c..225d2499e0 100644 --- a/bundle/permissions/workspace_path_permissions.go +++ b/bundle/permissions/workspace_path_permissions.go @@ -52,7 +52,7 @@ func (p WorkspacePathPermissions) Compare(perms []resources.Permission) diag.Dia } // containsAll checks if permA contains all permissions in permB. -func containsAll(permA []resources.Permission, permB []resources.Permission) (bool, []resources.Permission) { +func containsAll(permA, permB []resources.Permission) (bool, []resources.Permission) { missing := make([]resources.Permission, 0) for _, a := range permA { found := false diff --git a/bundle/phases/bind.go b/bundle/phases/bind.go index b2e92d6e2b..c62c48aea9 100644 --- a/bundle/phases/bind.go +++ b/bundle/phases/bind.go @@ -25,7 +25,7 @@ func Bind(opts *terraform.BindOptions) bundle.Mutator { ) } -func Unbind(resourceType string, resourceKey string) bundle.Mutator { +func Unbind(resourceType, resourceKey string) bundle.Mutator { return newPhase( "unbind", []bundle.Mutator{ diff --git a/bundle/run/pipeline.go b/bundle/run/pipeline.go index e8eb90b830..a0e7d1e1e2 100644 --- a/bundle/run/pipeline.go +++ b/bundle/run/pipeline.go @@ -41,7 +41,7 @@ func (r *pipelineRunner) logEvent(ctx context.Context, event pipelines.PipelineE } } -func (r *pipelineRunner) logErrorEvent(ctx context.Context, pipelineId string, updateId string) error { +func (r *pipelineRunner) logErrorEvent(ctx context.Context, pipelineId, updateId string) error { w := r.bundle.WorkspaceClient() // Note: For a 100 percent correct and complete solution we should use the diff --git a/bundle/run/progress/pipeline.go b/bundle/run/progress/pipeline.go index 4a256e76c4..b82dd7abd0 100644 --- a/bundle/run/progress/pipeline.go +++ b/bundle/run/progress/pipeline.go @@ -51,7 +51,7 @@ type UpdateTracker struct { w *databricks.WorkspaceClient } -func NewUpdateTracker(pipelineId string, updateId string, w *databricks.WorkspaceClient) *UpdateTracker { +func NewUpdateTracker(pipelineId, updateId string, w *databricks.WorkspaceClient) *UpdateTracker { return &UpdateTracker{ w: w, PipelineId: pipelineId, diff --git a/cmd/bundle/generate/utils.go b/cmd/bundle/generate/utils.go index e69df9506b..8e3764e352 100644 --- a/cmd/bundle/generate/utils.go +++ b/cmd/bundle/generate/utils.go @@ -134,7 +134,7 @@ func (n *downloader) FlushToDisk(ctx context.Context, force bool) error { return errs.Wait() } -func newDownloader(w *databricks.WorkspaceClient, sourceDir string, configDir string) *downloader { +func newDownloader(w *databricks.WorkspaceClient, sourceDir, configDir string) *downloader { return &downloader{ files: make(map[string]string), w: w, diff --git a/cmd/configure/configure_test.go b/cmd/configure/configure_test.go index f4a369c0cf..e2f6c1e29b 100644 --- a/cmd/configure/configure_test.go +++ b/cmd/configure/configure_test.go @@ -31,7 +31,7 @@ func setup(t *testing.T) string { return tempHomeDir } -func getTempFileWithContent(t *testing.T, tempHomeDir string, content string) *os.File { +func getTempFileWithContent(t *testing.T, tempHomeDir, content string) *os.File { inp, err := os.CreateTemp(tempHomeDir, "input") assert.NoError(t, err) _, err = inp.WriteString(content) diff --git a/internal/bundle/helpers.go b/internal/bundle/helpers.go index 2d8435168b..2d2e1098d4 100644 --- a/internal/bundle/helpers.go +++ b/internal/bundle/helpers.go @@ -107,7 +107,7 @@ func deployBundleWithFlags(t *testing.T, ctx context.Context, path string, flags return err } -func runResource(t *testing.T, ctx context.Context, path string, key string) (string, error) { +func runResource(t *testing.T, ctx context.Context, path, key string) (string, error) { ctx = env.Set(ctx, "BUNDLE_ROOT", path) ctx = cmdio.NewContext(ctx, cmdio.Default()) @@ -116,7 +116,7 @@ func runResource(t *testing.T, ctx context.Context, path string, key string) (st return stdout.String(), err } -func runResourceWithParams(t *testing.T, ctx context.Context, path string, key string, params ...string) (string, error) { +func runResourceWithParams(t *testing.T, ctx context.Context, path, key string, params ...string) (string, error) { ctx = env.Set(ctx, "BUNDLE_ROOT", path) ctx = cmdio.NewContext(ctx, cmdio.Default()) @@ -143,7 +143,7 @@ func getBundleRemoteRootPath(w *databricks.WorkspaceClient, t *testing.T, unique return root } -func blackBoxRun(t *testing.T, root string, args ...string) (stdout string, stderr string) { +func blackBoxRun(t *testing.T, root string, args ...string) (stdout, stderr string) { gitRoot, err := folders.FindDirWithLeaf(".", ".git") require.NoError(t, err) diff --git a/internal/bundle/python_wheel_test.go b/internal/bundle/python_wheel_test.go index 44f6200c1b..108676bd80 100644 --- a/internal/bundle/python_wheel_test.go +++ b/internal/bundle/python_wheel_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -func runPythonWheelTest(t *testing.T, templateName string, sparkVersion string, pythonWheelWrapper bool) { +func runPythonWheelTest(t *testing.T, templateName, sparkVersion string, pythonWheelWrapper bool) { ctx, _ := acc.WorkspaceTest(t) nodeTypeId := internal.GetNodeTypeId(env.Get(ctx, "CLOUD_ENV")) diff --git a/internal/bundle/spark_jar_test.go b/internal/bundle/spark_jar_test.go index cffcbb755a..a7a58a3663 100644 --- a/internal/bundle/spark_jar_test.go +++ b/internal/bundle/spark_jar_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" ) -func runSparkJarTestCommon(t *testing.T, ctx context.Context, sparkVersion string, artifactPath string) { +func runSparkJarTestCommon(t *testing.T, ctx context.Context, sparkVersion, artifactPath string) { cloudEnv := internal.GetEnvOrSkipTest(t, "CLOUD_ENV") nodeTypeId := internal.GetNodeTypeId(cloudEnv) tmpDir := t.TempDir() diff --git a/internal/dashboard_assumptions_test.go b/internal/dashboard_assumptions_test.go index 64294873d1..6d67937a8b 100644 --- a/internal/dashboard_assumptions_test.go +++ b/internal/dashboard_assumptions_test.go @@ -98,7 +98,7 @@ func TestAccDashboardAssumptions_WorkspaceImport(t *testing.T) { assert.Fail(t, "unexpected insert operation") return right, nil }, - VisitUpdate: func(basePath dyn.Path, left dyn.Value, right dyn.Value) (dyn.Value, error) { + VisitUpdate: func(basePath dyn.Path, left, right dyn.Value) (dyn.Value, error) { updatedFieldPaths = append(updatedFieldPaths, basePath.String()) return right, nil }, diff --git a/internal/filer_test.go b/internal/filer_test.go index 62bea03efa..5ba303dc73 100644 --- a/internal/filer_test.go +++ b/internal/filer_test.go @@ -22,7 +22,7 @@ type filerTest struct { filer.Filer } -func (f filerTest) assertContents(ctx context.Context, name string, contents string) { +func (f filerTest) assertContents(ctx context.Context, name, contents string) { reader, err := f.Read(ctx, name) if !assert.NoError(f, err) { return @@ -39,7 +39,7 @@ func (f filerTest) assertContents(ctx context.Context, name string, contents str assert.Equal(f, contents, body.String()) } -func (f filerTest) assertContentsJupyter(ctx context.Context, name string, language string) { +func (f filerTest) assertContentsJupyter(ctx context.Context, name, language string) { reader, err := f.Read(ctx, name) if !assert.NoError(f, err) { return diff --git a/internal/helpers.go b/internal/helpers.go index 55aeb6275c..060736dc6f 100644 --- a/internal/helpers.go +++ b/internal/helpers.go @@ -279,7 +279,7 @@ func (t *cobraTestRunner) Run() (bytes.Buffer, bytes.Buffer, error) { } // Like [require.Eventually] but errors if the underlying command has failed. -func (c *cobraTestRunner) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...any) { +func (c *cobraTestRunner) Eventually(condition func() bool, waitFor, tick time.Duration, msgAndArgs ...any) { ch := make(chan bool, 1) timer := time.NewTimer(waitFor) @@ -362,7 +362,7 @@ func readFile(t *testing.T, name string) string { return string(b) } -func writeFile(t *testing.T, name string, body string) string { +func writeFile(t *testing.T, name, body string) string { f, err := os.Create(filepath.Join(t.TempDir(), name)) require.NoError(t, err) _, err = f.WriteString(body) diff --git a/internal/sync_test.go b/internal/sync_test.go index 6f8b1827be..2518777fbd 100644 --- a/internal/sync_test.go +++ b/internal/sync_test.go @@ -145,7 +145,7 @@ func (a *syncTest) remoteDirContent(ctx context.Context, relativeDir string, exp } } -func (a *syncTest) remoteFileContent(ctx context.Context, relativePath string, expectedContent string) { +func (a *syncTest) remoteFileContent(ctx context.Context, relativePath, expectedContent string) { filePath := path.Join(a.remoteRoot, relativePath) // Remove leading "/" so we can use it in the URL. @@ -181,7 +181,7 @@ func (a *syncTest) touchFile(ctx context.Context, path string) { require.NoError(a.t, err) } -func (a *syncTest) objectType(ctx context.Context, relativePath string, expected string) { +func (a *syncTest) objectType(ctx context.Context, relativePath, expected string) { path := path.Join(a.remoteRoot, relativePath) a.c.Eventually(func() bool { @@ -193,7 +193,7 @@ func (a *syncTest) objectType(ctx context.Context, relativePath string, expected }, 30*time.Second, 5*time.Second) } -func (a *syncTest) language(ctx context.Context, relativePath string, expected string) { +func (a *syncTest) language(ctx context.Context, relativePath, expected string) { path := path.Join(a.remoteRoot, relativePath) a.c.Eventually(func() bool { diff --git a/internal/workspace_test.go b/internal/workspace_test.go index 4453616545..575c0cadca 100644 --- a/internal/workspace_test.go +++ b/internal/workspace_test.go @@ -71,14 +71,14 @@ func setupWorkspaceImportExportTest(t *testing.T) (context.Context, filer.Filer, return ctx, f, tmpdir } -func assertLocalFileContents(t *testing.T, path string, content string) { +func assertLocalFileContents(t *testing.T, path, content string) { require.FileExists(t, path) b, err := os.ReadFile(path) require.NoError(t, err) assert.Contains(t, string(b), content) } -func assertFilerFileContents(t *testing.T, ctx context.Context, f filer.Filer, path string, content string) { +func assertFilerFileContents(t *testing.T, ctx context.Context, f filer.Filer, path, content string) { r, err := f.Read(ctx, path) require.NoError(t, err) b, err := io.ReadAll(r) diff --git a/libs/cmdio/io.go b/libs/cmdio/io.go index 75c0c4b875..f7987c2335 100644 --- a/libs/cmdio/io.go +++ b/libs/cmdio/io.go @@ -31,7 +31,7 @@ type cmdIO struct { err io.Writer } -func NewIO(outputFormat flags.Output, in io.Reader, out io.Writer, err io.Writer, headerTemplate, template string) *cmdIO { +func NewIO(outputFormat flags.Output, in io.Reader, out, err io.Writer, headerTemplate, template string) *cmdIO { // The check below is similar to color.NoColor but uses the specified err writer. dumb := os.Getenv("NO_COLOR") != "" || os.Getenv("TERM") == "dumb" if f, ok := err.(*os.File); ok && !dumb { diff --git a/libs/cmdio/logger.go b/libs/cmdio/logger.go index 279a5006aa..7bc95e9a51 100644 --- a/libs/cmdio/logger.go +++ b/libs/cmdio/logger.go @@ -151,7 +151,7 @@ func (l *Logger) AskSelect(question string, choices []string) (string, error) { return ans, nil } -func (l *Logger) Ask(question string, defaultVal string) (string, error) { +func (l *Logger) Ask(question, defaultVal string) (string, error) { if l.Mode == flags.ModeJson { return "", fmt.Errorf("question prompts are not supported in json mode") } diff --git a/libs/dyn/dynassert/assert.go b/libs/dyn/dynassert/assert.go index ebdba1214a..616a588ec4 100644 --- a/libs/dyn/dynassert/assert.go +++ b/libs/dyn/dynassert/assert.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/assert" ) -func Equal(t assert.TestingT, expected any, actual any, msgAndArgs ...any) bool { +func Equal(t assert.TestingT, expected, actual any, msgAndArgs ...any) bool { ev, eok := expected.(dyn.Value) av, aok := actual.(dyn.Value) if eok && aok && ev.IsValid() && av.IsValid() { @@ -36,7 +36,7 @@ func EqualValues(t assert.TestingT, expected, actual any, msgAndArgs ...any) boo return assert.EqualValues(t, expected, actual, msgAndArgs...) } -func NotEqual(t assert.TestingT, expected any, actual any, msgAndArgs ...any) bool { +func NotEqual(t assert.TestingT, expected, actual any, msgAndArgs ...any) bool { return assert.NotEqual(t, expected, actual, msgAndArgs...) } @@ -84,11 +84,11 @@ func False(t assert.TestingT, value bool, msgAndArgs ...any) bool { return assert.False(t, value, msgAndArgs...) } -func Contains(t assert.TestingT, list any, element any, msgAndArgs ...any) bool { +func Contains(t assert.TestingT, list, element any, msgAndArgs ...any) bool { return assert.Contains(t, list, element, msgAndArgs...) } -func NotContains(t assert.TestingT, list any, element any, msgAndArgs ...any) bool { +func NotContains(t assert.TestingT, list, element any, msgAndArgs ...any) bool { return assert.NotContains(t, list, element, msgAndArgs...) } @@ -112,6 +112,6 @@ func NotPanics(t assert.TestingT, f func(), msgAndArgs ...any) bool { return assert.NotPanics(t, f, msgAndArgs...) } -func JSONEq(t assert.TestingT, expected string, actual string, msgAndArgs ...any) bool { +func JSONEq(t assert.TestingT, expected, actual string, msgAndArgs ...any) bool { return assert.JSONEq(t, expected, actual, msgAndArgs...) } diff --git a/libs/dyn/mapping.go b/libs/dyn/mapping.go index f5dbd18e6c..3c7c4e96ef 100644 --- a/libs/dyn/mapping.go +++ b/libs/dyn/mapping.go @@ -94,7 +94,7 @@ func (m *Mapping) GetByString(skey string) (Value, bool) { // If the key already exists, the value is updated. // If the key does not exist, a new key-value pair is added. // The key must be a string, otherwise an error is returned. -func (m *Mapping) Set(key Value, value Value) error { +func (m *Mapping) Set(key, value Value) error { skey, ok := key.AsString() if !ok { return fmt.Errorf("key must be a string, got %s", key.Kind()) diff --git a/libs/dyn/merge/override.go b/libs/dyn/merge/override.go index 10a5f1a4e7..ca62c73050 100644 --- a/libs/dyn/merge/override.go +++ b/libs/dyn/merge/override.go @@ -23,7 +23,7 @@ import ( type OverrideVisitor struct { VisitDelete func(valuePath dyn.Path, left dyn.Value) error VisitInsert func(valuePath dyn.Path, right dyn.Value) (dyn.Value, error) - VisitUpdate func(valuePath dyn.Path, left dyn.Value, right dyn.Value) (dyn.Value, error) + VisitUpdate func(valuePath dyn.Path, left, right dyn.Value) (dyn.Value, error) } var ErrOverrideUndoDelete = errors.New("undo delete operation") @@ -31,11 +31,11 @@ var ErrOverrideUndoDelete = errors.New("undo delete operation") // Override overrides value 'leftRoot' with 'rightRoot', keeping 'location' if values // haven't changed. Preserving 'location' is important to preserve the original source of the value // for error reporting. -func Override(leftRoot dyn.Value, rightRoot dyn.Value, visitor OverrideVisitor) (dyn.Value, error) { +func Override(leftRoot, rightRoot dyn.Value, visitor OverrideVisitor) (dyn.Value, error) { return override(dyn.EmptyPath, leftRoot, rightRoot, visitor) } -func override(basePath dyn.Path, left dyn.Value, right dyn.Value, visitor OverrideVisitor) (dyn.Value, error) { +func override(basePath dyn.Path, left, right dyn.Value, visitor OverrideVisitor) (dyn.Value, error) { if left.Kind() != right.Kind() { return visitor.VisitUpdate(basePath, left, right) } @@ -105,7 +105,7 @@ func override(basePath dyn.Path, left dyn.Value, right dyn.Value, visitor Overri return dyn.InvalidValue, fmt.Errorf("unexpected kind %s at %s", left.Kind(), basePath.String()) } -func overrideMapping(basePath dyn.Path, leftMapping dyn.Mapping, rightMapping dyn.Mapping, visitor OverrideVisitor) (dyn.Mapping, error) { +func overrideMapping(basePath dyn.Path, leftMapping, rightMapping dyn.Mapping, visitor OverrideVisitor) (dyn.Mapping, error) { out := dyn.NewMapping() for _, leftPair := range leftMapping.Pairs() { @@ -161,7 +161,7 @@ func overrideMapping(basePath dyn.Path, leftMapping dyn.Mapping, rightMapping dy return out, nil } -func overrideSequence(basePath dyn.Path, left []dyn.Value, right []dyn.Value, visitor OverrideVisitor) ([]dyn.Value, error) { +func overrideSequence(basePath dyn.Path, left, right []dyn.Value, visitor OverrideVisitor) ([]dyn.Value, error) { minLen := min(len(left), len(right)) var values []dyn.Value diff --git a/libs/dyn/merge/override_test.go b/libs/dyn/merge/override_test.go index 4af9377749..ea161d27c5 100644 --- a/libs/dyn/merge/override_test.go +++ b/libs/dyn/merge/override_test.go @@ -484,7 +484,7 @@ func createVisitor(opts visitorOpts) (*visitorState, OverrideVisitor) { s := visitorState{} return &s, OverrideVisitor{ - VisitUpdate: func(valuePath dyn.Path, left dyn.Value, right dyn.Value) (dyn.Value, error) { + VisitUpdate: func(valuePath dyn.Path, left, right dyn.Value) (dyn.Value, error) { s.updated = append(s.updated, valuePath.String()) if opts.error != nil { diff --git a/libs/exec/shell.go b/libs/exec/shell.go index f5d1768967..ee29eac8a0 100644 --- a/libs/exec/shell.go +++ b/libs/exec/shell.go @@ -36,7 +36,7 @@ func findShell() (shell, error) { return nil, errors.New("no shell found") } -func createTempScript(command string, extension string) (string, error) { +func createTempScript(command, extension string) (string, error) { file, err := os.CreateTemp(os.TempDir(), "cli-exec*"+extension) if err != nil { return "", err diff --git a/libs/filer/workspace_files_extensions_client_test.go b/libs/filer/workspace_files_extensions_client_test.go index 9e14ce3ea1..10a2bebf0a 100644 --- a/libs/filer/workspace_files_extensions_client_test.go +++ b/libs/filer/workspace_files_extensions_client_test.go @@ -17,7 +17,7 @@ type mockApiClient struct { } func (m *mockApiClient) Do(ctx context.Context, method, path string, - headers map[string]string, request any, response any, + headers map[string]string, request, response any, visitors ...func(*http.Request) error, ) error { args := m.Called(ctx, method, path, headers, request, response, visitors) diff --git a/libs/folders/folders.go b/libs/folders/folders.go index 81bf7ed01d..bbabc588ce 100644 --- a/libs/folders/folders.go +++ b/libs/folders/folders.go @@ -8,7 +8,7 @@ import ( // FindDirWithLeaf returns the first directory that holds `leaf`, // traversing up to the root of the filesystem, starting at `dir`. -func FindDirWithLeaf(dir string, leaf string) (string, error) { +func FindDirWithLeaf(dir, leaf string) (string, error) { dir, err := filepath.Abs(dir) if err != nil { return "", err diff --git a/libs/git/repository_test.go b/libs/git/repository_test.go index 474880e273..857df65a91 100644 --- a/libs/git/repository_test.go +++ b/libs/git/repository_test.go @@ -63,7 +63,7 @@ func (testRepo *testRepository) checkoutCommit(commitId string) { require.NoError(testRepo.t, err) } -func (testRepo *testRepository) addBranch(name string, latestCommit string) { +func (testRepo *testRepository) addBranch(name, latestCommit string) { // create dir for branch head reference branchDir := filepath.Join(testRepo.r.Root(), ".git", "refs", "heads") err := os.MkdirAll(branchDir, os.ModePerm) diff --git a/libs/locker/locker.go b/libs/locker/locker.go index 4547a4d8fe..eb59c9f748 100644 --- a/libs/locker/locker.go +++ b/libs/locker/locker.go @@ -196,7 +196,7 @@ func (locker *Locker) Unlock(ctx context.Context, opts ...UnlockOption) error { return nil } -func CreateLocker(user string, targetDir string, w *databricks.WorkspaceClient) (*Locker, error) { +func CreateLocker(user, targetDir string, w *databricks.WorkspaceClient) (*Locker, error) { filer, err := filer.NewWorkspaceFilesClient(w, targetDir) if err != nil { return nil, err diff --git a/libs/sync/diff.go b/libs/sync/diff.go index e91f7277ee..d81a3ae65e 100644 --- a/libs/sync/diff.go +++ b/libs/sync/diff.go @@ -20,7 +20,7 @@ func (d diff) IsEmpty() bool { // Compute operations required to make files in WSFS reflect current local files. // Takes into account changes since the last sync iteration. -func computeDiff(after *SnapshotState, before *SnapshotState) diff { +func computeDiff(after, before *SnapshotState) diff { d := &diff{ delete: make([]string, 0), rmdir: make([]string, 0), @@ -35,7 +35,7 @@ func computeDiff(after *SnapshotState, before *SnapshotState) diff { } // Add operators for tracked files that no longer exist. -func (d *diff) addRemovedFiles(after *SnapshotState, before *SnapshotState) { +func (d *diff) addRemovedFiles(after, before *SnapshotState) { for localName, remoteName := range before.LocalToRemoteNames { if _, ok := after.LocalToRemoteNames[localName]; !ok { d.delete = append(d.delete, remoteName) @@ -50,7 +50,7 @@ func (d *diff) addRemovedFiles(after *SnapshotState, before *SnapshotState) { // Cleanup previous remote files for files that had their remote targets change. For // example this is possible if you convert a normal python script to a notebook. -func (d *diff) addFilesWithRemoteNameChanged(after *SnapshotState, before *SnapshotState) { +func (d *diff) addFilesWithRemoteNameChanged(after, before *SnapshotState) { for localName, beforeRemoteName := range before.LocalToRemoteNames { afterRemoteName, ok := after.LocalToRemoteNames[localName] if ok && afterRemoteName != beforeRemoteName { @@ -60,7 +60,7 @@ func (d *diff) addFilesWithRemoteNameChanged(after *SnapshotState, before *Snaps } // Add operators for files that were not being tracked before. -func (d *diff) addNewFiles(after *SnapshotState, before *SnapshotState) { +func (d *diff) addNewFiles(after, before *SnapshotState) { for localName := range after.LastModifiedTimes { if _, ok := before.LastModifiedTimes[localName]; !ok { d.put = append(d.put, localName) @@ -74,7 +74,7 @@ func (d *diff) addNewFiles(after *SnapshotState, before *SnapshotState) { } // Add operators for files which had their contents updated. -func (d *diff) addUpdatedFiles(after *SnapshotState, before *SnapshotState) { +func (d *diff) addUpdatedFiles(after, before *SnapshotState) { for localName, modTime := range after.LastModifiedTimes { prevModTime, ok := before.LastModifiedTimes[localName] if ok && modTime.After(prevModTime) { diff --git a/libs/sync/event.go b/libs/sync/event.go index 8e5c0efa2e..05821a477b 100644 --- a/libs/sync/event.go +++ b/libs/sync/event.go @@ -73,7 +73,7 @@ func (e *EventStart) String() string { return fmt.Sprintf("Action: %s", e.EventChanges.String()) } -func newEventStart(seq int, put []string, delete []string) Event { +func newEventStart(seq int, put, delete []string) Event { return &EventStart{ EventBase: newEventBase(seq, EventTypeStart), EventChanges: &EventChanges{Put: put, Delete: delete}, @@ -133,7 +133,7 @@ func (e *EventSyncComplete) String() string { return "Complete" } -func newEventComplete(seq int, put []string, delete []string) Event { +func newEventComplete(seq int, put, delete []string) Event { return &EventSyncComplete{ EventBase: newEventBase(seq, EventTypeComplete), EventChanges: &EventChanges{Put: put, Delete: delete}, diff --git a/libs/template/renderer_test.go b/libs/template/renderer_test.go index d1ce0fa779..eeb3087327 100644 --- a/libs/template/renderer_test.go +++ b/libs/template/renderer_test.go @@ -27,7 +27,7 @@ import ( "github.com/stretchr/testify/require" ) -func assertFileContent(t *testing.T, path string, content string) { +func assertFileContent(t *testing.T, path, content string) { b, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, content, string(b)) @@ -39,7 +39,7 @@ func assertFilePermissions(t *testing.T, path string, perm fs.FileMode) { assert.Equal(t, perm, info.Mode().Perm()) } -func assertBuiltinTemplateValid(t *testing.T, template string, settings map[string]any, target string, isServicePrincipal bool, build bool, tempDir string) { +func assertBuiltinTemplateValid(t *testing.T, template string, settings map[string]any, target string, isServicePrincipal, build bool, tempDir string) { ctx := context.Background() templateFS, err := fs.Sub(builtinTemplates, path.Join("templates", template))