take dive flags before a "--" in dive build and show its help

- `dive build` has flag parsing turned off so the build args pass through, which meant every arg went to `docker build`: there was no way to give dive flags like `--ci`, `--json` or `--source`, and `dive build --help` started a build
- args before a `--` are now parsed as dive flags (ahead of the config load, so they override the config like on other commands) and the rest go to the build: `dive build --ci -- -t app .`. Without a `--` everything still goes to the build
- `-h` / `--help` anywhere shows the dive build help

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>
This commit is contained in:
Alex Goodman 2026-11-16 17:16:05 -05:00
parent c35d7fec06
commit 95fb49457a
No known key found for this signature in database
3 changed files with 69 additions and 5 deletions

View file

@ -62,6 +62,34 @@ func Test_Build_CI_gate_fail(t *testing.T) {
}
func Test_Build_help(t *testing.T) {
for _, args := range []string{"build --help", "build -h", "build -t app . --help"} {
t.Run(args, func(t *testing.T) {
rootCmd := getTestCommand(t, args)
combined := Capture().WithStdout().WithStderr().Run(t, func() {
require.NoError(t, rootCmd.Execute())
})
assert.Contains(t, combined, "Usage:")
assert.NotContains(t, combined, "Building image")
})
}
}
func Test_Build_diveFlags(t *testing.T) {
// dive's flags come before "--", an invalid one fails before anything is built
rootCmd := getTestCommand(t, "build --platform a/b/c/d -- -t app .")
combined := Capture().WithStdout().WithStderr().Run(t, func() {
require.ErrorContains(t, rootCmd.Execute(), "invalid platform")
})
assert.NotContains(t, combined, "Building image")
rootCmd = getTestCommand(t, "build --not-a-dive-flag -- .")
require.ErrorContains(t, rootCmd.Execute(), "not-a-dive-flag")
rootCmd = getTestCommand(t, "build . -- -t app")
require.ErrorContains(t, rootCmd.Execute(), "unexpected arguments")
}
func Test_BuildFailure(t *testing.T) {
t.Run("nonexistent directory", func(t *testing.T) {

View file

@ -3,10 +3,12 @@ package command
import (
"context"
"fmt"
"slices"
"strings"
"github.com/anchore/clio"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/wagoodman/dive/cmd/dive/cli/internal/options"
"github.com/wagoodman/dive/internal/bus"
@ -25,9 +27,13 @@ func Build(app clio.Application) *cobra.Command {
opts := &buildOptions{
Application: options.DefaultApplication(),
}
return app.SetupCommand(&cobra.Command{
Use: "build [any valid `docker build` arguments]",
Short: "Builds and analyzes a docker image from a Dockerfile (this is a thin wrapper for the `docker build` command).",
cmd := app.SetupCommand(&cobra.Command{
Use: "build [dive flags --] [any valid `docker build` arguments]",
Short: "Builds and analyzes a docker image from a Dockerfile (this is a thin wrapper for the `docker build` command).",
Long: `Builds and analyzes a docker image from a Dockerfile (this is a thin wrapper for the ` + "`docker build`" + ` command).
All arguments go to the build, unless there is a "--": then the arguments before it are dive flags and the ones
after it go to the build, e.g. "dive build --ci -- -t app .".`,
DisableFlagParsing: true,
RunE: escaped(func(cmd *cobra.Command, args []string) error {
// the build subprocess writes to the terminal, so no UI may take it over
@ -35,7 +41,8 @@ func Build(app clio.Application) *cobra.Command {
return fmt.Errorf("failed to set UI: %w", err)
}
ref, err := build(cmd.Context(), opts.Analysis.Source, args)
_, buildArgs := splitBuildArgs(args)
ref, err := build(cmd.Context(), opts.Analysis.Source, buildArgs)
if err != nil {
return fmt.Errorf("cannot build image: %w", err)
}
@ -44,6 +51,35 @@ func Build(app clio.Application) *cobra.Command {
return run(cmd.Context(), opts.Application, ref)
}),
}, opts)
// flag parsing is off so the build args pass through untouched. The dive flags are parsed here instead, ahead
// of the config load in the setup PreRunE
setup := cmd.PreRunE
cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
if slices.Contains(args, "-h") || slices.Contains(args, "--help") {
// cobra shows the help for this
return pflag.ErrHelp
}
diveArgs, _ := splitBuildArgs(args)
cmd.InheritedFlags() // merges the root's persistent flags (--config, -v, ...) into cmd.Flags()
if err := cmd.Flags().Parse(diveArgs); err != nil {
return err
}
if cmd.Flags().NArg() > 0 {
return fmt.Errorf("unexpected arguments before \"--\": %s", strings.Join(cmd.Flags().Args(), " "))
}
return setup(cmd, args)
}
return cmd
}
// splitBuildArgs splits the args at the first "--" into dive flags and build args. Without one, everything is a
// build arg.
func splitBuildArgs(args []string) (diveArgs, buildArgs []string) {
if i := slices.Index(args, "--"); i >= 0 {
return args[:i], args[i+1:]
}
return nil, args
}
func build(ctx context.Context, engine string, args []string) (string, error) {

2
go.mod
View file

@ -30,6 +30,7 @@ require (
github.com/phayes/permbits v0.0.0-20190612203442-39d7c581d2ee
github.com/spf13/afero v1.15.0
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.0.10
github.com/stretchr/testify v1.12.1
github.com/wagoodman/go-partybus v0.0.0-20230516145632-8ccac152c651
github.com/wagoodman/go-progress v0.0.0-20260303201901-10176f79b2c0
@ -153,7 +154,6 @@ require (
github.com/smallstep/pkcs7 v0.2.1 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/cast v1.7.1 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/spf13/viper v1.20.1 // indirect
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 // indirect
github.com/subosito/gotenv v1.6.0 // indirect