From e5f2afa72fd99d46d57b9a8413e365fe5f84740d Mon Sep 17 00:00:00 2001 From: "pieter.noordhuis" Date: Wed, 11 Nov 2026 13:37:39 +0000 Subject: [PATCH 1/2] Test sync option builders without a root command The sync and bundle sync option builders took the command only to read its context, output type, and stdout. Pass those instead, so their tests no longer attach the command to root.New() to resolve the root flags. The argument count check for sync moves from the builder into RunE. Co-authored-by: Isaac --- cmd/bundle/sync.go | 12 +++++----- cmd/bundle/sync_test.go | 46 ++++++++++++++------------------------ cmd/sync/sync.go | 27 ++++++++++------------- cmd/sync/sync_test.go | 49 ++++++++++++++--------------------------- 4 files changed, 53 insertions(+), 81 deletions(-) diff --git a/cmd/bundle/sync.go b/cmd/bundle/sync.go index 955d425f208..219c82f3171 100644 --- a/cmd/bundle/sync.go +++ b/cmd/bundle/sync.go @@ -23,14 +23,16 @@ 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: @@ -38,7 +40,7 @@ func (f *syncFlags) syncOptionsFromBundle(cmd *cobra.Command, b *bundle.Bundle) } if outputFunc != nil { opts.OutputHandler = func(ctx context.Context, c <-chan sync.Event) { - outputFunc(ctx, c, cmd.OutOrStdout()) + outputFunc(ctx, c, stdout) } } @@ -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 } diff --git a/cmd/bundle/sync_test.go b/cmd/bundle/sync_test.go index 579aa69865f..4f778ca565a 100644 --- a/cmd/bundle/sync_test.go +++ b/cmd/bundle/sync_test.go @@ -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) { @@ -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) + } } diff --git a/cmd/sync/sync.go b/cmd/sync/sync.go index 027ef79a4a0..7d7fc21a600 100644 --- a/cmd/sync/sync.go +++ b/cmd/sync/sync.go @@ -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) } @@ -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: @@ -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 { @@ -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 diff --git a/cmd/sync/sync_test.go b/cmd/sync/sync_test.go index 757defc34f8..182f764df1b 100644 --- a/cmd/sync/sync_test.go +++ b/cmd/sync/sync_test.go @@ -1,6 +1,7 @@ package sync import ( + "io" "os" "path/filepath" "strings" @@ -8,22 +9,13 @@ import ( "github.com/databricks/cli/bundle" "github.com/databricks/cli/bundle/config" - "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/libs/cmdctx" "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 := New() - root.New(t.Context()).AddCommand(syncCmd) - return syncCmd -} - func TestSyncOptionsFromBundle(t *testing.T) { tempDir := t.TempDir() b := &bundle.Bundle{ @@ -43,7 +35,7 @@ func TestSyncOptionsFromBundle(t *testing.T) { } f := syncFlags{} - opts, err := f.syncOptionsFromBundle(New(), []string{}, b) + opts, err := f.syncOptionsFromBundle(t.Context(), []string{}, b) require.NoError(t, err) assert.Equal(t, tempDir, opts.LocalRoot.Native()) assert.Equal(t, "/Users/jane@doe.com/path", opts.RemotePath) @@ -51,35 +43,29 @@ func TestSyncOptionsFromBundle(t *testing.T) { assert.NotNil(t, opts.WorkspaceClient) } -func TestSyncOptionsFromArgsRequiredTwoArgs(t *testing.T) { - var err error - f := syncFlags{} - _, err = f.syncOptionsFromArgs(New(), []string{}) - require.ErrorContains(t, err, "accepts 2 arg(s), received 0") - _, err = f.syncOptionsFromArgs(New(), []string{"foo"}) - require.ErrorContains(t, err, "accepts 2 arg(s), received 1") - _, err = f.syncOptionsFromArgs(New(), []string{"foo", "bar", "qux"}) - require.ErrorContains(t, err, "accepts 2 arg(s), received 3") -} - func TestSyncOptionsFromArgs(t *testing.T) { local := t.TempDir() remote := "/remote" f := syncFlags{} - cmd := newTestSyncCommand(t) - cmd.SetContext(cmdctx.SetWorkspaceClient(t.Context(), nil)) - opts, err := f.syncOptionsFromArgs(cmd, []string{local, remote}) + ctx := cmdctx.SetWorkspaceClient(t.Context(), nil) + opts, err := f.syncOptionsFromArgs(ctx, flags.OutputText, io.Discard, []string{local, remote}) require.NoError(t, err) assert.Equal(t, local, opts.LocalRoot.Native()) assert.Equal(t, remote, opts.RemotePath) } -func TestSyncShorthandFlags(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()) +// TestSyncDoesNotShadowRootFlags checks that 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 TestSyncDoesNotShadowRootFlags(t *testing.T) { + cmd := New() + 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 TestReadPatternsFileErrorNamesFlag(t *testing.T) { @@ -108,12 +94,11 @@ func TestExcludeFromFlag(t *testing.T) { // Set up the flags f := syncFlags{excludeFrom: excludeFromPath} - cmd := newTestSyncCommand(t) - cmd.SetContext(cmdctx.SetWorkspaceClient(t.Context(), nil)) + ctx := cmdctx.SetWorkspaceClient(t.Context(), nil) // Test with both exclude flag and exclude-from flag f.exclude = []string{"node_modules/"} - opts, err := f.syncOptionsFromArgs(cmd, []string{local, remote}) + opts, err := f.syncOptionsFromArgs(ctx, flags.OutputText, io.Discard, []string{local, remote}) require.NoError(t, err) // Should include both exclude flag and exclude-from patterns From cc0e1512c1066194e483d70031072488db9c26c6 Mon Sep 17 00:00:00 2001 From: "pieter.noordhuis" Date: Wed, 11 Nov 2026 18:54:14 +0000 Subject: [PATCH 2/2] Pass args to root.Execute explicitly Lets Execute resolve the target command before running cobra, which lazily added subcommands need. nil args now mean no arguments instead of falling back to the process arguments. Co-authored-by: Isaac --- cmd/aitools/install_test.go | 4 +--- cmd/configure/configure_test.go | 28 +++++++--------------------- cmd/root/bundle_test.go | 9 +++------ cmd/root/root.go | 14 +++++++++++--- cmd/root/root_test.go | 27 +++++++++++++++++++++++---- internal/testcli/runner.go | 6 ++---- main.go | 2 +- 7 files changed, 48 insertions(+), 42 deletions(-) diff --git a/cmd/aitools/install_test.go b/cmd/aitools/install_test.go index f98e0697e79..0b80056009f 100644 --- a/cmd/aitools/install_test.go +++ b/cmd/aitools/install_test.go @@ -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:") diff --git a/cmd/configure/configure_test.go b/cmd/configure/configure_test.go index 3f3d7ea8633..44d75999522 100644 --- a/cmd/configure/configure_test.go +++ b/cmd/configure/configure_test.go @@ -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") @@ -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) @@ -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) @@ -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) @@ -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) @@ -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) @@ -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) diff --git a/cmd/root/bundle_test.go b/cmd/root/bundle_test.go index 6116003ea70..ae98df4b028 100644 --- a/cmd/root/bundle_test.go +++ b/cmd/root/bundle_test.go @@ -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)) @@ -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)) @@ -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)) diff --git a/cmd/root/root.go b/cmd/root/root.go index 59b9777ef69..52e14eae0e7 100644 --- a/cmd/root/root.go +++ b/cmd/root/root.go @@ -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() @@ -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 diff --git a/cmd/root/root_test.go b/cmd/root/root_test.go index ce1584eacd4..3ca81828091 100644 --- a/cmd/root/root_test.go +++ b/cmd/root/root_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "os" "testing" "github.com/databricks/cli/libs/cmdctx" @@ -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() @@ -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() @@ -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() @@ -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) +} diff --git a/internal/testcli/runner.go b/internal/testcli/runner.go index 5f2d1a23b75..efd4dfecaaf 100644 --- a/internal/testcli/runner.go +++ b/internal/testcli/runner.go @@ -104,7 +104,6 @@ func (r *Runner) RunBackground() { cli := cmd.New(r.ctx) cli.SetOut(stdoutW) cli.SetErr(stderrW) - cli.SetArgs(r.args) if r.stdinW != nil { cli.SetIn(r.stdinR) } @@ -123,7 +122,7 @@ func (r *Runner) RunBackground() { // Run command in background. go func() { - err := root.Execute(ctx, cli) + err := root.Execute(ctx, cli, r.args) if err != nil { if r.Verbose { r.Logf("Error running command: %s", err) @@ -181,13 +180,12 @@ func (r *Runner) Run() (bytes.Buffer, bytes.Buffer, error) { cli := cmd.New(r.ctx) cli.SetOut(&stdout) cli.SetErr(&stderr) - cli.SetArgs(r.args) if r.Verbose { r.Logf(" args: %s", strings.Join(r.args, ", ")) } - err := root.Execute(r.ctx, cli) + err := root.Execute(r.ctx, cli, r.args) if err != nil { if r.Verbose { r.Logf(" error: %s", err) diff --git a/main.go b/main.go index 6c4dddd40b6..0eb99617b78 100644 --- a/main.go +++ b/main.go @@ -25,7 +25,7 @@ func main() { } ctx := context.Background() - err := root.Execute(ctx, cmd.New(ctx)) + err := root.Execute(ctx, cmd.New(ctx), os.Args[1:]) if err != nil { os.Exit(1) }