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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions cmd/aitools/install_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1087,9 +1087,7 @@ func TestInstallOutputJSONThroughRoot(t *testing.T) {
var out, errOut bytes.Buffer
cli.SetOut(&out)
cli.SetErr(&errOut)
cli.SetArgs([]string{"install", "--agents", "codex", "--scope", "global", "--output", "json"})

err := root.Execute(ctx, cli)
err := root.Execute(ctx, cli, []string{"install", "--agents", "codex", "--scope", "global", "--output", "json"})
require.ErrorIs(t, err, root.ErrAlreadyPrinted)
assert.NotContains(t, errOut.String(), "Error:")

Expand Down
12 changes: 7 additions & 5 deletions cmd/bundle/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,24 @@ type syncFlags struct {
dryRun bool
}

func (f *syncFlags) syncOptionsFromBundle(cmd *cobra.Command, b *bundle.Bundle) (*sync.SyncOptions, error) {
opts, err := files.GetSyncOptions(cmd.Context(), b)
// syncOptionsFromBundle returns the options to sync the bundle, writing
// progress in the output format to stdout.
func (f *syncFlags) syncOptionsFromBundle(ctx context.Context, output flags.Output, stdout io.Writer, b *bundle.Bundle) (*sync.SyncOptions, error) {
opts, err := files.GetSyncOptions(ctx, b)
if err != nil {
return nil, fmt.Errorf("cannot get sync options: %w", err)
}

var outputFunc func(context.Context, <-chan sync.Event, io.Writer)
switch root.OutputType(cmd) {
switch output {
case flags.OutputText:
outputFunc = sync.TextOutput
case flags.OutputJSON:
outputFunc = sync.JsonOutput
}
if outputFunc != nil {
opts.OutputHandler = func(ctx context.Context, c <-chan sync.Event) {
outputFunc(ctx, c, cmd.OutOrStdout())
outputFunc(ctx, c, stdout)
}
}

Expand Down Expand Up @@ -78,7 +80,7 @@ Use 'databricks bundle deploy' for full resource deployment.`,
}
ctx := cmd.Context()

opts, err := f.syncOptionsFromBundle(cmd, b)
opts, err := f.syncOptionsFromBundle(ctx, root.OutputType(cmd), cmd.OutOrStdout(), b)
if err != nil {
return err
}
Expand Down
46 changes: 17 additions & 29 deletions cmd/bundle/sync_test.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
package bundle

import (
"io"
"testing"

"github.com/databricks/cli/bundle"
"github.com/databricks/cli/bundle/config"
"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/flags"
"github.com/databricks/cli/libs/vfs"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// newTestSyncCommand attaches the sync command to a root command so the root persistent flags resolve.
func newTestSyncCommand(t *testing.T) *cobra.Command {
syncCmd := newSyncCommand()
root.New(t.Context()).AddCommand(syncCmd)
return syncCmd
}

func TestBundleSyncShorthandFlags(t *testing.T) {
cmd := newTestSyncCommand(t)
require.NoError(t, cmd.ParseFlags([]string{"-o", "json", "-p", "myprofile"}))
assert.Equal(t, flags.OutputJSON, root.OutputType(cmd))
assert.Equal(t, "myprofile", cmd.Flag("profile").Value.String())
// TestBundleSyncDoesNotShadowRootFlags checks that bundle sync defines no
// local --output or --profile, which would hide the root's flags, and no -o or
// -p shorthand, which would conflict with them.
func TestBundleSyncDoesNotShadowRootFlags(t *testing.T) {
cmd := newSyncCommand()
for _, name := range []string{"output", "profile"} {
assert.Nil(t, cmd.LocalFlags().Lookup(name), name)
}
for _, shorthand := range []string{"o", "p"} {
assert.Nil(t, cmd.LocalFlags().ShorthandLookup(shorthand), shorthand)
}
}

func TestBundleSyncInstallsOutputHandler(t *testing.T) {
Expand All @@ -46,19 +44,9 @@ func TestBundleSyncInstallsOutputHandler(t *testing.T) {

f := syncFlags{}

// bundle sync defaults to text output, matching the standalone sync command:
// the root --output flag resolves to text when unset, so a handler is installed.
cmd := newTestSyncCommand(t)
cmd.SetContext(t.Context())
require.NoError(t, cmd.ParseFlags(nil))
opts, err := f.syncOptionsFromBundle(cmd, b)
require.NoError(t, err)
assert.NotNil(t, opts.OutputHandler)

cmd = newTestSyncCommand(t)
cmd.SetContext(t.Context())
require.NoError(t, cmd.ParseFlags([]string{"-o", "json"}))
opts, err = f.syncOptionsFromBundle(cmd, b)
require.NoError(t, err)
assert.NotNil(t, opts.OutputHandler)
for _, output := range []flags.Output{flags.OutputText, flags.OutputJSON} {
opts, err := f.syncOptionsFromBundle(t.Context(), output, io.Discard, b)
require.NoError(t, err)
assert.NotNil(t, opts.OutputHandler, output)
}
}
28 changes: 7 additions & 21 deletions cmd/configure/configure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@ func TestDefaultConfigureNoInteractive(t *testing.T) {
os.Stdin = inp

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure", "--token", "--host", "https://host"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure", "--token", "--host", "https://host"})
assert.NoError(t, err)

cfgPath := filepath.Join(tempHomeDir, ".databrickscfg")
Expand Down Expand Up @@ -90,9 +88,7 @@ func TestConfigFileFromEnvNoInteractive(t *testing.T) {
os.Stdin = inp

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure", "--token", "--host", "https://host"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure", "--token", "--host", "https://host"})
assert.NoError(t, err)

_, err = os.Stat(cfgPath)
Expand Down Expand Up @@ -130,9 +126,7 @@ func TestEnvVarsConfigureNoInteractive(t *testing.T) {
t.Setenv("DATABRICKS_METADATA_SERVICE_URL", "https://metadata")

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure", "--token"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure", "--token"})
assert.NoError(t, err)

_, err = os.Stat(cfgPath)
Expand Down Expand Up @@ -163,9 +157,7 @@ func TestEnvVarsConfigureNoArgsNoInteractive(t *testing.T) {
t.Setenv("DATABRICKS_TOKEN", "secret")

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure"})
assert.NoError(t, err)

_, err = os.Stat(cfgPath)
Expand Down Expand Up @@ -194,9 +186,7 @@ func TestEnvProfileConfigureNoInteractive(t *testing.T) {
t.Setenv("DATABRICKS_CONFIG_PROFILE", "FROM-ENV")

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure", "--token", "--host", "https://host"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure", "--token", "--host", "https://host"})
assert.NoError(t, err)

cfg, err := ini.Load(cfgPath)
Expand All @@ -222,9 +212,7 @@ func TestProfileShorthandOverridesEnvConfigureNoInteractive(t *testing.T) {
t.Setenv("DATABRICKS_CONFIG_PROFILE", "FROM-ENV")

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure", "--token", "--host", "https://host", "-p", "FROM-FLAG"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure", "--token", "--host", "https://host", "-p", "FROM-FLAG"})
assert.NoError(t, err)

cfg, err := ini.Load(cfgPath)
Expand All @@ -251,9 +239,7 @@ func TestCustomProfileConfigureNoInteractive(t *testing.T) {
os.Stdin = inp

cmd := cmd.New(ctx)
cmd.SetArgs([]string{"configure", "--token", "--host", "https://host", "--profile", "CUSTOM"})

err := root.Execute(ctx, cmd)
err := root.Execute(ctx, cmd, []string{"configure", "--token", "--host", "https://host", "--profile", "CUSTOM"})
assert.NoError(t, err)

_, err = os.Stat(cfgPath)
Expand Down
9 changes: 3 additions & 6 deletions cmd/root/bundle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,10 +387,9 @@ workspace:
func TestTargetFlagFull(t *testing.T) {
cmd := emptyCommand(t)
initTargetFlag(cmd)
cmd.SetArgs([]string{"version", "--target", "development"})

ctx := t.Context()
err := Execute(ctx, cmd)
err := Execute(ctx, cmd, []string{"version", "--target", "development"})
assert.NoError(t, err)

assert.Equal(t, "development", getTarget(cmd))
Expand All @@ -399,10 +398,9 @@ func TestTargetFlagFull(t *testing.T) {
func TestTargetFlagShort(t *testing.T) {
cmd := emptyCommand(t)
initTargetFlag(cmd)
cmd.SetArgs([]string{"version", "-t", "production"})

ctx := t.Context()
err := Execute(ctx, cmd)
err := Execute(ctx, cmd, []string{"version", "-t", "production"})
assert.NoError(t, err)

assert.Equal(t, "production", getTarget(cmd))
Expand All @@ -413,10 +411,9 @@ func TestTargetEnvironmentFlag(t *testing.T) {
cmd := emptyCommand(t)
initTargetFlag(cmd)
initEnvironmentFlag(cmd)
cmd.SetArgs([]string{"version", "--environment", "development"})

ctx := t.Context()
err := Execute(ctx, cmd)
err := Execute(ctx, cmd, []string{"version", "--environment", "development"})
assert.NoError(t, err)

assert.Equal(t, "development", getTarget(cmd))
Expand Down
14 changes: 11 additions & 3 deletions cmd/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,11 @@ func flagErrorFunc(c *cobra.Command, err error) error {
return fmt.Errorf("%w\n\n%s", err, c.UsageString())
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute(ctx context.Context, cmd *cobra.Command) (err error) {
// Execute runs cmd with args, which select the subcommand to run. It is called
// by main.main() with the arguments after the program name. Unlike
// [cobra.Command.SetArgs], nil args mean no arguments rather than the process
// arguments.
func Execute(ctx context.Context, cmd *cobra.Command, args []string) (err error) {
defer func() {
r := recover()

Expand Down Expand Up @@ -152,6 +154,12 @@ Stack Trace:
// Set a command execution ID value in the context
ctx = cmdctx.GenerateExecId(ctx)

// Cobra runs with the process arguments if args are nil.
if args == nil {
args = []string{}
}
cmd.SetArgs(args)

startTime := time.Now()

// Run the command
Expand Down
27 changes: 23 additions & 4 deletions cmd/root/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"os"
"testing"

"github.com/databricks/cli/libs/cmdctx"
Expand Down Expand Up @@ -45,7 +46,7 @@ func TestExecuteEnrichesAuthErrors(t *testing.T) {
return nil
}

err := Execute(ctx, cmd)
err := Execute(ctx, cmd, nil)
require.Error(t, err)

output := stderr.String()
Expand All @@ -71,7 +72,7 @@ func TestExecuteNoEnrichmentWithoutConfigUsed(t *testing.T) {
}
cmd.SetErr(stderr)

err := Execute(ctx, cmd)
err := Execute(ctx, cmd, nil)
require.Error(t, err)

output := stderr.String()
Expand Down Expand Up @@ -144,7 +145,7 @@ func TestExecuteAppendsAccountHostHint(t *testing.T) {
return nil
}

err := Execute(t.Context(), cmd)
err := Execute(t.Context(), cmd, nil)
require.Error(t, err)

output := stderr.String()
Expand Down Expand Up @@ -173,7 +174,25 @@ func TestExecuteErrAlreadyPrintedNotEnriched(t *testing.T) {
}
cmd.SetErr(stderr)

err := Execute(ctx, cmd)
err := Execute(ctx, cmd, nil)
require.Error(t, err)
assert.Empty(t, stderr.String())
}

func TestExecuteWithNilArgsRunsWithoutArgs(t *testing.T) {
processArgs := os.Args
t.Cleanup(func() { os.Args = processArgs })
os.Args = []string{"databricks", "process-arg"}

var got []string
cmd := &cobra.Command{
Use: "test",
RunE: func(cmd *cobra.Command, args []string) error {
got = args
return nil
},
}
require.NoError(t, Execute(t.Context(), cmd, nil))
assert.NotNil(t, got, "RunE did not run")
assert.Empty(t, got)
}
27 changes: 12 additions & 15 deletions cmd/sync/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ func readPatternsFile(flagName, filePath string) ([]string, error) {
return patterns, nil
}

func (f *syncFlags) syncOptionsFromBundle(cmd *cobra.Command, args []string, b *bundle.Bundle) (*sync.SyncOptions, error) {
func (f *syncFlags) syncOptionsFromBundle(ctx context.Context, args []string, b *bundle.Bundle) (*sync.SyncOptions, error) {
if len(args) > 0 {
return nil, errors.New("SRC and DST are not configurable in the context of a bundle")
}

opts, err := files.GetSyncOptions(cmd.Context(), b)
opts, err := files.GetSyncOptions(ctx, b)
if err != nil {
return nil, fmt.Errorf("cannot get sync options: %w", err)
}
Expand All @@ -91,13 +91,11 @@ func (f *syncFlags) syncOptionsFromBundle(cmd *cobra.Command, args []string, b *
return opts, nil
}

func (f *syncFlags) syncOptionsFromArgs(cmd *cobra.Command, args []string) (*sync.SyncOptions, error) {
if err := root.ExactArgs(2)(cmd, args); err != nil {
return nil, err
}

// syncOptionsFromArgs returns the options to sync the SRC and DST in args,
// writing progress in the output format to stdout.
func (f *syncFlags) syncOptionsFromArgs(ctx context.Context, output flags.Output, stdout io.Writer, args []string) (*sync.SyncOptions, error) {
var outputFunc func(context.Context, <-chan sync.Event, io.Writer)
switch root.OutputType(cmd) {
switch output {
case flags.OutputText:
outputFunc = sync.TextOutput
case flags.OutputJSON:
Expand All @@ -107,11 +105,10 @@ func (f *syncFlags) syncOptionsFromArgs(cmd *cobra.Command, args []string) (*syn
var outputHandler sync.OutputHandler
if outputFunc != nil {
outputHandler = func(ctx context.Context, events <-chan sync.Event) {
outputFunc(ctx, events, cmd.OutOrStdout())
outputFunc(ctx, events, stdout)
}
}

ctx := cmd.Context()
client := cmdctx.WorkspaceClient(ctx)

if f.dryRun {
Expand Down Expand Up @@ -192,15 +189,15 @@ func New() *cobra.Command {

cmd.PreRunE = mustWorkspaceClient
cmd.RunE = func(cmd *cobra.Command, args []string) error {
var opts *sync.SyncOptions
var err error

opts, err = f.syncOptionsFromArgs(cmd, args)
ctx := cmd.Context()
if err := root.ExactArgs(2)(cmd, args); err != nil {
return err
}
opts, err := f.syncOptionsFromArgs(ctx, root.OutputType(cmd), cmd.OutOrStdout(), args)
if err != nil {
return err
}

ctx := cmd.Context()
s, err := sync.New(ctx, *opts)
if err != nil {
return err
Expand Down
Loading
Loading