Skip to content
Draft
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
6 changes: 5 additions & 1 deletion cli/command/container/cp.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal/hint"
"github.com/docker/go-units"
"github.com/moby/go-archive"
"github.com/moby/moby/client"
Expand Down Expand Up @@ -242,7 +243,10 @@ func runCopy(ctx context.Context, dockerCli command.Cli, opts copyOptions) error
case acrossContainers:
return errors.New("copying between containers is not supported")
default:
return errors.New("must specify at least one container source")
return hint.Wrap(
errors.New("one argument must reference a container as 'CONTAINER:PATH'"),
"Use 'docker cp CONTAINER:SRC LOCAL' to copy from a container, or 'docker cp LOCAL CONTAINER:DEST' to copy into one.",
)
}
}

Expand Down
2 changes: 1 addition & 1 deletion cli/command/container/cp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestRunCopyWithInvalidArguments(t *testing.T) {
source: "./source",
destination: "./dest",
},
expectedErr: "must specify at least one container source",
expectedErr: "one argument must reference a container as 'CONTAINER:PATH'",
},
}
for _, testcase := range testcases {
Expand Down
6 changes: 5 additions & 1 deletion cli/command/container/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/types"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal/hint"
"github.com/docker/cli/internal/jsonstream"
"github.com/docker/cli/opts"
"github.com/moby/moby/api/types/mount"
Expand Down Expand Up @@ -188,7 +189,10 @@ func (cid *cidFile) Write(id string) error {
return nil
}
if _, err := cid.file.WriteString(id); err != nil {
return fmt.Errorf("failed to write the container ID (%s) to file: %w", id, err)
return hint.Wrap(
fmt.Errorf("container %s was created, but writing its ID to %s failed: %w", id, cid.path, err),
fmt.Sprintf("The container exists on the daemon. Run 'docker rm %s' to remove it, or note the ID for later use.", id),
)
Comment on lines +192 to +195
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be swallowed by cli.StatusError wrapping at the call site:

Status: withHelp(err, "create").Error(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will also be case for many other operations too

}
cid.written = true
return nil
Expand Down
6 changes: 5 additions & 1 deletion cli/command/container/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal/hint"
"github.com/docker/cli/opts"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
Expand Down Expand Up @@ -115,7 +116,10 @@ func RunExec(ctx context.Context, dockerCLI command.Cli, containerIDorName strin

execID := response.ID
if execID == "" {
return errors.New("exec ID empty")
return hint.Wrap(
errors.New("the Docker daemon returned an empty response when creating the exec session"),
"This is unexpected — please report it at https://github.com/moby/moby/issues with the daemon version ('docker version') and the command you ran.",
)
}

if options.Detach {
Expand Down
2 changes: 1 addition & 1 deletion cli/command/container/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ func TestRunExec(t *testing.T) {
{
doc: "missing exec ID",
options: NewExecOptions(),
expectedError: "exec ID empty",
expectedError: "the Docker daemon returned an empty response when creating the exec session",
client: &fakeClient{},
},
}
Expand Down
8 changes: 6 additions & 2 deletions cli/command/container/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal/hint"
"github.com/moby/moby/client"
"github.com/moby/sys/atomicwriter"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -49,13 +50,16 @@ func runExport(ctx context.Context, dockerCLI command.Cli, opts exportOptions) e
var output io.Writer
if opts.output == "" {
if dockerCLI.Out().IsTerminal() {
return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect")
return hint.Wrap(
errors.New("refusing to write a binary tar archive to the terminal"),
"Use '-o FILE' to write to a file, or redirect stdout, e.g. 'docker container export CONTAINER > out.tar'.",
)
}
output = dockerCLI.Out()
} else {
writer, err := atomicwriter.New(opts.output, 0o600)
if err != nil {
return fmt.Errorf("failed to export container: %w", err)
return fmt.Errorf("cannot open output file %q: %w", opts.output, err)
}
defer writer.Close()
output = writer
Expand Down
2 changes: 1 addition & 1 deletion cli/command/container/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ func TestContainerExportOutputToIrregularFile(t *testing.T) {
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"-o", "/dev/random", "container"})

const expected = `failed to export container: cannot write to a character device file`
const expected = `cannot open output file "/dev/random": cannot write to a character device file`
assert.Error(t, cmd.Execute(), expected)
}
32 changes: 24 additions & 8 deletions cli/command/container/opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"strings"
"time"

"github.com/docker/cli/internal/hint"
"github.com/docker/cli/internal/lazyregexp"
"github.com/docker/cli/internal/volumespec"
"github.com/docker/cli/opts"
Expand Down Expand Up @@ -517,22 +518,34 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con

pidMode := container.PidMode(copts.pidMode)
if !pidMode.Valid() {
return nil, errors.New("--pid: invalid PID mode")
return nil, hint.Wrap(
fmt.Errorf("invalid --pid mode %q", copts.pidMode),
"Valid forms are 'host' or 'container:<name|id>'.",
)
}

utsMode := container.UTSMode(copts.utsMode)
if !utsMode.Valid() {
return nil, errors.New("--uts: invalid UTS mode")
return nil, hint.Wrap(
fmt.Errorf("invalid --uts mode %q", copts.utsMode),
"The only valid form is 'host'.",
)
}

usernsMode := container.UsernsMode(copts.usernsMode)
if !usernsMode.Valid() {
return nil, errors.New("--userns: invalid USER mode")
return nil, hint.Wrap(
fmt.Errorf("invalid --userns mode %q", copts.usernsMode),
"The only valid form is 'host'.",
)
}

cgroupnsMode := container.CgroupnsMode(copts.cgroupnsMode)
if !cgroupnsMode.Valid() {
return nil, errors.New("--cgroupns: invalid CGROUP mode")
return nil, hint.Wrap(
fmt.Errorf("invalid --cgroupns mode %q", copts.cgroupnsMode),
"Valid forms are 'private' or 'host'.",
)
}

restartPolicy, err := opts.ParseRestartPolicy(copts.restartPolicy)
Expand Down Expand Up @@ -920,7 +933,10 @@ func convertToStandardNotation(ports []string) ([]string, error) {
func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) {
loggingOptsMap := opts.ConvertKVStringsToMap(loggingOpts)
if loggingDriver == "none" && len(loggingOpts) > 0 {
return map[string]string{}, fmt.Errorf("invalid logging opts for driver %s", loggingDriver)
return map[string]string{}, hint.Wrap(
errors.New("log driver \"none\" accepts no --log-opt entries"),
"Remove the --log-opt flag(s) or choose a different --log-driver.",
)
}
return loggingOptsMap, nil
}
Expand Down Expand Up @@ -984,7 +1000,7 @@ func parseStorageOpts(storageOpts []string) (map[string]string, error) {
for _, option := range storageOpts {
k, v, ok := strings.Cut(option, "=")
if !ok {
return nil, errors.New("invalid storage option")
return nil, fmt.Errorf("invalid --storage-opt value %q: expected key=value", option)
}
m[k] = v
}
Expand Down Expand Up @@ -1095,12 +1111,12 @@ func validateLinuxPath(val string, validator func(string) bool) (string, error)
var mode string

if strings.Count(val, ":") > 2 {
return val, fmt.Errorf("bad format for path: %s", val)
return val, fmt.Errorf("invalid --device %q: too many ':' separators, expected [host-path:]container-path[:mode]", val)
}

split := strings.SplitN(val, ":", 3)
if split[0] == "" {
return val, fmt.Errorf("bad format for path: %s", val)
return val, fmt.Errorf("invalid --device %q: host path before ':' is empty, expected [host-path:]container-path[:mode]", val)
}
switch len(split) {
case 1:
Expand Down
28 changes: 15 additions & 13 deletions cli/command/container/opts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ func TestParseModes(t *testing.T) {
args := []string{"--pid=container:", "img", "cmd"}
assert.NilError(t, flags.Parse(args))
_, err := parse(flags, copts, runtime.GOOS)
assert.ErrorContains(t, err, "--pid: invalid PID mode")
assert.ErrorContains(t, err, "invalid --pid mode")

// pid ok
_, hostconfig, _, err := parseRun([]string{"--pid=host", "img", "cmd"})
Expand All @@ -778,7 +778,7 @@ func TestParseModes(t *testing.T) {

// uts ko
_, _, _, err = parseRun([]string{"--uts=container:", "img", "cmd"}) //nolint:dogsled
assert.ErrorContains(t, err, "--uts: invalid UTS mode")
assert.ErrorContains(t, err, "invalid --uts mode")

// uts ok
_, hostconfig, _, err = parseRun([]string{"--uts=host", "img", "cmd"})
Expand Down Expand Up @@ -923,8 +923,8 @@ func TestParseHealth(t *testing.T) {

func TestParseLoggingOpts(t *testing.T) {
// logging opts ko
if _, _, _, err := parseRun([]string{"--log-driver=none", "--log-opt=anything", "img", "cmd"}); err == nil || err.Error() != "invalid logging opts for driver none" {
t.Fatalf("Expected an error with message 'invalid logging opts for driver none', got %v", err)
if _, _, _, err := parseRun([]string{"--log-driver=none", "--log-opt=anything", "img", "cmd"}); err == nil || !strings.HasPrefix(err.Error(), "log driver \"none\" accepts no --log-opt entries") {
t.Fatalf("Expected an error stating that 'none' accepts no --log-opt entries, got %v", err)
}
// logging opts ok
_, hostconfig, _, err := parseRun([]string{"--log-driver=syslog", "--log-opt=something", "img", "cmd"})
Expand Down Expand Up @@ -1034,22 +1034,24 @@ func TestValidateDevice(t *testing.T) {
"/hostPath:/containerPath:rw",
"/hostPath:/containerPath:mrw",
}
const emptyHostMsg = `: host path before ':' is empty, expected [host-path:]container-path[:mode]`
const tooManyMsg = `: too many ':' separators, expected [host-path:]container-path[:mode]`
invalid := map[string]string{
"": "bad format for path: ",
"": `invalid --device ""` + emptyHostMsg,
"./": "./ is not an absolute path",
"../": "../ is not an absolute path",
"/:../": "../ is not an absolute path",
"/:path": "path is not an absolute path",
":": "bad format for path: :",
":": `invalid --device ":"` + emptyHostMsg,
"/tmp:": " is not an absolute path",
":test": "bad format for path: :test",
":/test": "bad format for path: :/test",
":test": `invalid --device ":test"` + emptyHostMsg,
":/test": `invalid --device ":/test"` + emptyHostMsg,
"tmp:": " is not an absolute path",
":test:": "bad format for path: :test:",
"::": "bad format for path: ::",
":::": "bad format for path: :::",
"/tmp:::": "bad format for path: /tmp:::",
":/tmp::": "bad format for path: :/tmp::",
":test:": `invalid --device ":test:"` + emptyHostMsg,
"::": `invalid --device "::"` + emptyHostMsg,
":::": `invalid --device ":::"` + tooManyMsg,
"/tmp:::": `invalid --device "/tmp:::"` + tooManyMsg,
":/tmp::": `invalid --device ":/tmp::"` + tooManyMsg,
"path:ro": "ro is not an absolute path",
"path:rr": "rr is not an absolute path",
"a:/b:ro": "bad mode specified: ro",
Expand Down
6 changes: 5 additions & 1 deletion cli/command/container/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal/hint"
"github.com/docker/cli/opts"
containertypes "github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
Expand Down Expand Up @@ -92,7 +93,10 @@ func runUpdate(ctx context.Context, dockerCli command.Cli, options *updateOption
var err error

if options.nFlag == 0 {
return errors.New("you must provide one or more flags when using this command")
return hint.Wrap(
errors.New("no resource flags supplied — nothing to update"),
"Pass at least one tunable flag (for example --memory, --cpus, --restart). Run 'docker container update --help' for the full list.",
)
}

var restartPolicy containertypes.RestartPolicy
Expand Down
2 changes: 1 addition & 1 deletion cli/command/context/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func runCreate(dockerCLI command.Cli, name string, opts createOptions) error {

func createNewContext(contextStore store.ReaderWriter, name string, opts createOptions) error {
if opts.endpoint == nil {
return errors.New("docker endpoint configuration is required")
return errors.New("no docker endpoint configured: set one with --docker, or copy from an existing context with --from")
}
dockerEP, dockerTLS, err := getDockerEndpointMetadataAndTLS(contextStore, opts.endpoint)
if err != nil {
Expand Down
6 changes: 5 additions & 1 deletion cli/command/context/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/context/store"
"github.com/docker/cli/internal/hint"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -37,7 +38,10 @@ func writeTo(dockerCli command.Cli, reader io.Reader, dest string) error {
var printDest bool
if dest == "-" {
if dockerCli.Out().IsTerminal() {
return errors.New("cowardly refusing to export to a terminal, specify a file path")
return hint.Wrap(
errors.New("exported context is a binary tar stream and would corrupt the terminal"),
"Pass a file path as the second argument, or redirect stdout (e.g. 'docker context export NAME > file.dockercontext').",
)
}
writer = dockerCli.Out()
} else {
Expand Down
2 changes: 1 addition & 1 deletion cli/command/context/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func getDockerEndpoint(contextStore store.Reader, config map[string]string) (doc
if ep, ok := metadata.Endpoints[docker.DockerEndpoint].(docker.EndpointMeta); ok {
return docker.Endpoint{EndpointMeta: ep}, nil
}
return docker.Endpoint{}, fmt.Errorf("unable to get endpoint from context %q", contextName)
return docker.Endpoint{}, fmt.Errorf("context %q has no docker endpoint configured", contextName)
}
tlsData, err := context.TLSDataFromFiles(config[keyCA], config[keyCert], config[keyKey])
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions cli/command/image/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions)
_, _ = fmt.Fprintln(dockerCli.Err(), progBuff)
}
default:
return fmt.Errorf("unable to prepare context: path %q not found", options.context)
return fmt.Errorf("build context %q is not a supported form: expected '-' for stdin, an existing directory, a Git URL, or an HTTP(S) URL", options.context)
}

// read from a directory into tar archive
Expand Down Expand Up @@ -356,7 +356,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions)
aux := func(msg jsonstream.JSONMessage) {
var result buildtypes.Result
if err := json.Unmarshal(*msg.Aux, &result); err != nil {
_, _ = fmt.Fprintf(dockerCli.Err(), "Failed to parse aux message: %s", err)
_, _ = fmt.Fprintf(dockerCli.Err(), "could not read image ID from daemon response; the image was built, but --iidfile and -q output will be empty: %s", err)
} else {
imageID = result.ID
}
Expand Down Expand Up @@ -387,7 +387,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions)

if options.imageIDFile != "" {
if imageID == "" {
return fmt.Errorf("server did not provide an image ID. Cannot write %s", options.imageIDFile)
return fmt.Errorf("image was built, but --iidfile %q was not written: the daemon did not return an image ID", options.imageIDFile)
}
if err := os.WriteFile(options.imageIDFile, []byte(imageID), 0o666); err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion cli/command/image/build/context_detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func DetectContextType(specifiedContext string) (ContextType, error) {
case urlutil.IsURL(specifiedContext):
return ContextTypeRemote, nil
default:
return "", fmt.Errorf("unable to prepare context: path %q not found", specifiedContext)
return "", fmt.Errorf("build context %q is not a supported form: expected '-' for stdin, an existing directory, a Git URL, or an HTTP(S) URL", specifiedContext)
}
}

Expand Down
2 changes: 1 addition & 1 deletion cli/command/image/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func shouldUseTree(options imagesOptions) (bool, error) {
}
if options.showDigests {
if options.tree {
return false, errors.New("--show-digest is not yet supported with --tree")
return false, errors.New("--digests is not yet supported with --tree")
}
return false, nil
}
Expand Down
6 changes: 5 additions & 1 deletion cli/command/image/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal/hint"
"github.com/docker/cli/internal/jsonstream"
"github.com/moby/moby/client"
"github.com/moby/sys/sequential"
Expand Down Expand Up @@ -61,7 +62,10 @@ func runLoad(ctx context.Context, dockerCli command.Cli, opts loadOptions) error
// To avoid getting stuck, verify that a tar file is given either in
// the input flag or through stdin and if not display an error message and exit.
if dockerCli.In().IsTerminal() {
return errors.New("requested load from stdin, but stdin is empty")
return hint.Wrap(
errors.New("no input given: stdin is a terminal, not a tar archive"),
"Pipe a tar archive into 'docker image load', or pass one with '-i FILE'.",
)
}
default:
// We use sequential.Open to use sequential file access on Windows, avoiding
Expand Down
2 changes: 1 addition & 1 deletion cli/command/image/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestNewLoadCommandErrors(t *testing.T) {
name: "input-to-terminal",
args: []string{},
isTerminalIn: true,
expectedError: "requested load from stdin, but stdin is empty",
expectedError: "stdin is a terminal, not a tar archive",
},
{
name: "pull-error",
Expand Down
Loading
Loading