Compare commits

...

1598 Commits

Author SHA1 Message Date
Sebastiaan van Stijn 2f87a11e96
Merge pull request #6202 from Mewsen/issue/6188
refactor(cli/compose/loader): extract ParseVolume() to its own package
2025-07-25 17:08:54 +02:00
Michael Tews ef7fd8bb67
refactor(cli/compose/loader): extract ParseVolume() to its own package
Moves ParseVolume() to a new internal package to remove the dependency
on cli/compose/loader in cli/command/container/opts.go

refactor to keep types isolated

- rename the package to "volumespec" to reuse the name of the package
  as part of the name (parsevolume.ParseVolume() -> volumespec.Parse())
- move the related compose types to the internal package as well,
  and rename them to be more generic (not associated with "compose");
  - ServiceVolumeConfig -> VolumeConfig
  - ServiceVolumeBind -> BindOpts
  - ServiceVolumeVolume -> VolumeOpts
  - ServiceVolumeImage -> ImageOpts
  - ServiceVolumeTmpfs -> TmpFsOpts
  - ServiceVolumeCluster -> ClusterOpts
- alias the internal types inside cli/compose/types to keep backward
  compatibility (for any external consumers); even though the implementation
  is internal, Go allows aliasing types to use them externally.

Signed-off-by: Michael Tews <michael@tews.dev>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-25 16:56:17 +02:00
Paweł Gronowski 3046019d3b
Merge pull request #6209 from vvoland/image-tree-nonexp
image/tree: Unmark as experimental, warn when redirected
2025-07-25 12:58:37 +02:00
Sebastiaan van Stijn 1eeb0cc3e1
Merge pull request #6207 from thaJeztah/fork_registry
add internal fork of docker/docker/registry
2025-07-25 12:57:47 +02:00
Paweł Gronowski 9257cc7f68
image/tree: Unmark as experimental, warn when redirected
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-07-25 12:07:54 +02:00
Paweł Gronowski f214f860b6
image/tree: Remove extra newline after legend
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-07-25 12:04:42 +02:00
Sebastiaan van Stijn f907c7a4b0
internal/registry: fix linting issues (revive)
internal/registry/errors.go:26:43: use-any: since Go 1.18 'interface{}' can be replaced by 'any' (revive)
    func invalidParamf(format string, args ...interface{}) error {
                                              ^
    internal/registry/registry_mock_test.go:52:51: use-any: since Go 1.18 'interface{}' can be replaced by 'any' (revive)
    func writeResponse(w http.ResponseWriter, message interface{}, code int) {
                                                      ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-25 00:08:26 +02:00
Sebastiaan van Stijn cd277a5815
cli/command/system: remove use of Mirrors field in test
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:29:48 +02:00
Sebastiaan van Stijn c297770d2d
internal/registry: remove pkg/errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:29:47 +02:00
Sebastiaan van Stijn 219cfc8b7d
internal/registry: define local serviceConfig
The registry.ServiceConfig struct in the API types was meant for the
registry configuration on the daemon side; it has variuos fields we
don't use, defines methods for (un)marshaling JSON, and a custom version
of `net.IPNet`, also to (un)marshal JSON.

None of that is needed, so let's change it to a local type, and implement
a constructor (as we now only have "insecure registries" to care
about).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:29:47 +02:00
Sebastiaan van Stijn 2607ba8062
internal/registry: remove ValidateIndexName
It was written to be used as validate-func for command-line flags, which
we don't use it for (which for CLI-flags includes normalizing the value).

The validation itself didn't add much; it only checked the registry didn't
start or end with a hyphen (which would still fail when parsing).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:29:36 +02:00
Sebastiaan van Stijn 5322affc9f
internal/registry: remove duplicate endpoint methods
now that we no longer need to account for mirrors, these were
identical, so just use a single one.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:23:11 +02:00
Sebastiaan van Stijn dc41365b56
internal/registry: remove NewStaticCredentialStore
It was only used in a single place; inline it there.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:23:10 +02:00
Sebastiaan van Stijn dad2e67860
internal/registry: remove PingResponseError
It's not matched anywhere, so we can just return a plain error.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:23:10 +02:00
Sebastiaan van Stijn 7cf245d2f7
internal/registry: Service.Auth remove unused statusmessage return
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:23:10 +02:00
Sebastiaan van Stijn e0b351b3d9
internal/registry: remove code related to mirrors
The CLI does not have information about mirrors, and doesn't
configure them, so we can remove these parts.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 23:23:02 +02:00
Sebastiaan van Stijn 7716219e17
internal/registry: remove dead code
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 22:14:25 +02:00
Sebastiaan van Stijn f6b90bc253
add internal fork of docker/docker/registry
This adds an internal fork of [github.com/docker/docker/registry], taken
at commit [moby@f651a5d]. Git history  was not preserved in this fork,
but can be found using the URLs provided.

This fork was created to remove the dependency on the "Moby" codebase,
and because the CLI only needs a subset of its features. The original
package was written specifically for use in the daemon code, and includes
functionality that cannot be used in the CLI.

[github.com/docker/docker/registry]: https://pkg.go.dev/github.com/docker/docker@v28.3.2+incompatible/registry
[moby@49306c6]: 49306c607b/registry

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 19:59:17 +02:00
Sebastiaan van Stijn 636a4cf2dc
Merge pull request #6208 from thaJeztah/bump_moby
vendor: github.com/docker/docker master
2025-07-24 19:45:06 +02:00
Sebastiaan van Stijn 20181d4363
vendor: github.com/docker/docker master
forgot to update this dependency (only updated the api and client)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 18:12:28 +02:00
Paweł Gronowski d29d719c42
Merge pull request #6204 from thaJeztah/bump_engine
vendor: docker/docker, moby/api, and moby/client master
2025-07-24 17:25:47 +02:00
Sebastiaan van Stijn fa169b6933
vendor: docker/docker, moby/api, and moby/client master
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 16:06:08 +02:00
Paweł Gronowski 1ca6c946d5
Merge pull request #6126 from ctalledo/fix-for-moby-48759
Add support for multiple platform options in image load and save
2025-07-24 11:48:11 +02:00
Sebastiaan van Stijn c2586d68cf
Merge pull request #6206 from thaJeztah/remove_RepoNameForReference
cli/registry/client: remove deprecated RepoNameForReference
2025-07-24 11:35:03 +02:00
Sebastiaan van Stijn a87bde0068
cli/registry/client: remove deprecated RepoNameForReference
This was deprecated in 6f46cd2f4b,
which is part of v28.x, and no longer used, so we can remove it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-24 01:33:55 +02:00
Sebastiaan van Stijn df9950aa06
Merge pull request #6201 from thaJeztah/bump_engine
vendor: docker/docker, moby/api, moby/client to latest
2025-07-23 13:40:13 +02:00
Sebastiaan van Stijn 323ef1997f
vendor: docker/docker, moby/api, moby/client to latest
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-23 09:45:51 +02:00
Sebastiaan van Stijn 80be02c72b
Merge pull request #6200 from thaJeztah/search_no_registrypkg
cli/command/registry: remove uses of registry.ParseSearchIndexInfo
2025-07-22 23:01:28 +02:00
Sebastiaan van Stijn e504faf6da
cli/command/registry: remove uses of registry.ParseSearchIndexInfo
This utility was only used in the CLI, but the implementation was
based on it being used on the daemon side, so included resolving
the host's IP-address, mirrors, etc.

The only reason it's used in the CLI is to provide credentials for
the registry that's being searched, so reduce it to just that.

There's more cleaning up to do in this area, so to make our lives
easier, it's implemented locally as non-exported functions; likely
to be replaced with something else.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-22 22:13:38 +02:00
Sebastiaan van Stijn 03ff54b8ba
Merge pull request #6193 from thaJeztah/bump_engine
vendor: github.com/docker/docker master (v29.0-dev)
2025-07-22 09:19:13 +02:00
Sebastiaan van Stijn 644dc16b16
vendor: github.com/docker/docker master (v29.0-dev)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-21 23:04:50 +02:00
Sebastiaan van Stijn 2a2748a94c
Merge pull request #6195 from thaJeztah/build_no_dct
build: remove DCT support for classic builder
2025-07-21 22:03:46 +02:00
Sebastiaan van Stijn 7609dde8d0
build: remove DCT support for classic builder
Docker Content Trust is currently only implemented for the classic
builder, but is known to not work with multi-stage builds, and
requires rewriting the Dockerfile, which is brittle because the
Dockerfile syntax evolved with the introduction of BuildKit as
default builder.

Given that the classic builder is deprecated, and only used for
Windows images, which are not verified by content trust;

    # docker pull --disable-content-trust=false mcr.microsoft.com/windows/servercore:ltsc2025
    Error: remote trust data does not exist for mcr.microsoft.com/windows/servercore: mcr.microsoft.com does not have trust data for mcr.microsoft.com/windows/servercore

With content trust not implemented in BuildKit, and not implemented
in docker compose, this resulted in an inconsistent behavior.

This patch removes content-trust support for "docker build". As this
is a client-side feature, users who require this feature can still
use an older CLI to to start the build.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-21 19:05:38 +02:00
Sebastiaan van Stijn 71bc8ab3ea
Merge pull request #6186 from thaJeztah/remove_more_aliases
opts: minor cleanup in tests, and remove some import aliases
2025-07-17 17:18:15 +02:00
Sebastiaan van Stijn 6cf2c023f8
Merge pull request #6187 from thaJeztah/container_unexport
cli/command/container: deprecate NewDiffFormat, DiffFormatWrite
2025-07-17 17:09:50 +02:00
Sebastiaan van Stijn 73604b8c36
Merge pull request #6192 from thaJeztah/trust_no_api_const
cli/command/image: remove use of api.NoBaseImageSpecifier
2025-07-17 15:59:06 +02:00
Sebastiaan van Stijn e2cab2c64c
cli/command/image: remove use of api.NoBaseImageSpecifier
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-17 14:28:13 +02:00
Sebastiaan van Stijn 74042f5ffa
Merge pull request #6191 from robmry/info_firewall_backend
Include FirewallBackend in docker info output
2025-07-17 11:52:35 +02:00
Sebastiaan van Stijn 8c317ad3fd
Merge pull request #6190 from thaJeztah/fork_remotecontext
add local fork of github.com/docker/docker/builder/remotecontext
2025-07-17 01:34:55 +02:00
Sebastiaan van Stijn 64f33cd463
TestCloneArgsSmartHttp: fix unhandled error
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 22:21:46 +02:00
Rob Murray a3bea24086 Include FirewallBackend in docker info output
Signed-off-by: Rob Murray <rob.murray@docker.com>
2025-07-16 17:17:27 +00:00
Sebastiaan van Stijn b05aa464a6
Dockerfile: install git-daemon for use in tests
gitutils_test.go:210: git-http-backend: git: 'http-backend' is not a git command. See 'git --help'.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 16:48:40 +02:00
Sebastiaan van Stijn e34616574f
fix linting issues
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 16:27:27 +02:00
Sebastiaan van Stijn 8d2ccc128a
add local fork of github.com/docker/docker/builder/remotecontext
Adds a local fork of this package for use in the classic builder.

Code was taken at commit [d33d46d01656e1d9ee26743f0c0d7779f685dd4e][1].

Migration was done using the following steps:

    # install filter-repo (https://github.com/newren/git-filter-repo/blob/main/INSTALL.md)
    brew install git-filter-repo

    # create a temporary clone of docker
    cd ~/Projects
    git clone https://github.com/docker/docker.git build_context_temp
    cd build_context_temp

    # commit taken from
    git rev-parse --verify HEAD
    d33d46d01656e1d9ee26743f0c0d7779f685dd4e

    git filter-repo --analyze

    # remove all code, except for the remotecontext packages, and move to build/internal docs and previous locations of it
    git filter-repo \
      --path 'builder/remotecontext/git' \
      --path 'builder/remotecontext/urlutil' \
      --path-rename builder/remotecontext:cli/command/image/build/internal

    # go to the target repository
    cd ~/go/src/github.com/docker/cli

    # create a branch to work with
    git checkout -b fork_remotecontext

    # add the temporary repository as an upstream and make sure it's up-to-date
    git remote add build_context_temp ~/Projects/build_context_temp
    git fetch build_context_temp

    # merge the upstream code
    git merge --allow-unrelated-histories --signoff -S build_context_temp/master

[1]: https://github.com/docker/docker/d33d46d01656e1d9ee26743f0c0d7779f685dd4e

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 16:18:51 +02:00
Sebastiaan van Stijn b5a939268b
Merge pull request #6189 from thaJeztah/cleanup_build_context
cli/command/image: move build-context detection to build
2025-07-16 15:57:58 +02:00
Sebastiaan van Stijn 260f1dbebb
cli/command/image: move build-context detection to build
Removes direct imports of github.com/docker/docker/builder in
the image package, to be moved later.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 15:50:32 +02:00
Sebastiaan van Stijn e95d133612
remove some redundant import aliases
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 13:56:49 +02:00
Sebastiaan van Stijn 3dec3879c8
opts: minor cleanup in tests
- use consistent name for MountOpt vars
- cleanup some comments and make them a GoDoc
- remove import alias
- use subtests for tests that were prepared for it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 13:56:49 +02:00
Sebastiaan van Stijn fdc90caeee
cli/command/container: deprecate DiffFormatWrite
It's part of the presentation logic of the cli, and only used internally.
We can consider providing utilities for these, but better as part of
separate packages.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 13:52:04 +02:00
Sebastiaan van Stijn 0db7b9f774
cli/command/container: newDiffContext: use struct-literal
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 13:50:31 +02:00
Sebastiaan van Stijn 239b727834
cli/command/container: DiffFormatWrite: remove intermediate var
Also rename "ctx" argument; we shouldn't use this as name for things
that are not a context.Context.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 13:45:09 +02:00
Sebastiaan van Stijn 907507e22a
cli/command/container: deprecate NewDiffFormat
It's part of the presentation logic of the cli, and only used internally.
We can consider providing utilities for these, but better as part of
separate packages.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 13:45:05 +02:00
Sebastiaan van Stijn d8089e7d1b
Merge pull request #6184 from Benehiko/deprecate-prompt-privilege-func
cli/command: deprecate RegistryAuthenticationPrivilegedFunc
2025-07-16 13:26:12 +02:00
Alano Terblanche 29263e865b
cli/command: remove usages of RegistryAuthenticationPrivilegedFunc
This patch deprecates the unused `RegistryAuthenticationPrivilegedFunc`.
The function would prompt the user when the registry returns a 403 after trying
the initial auth value set in `RegistryAuth`.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-07-16 12:49:19 +02:00
Sebastiaan van Stijn 6bcc9ce730
Merge pull request #6174 from Benehiko/remove-prompt-privilege-func
cli/command: remove interactive login prompt from docker push/pull
2025-07-16 12:48:25 +02:00
Sebastiaan van Stijn 46b8679315
Merge pull request #6155 from thaJeztah/bump_alpine
Dockerfile: update to alpine 3.22
2025-07-16 12:47:48 +02:00
Sebastiaan van Stijn 980b856816
Merge pull request #6183 from thaJeztah/diff_simplify
cli/command/container: diff: remove redundant validation and cleanup
2025-07-16 12:32:48 +02:00
Sebastiaan van Stijn ea4c161067
Dockerfile: update to alpine 3.22
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 12:20:03 +02:00
Sebastiaan van Stijn 9c256146ac
Merge pull request #6181 from thaJeztah/fork_readCloserWrapper
remove uses of github.com/docker/docker/pkg/ioutils ReadCloserWrapper
2025-07-16 12:19:14 +02:00
Sebastiaan van Stijn bc01f8489d
Merge pull request #6182 from thaJeztah/fork_longpath
remove use of github.com/docker/docker/pkg/longpath
2025-07-16 12:18:06 +02:00
Sebastiaan van Stijn ea2a0c3b8a
Merge pull request #6177 from thaJeztah/rm_aliases
cli/command: remove some redundant import-aliases
2025-07-16 12:17:23 +02:00
Sebastiaan van Stijn 3d985799d4
cli/command: remove some redundant import-aliases
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 12:12:41 +02:00
Sebastiaan van Stijn f5f3b027e8
Merge pull request #6178 from thaJeztah/bump_dev_tools
Dockerfile: update Buildx v0.25.0, compose v2.38.2
2025-07-16 12:07:46 +02:00
Sebastiaan van Stijn 143f36133a
Merge pull request #6179 from thaJeztah/bump_gotestsum
Dockerfile: bump gotest.tools/gotestsum v1.12.3 (for go1.25)
2025-07-16 12:07:17 +02:00
Sebastiaan van Stijn d7181e47e2
Merge pull request #6185 from thaJeztah/alpine_doc
Dockerfile: document ALPINE_VERSION build-arg
2025-07-16 12:06:17 +02:00
Sebastiaan van Stijn 8b6436ecee
Dockerfile: document ALPINE_VERSION build-arg
docker build --call outline .

    TARGET: binary

    BUILD ARG               VALUE    DESCRIPTION
    BASE_VARIANT            alpine
    ALPINE_VERSION          3.21     sets the version of the alpine base image to use, including for the golang image.
    GO_VERSION              1.24.5
    XX_VERSION              1.6.1
    GOVERSIONINFO_VERSION   v1.4.1
    GO_LINKMODE             static   defines if static or dynamic binary should be produced
    GO_BUILDTAGS                     defines additional build tags
    GO_STRIP                         strips debugging symbols if set
    CGO_ENABLED                      manually sets if cgo is used
    VERSION                          sets the version for the produced binary
    PACKAGER_NAME                    sets the company that produced the windows binary

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-16 09:51:14 +02:00
Alano Terblanche 2b56b66b10
cli/command: remove interactive login prompt from docker push/pull
This patch removes the interactive prompts from `docker push/pull`.
The prompt would only execute on a response status code 403 from the registry
after trying the value set in `RegistryAuth`. Docker Hub could return 404
instead or 429, which would never execute the prompt.

The UX regarding the prompt is also questionable since the user might
not actually want to authenticate with a registry and the CLI could fail fast
instead. The user can always run `docker login` or set the `DOCKER_AUTH_CONFIG`
environment variable to get authenticated.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-07-16 08:43:35 +02:00
Sebastiaan van Stijn 7d574b816d
Merge pull request #6180 from thaJeztah/truncate_id
remove uses of github.com/docker/docker/pkg/stringid
2025-07-15 14:03:18 +02:00
Sebastiaan van Stijn 0f2b709c7c
cli/command/container: diff: remove redundant validation and cleanup
client.ContainerDiff already validates the given container name/ID, and
produces an error when empty, so we don't have to check for this;
abba330bbf/client/container_diff.go (L13-L16)

While updating, also;

- remove the diffOptions type, as there were no other options, and make
  the container name/ID a string argument.
- fix camelCase nameing of dockerCLI

Before this patch:

    docker diff ""
    Container name cannot be empty

With this patch:

    docker diff ""
    invalid container name or ID: value is empty

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-15 01:08:29 +02:00
Sebastiaan van Stijn 7668b683d2
Merge pull request #6176 from thaJeztah/rm_use_AllowOverwriteDirWithFile
cli/command/container: don't set CopyToContainerOptions.AllowOverwriteDirWithFile
2025-07-14 23:17:34 +02:00
Sebastiaan van Stijn 53d02ece89
remove use of github.com/docker/docker/pkg/longpath
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-14 22:34:36 +02:00
Sebastiaan van Stijn 3600ebca76
remove uses of github.com/docker/docker/pkg/ioutils ReadCloserWrapper
It was the only utility we consumed from the package, and it's trivial
to implement, so let's create local copies of it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-14 22:09:31 +02:00
Sebastiaan van Stijn 9b047a501f
remove uses of pkg/stringid.GenerateRandomID()
This utility was only used for testing, and to generate a random
suffix for Dockerfiles. As we don't need the same contract as
pkg/stringid.GenerateRandomID() (not allow all-numeric IDs as they
would not be usable for hostnames), we can use a local test-utility,
and local implementation for the random suffix instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-14 20:11:07 +02:00
Sebastiaan van Stijn e0f4bc699c
cli/command/formatter: add TrunateID utility
We were depending on pkg/stringid to truncate IDs for presentation. While
traditionally, we used a fixed length for "truncated" IDs, this is not
a strict requirement (any ID-prefix should work, but conflicts may
happen on shorter IDs).

This patch adds a local `TruncateID()` utility in the formatter package;
it's currently using the same implementation and length as the
`stringid.TruncateID` function, but may diverge in future.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-14 20:10:56 +02:00
Sebastiaan van Stijn 1264a59779
Dockerfile: bump gotest.tools/gotestsum v1.12.3 (for go1.25)
full diff: https://github.com/gotestyourself/gotestsum/compare/v1.12.0...v1.12.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-13 17:50:03 +02:00
Sebastiaan van Stijn e6b8cc1c7d
Dockerfile: update buildx to v0.25.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-13 17:45:07 +02:00
Sebastiaan van Stijn 50fa436c21
Dockerfile: update compose to v2.38.2
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-13 17:43:50 +02:00
Sebastiaan van Stijn 0be687acc0
cli/command/container: don't set CopyToContainerOptions.AllowOverwriteDirWithFile
The `AllowOverwriteDirWithFile` option was added when reimplementing the
CLI using the API Client lib in [moby@1b2b91b]. Before that refactor, the
`noOverwriteDirNonDir` query argument [would be set unconditionally][1]
by the CLI, with no options to control the behavior.

It's unclear why the `noOverwriteDirNonDir` was implemented as opt-in (not
opt-out), as overwriting a file with a directory (or vice-versa) would
generally be unexpected behavior.

We're considering making `noOverwriteDirNonDir` unconditional on the daemon
side, and to deprecate the `AllowOverwriteDirWithFile` option. This patch
removes its use, as it was set to the default either way, and there's no
options to configure it from the CLI.

[1]: 8c9ad7b818/api/client/cp.go (L345-L346)
[moby@1b2b91b]: 1b2b91ba43

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-13 13:48:59 +02:00
Sebastiaan van Stijn c69d8bde4a
Merge pull request #6173 from vvoland/fix-anchor-cdi
docs: fix CDI device configuration anchor
2025-07-11 15:27:46 +02:00
Paweł Gronowski 8eac03d5fa
docs: fix CDI device configuration anchor
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-07-11 10:44:29 +02:00
Paweł Gronowski 578ccf607d
Merge pull request #6170 from thaJeztah/e2e_newline_check
e2e/global: TestPromptExitCode: check for trailing newline
2025-07-09 14:04:02 +02:00
Sebastiaan van Stijn 0c5e258f8a
e2e/global: TestPromptExitCode: check for trailing newline
Make the test slightly more permissive; we're looking for a trailing
newline, not necessarily an empty line.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-09 13:35:17 +02:00
Paweł Gronowski 30cad385b6
Merge pull request #6167 from vvoland/update-go
Update to go1.24.5
2025-07-09 01:23:29 +02:00
Paweł Gronowski 9bcc88611f
update to go1.24.5
- https://github.com/golang/go/issues?q=milestone%3AGo1.24.5+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.24.4...go1.24.5

This minor releases include 1 security fixes following the security policy:

- cmd/go: unexpected command execution in untrusted VCS repositories

    Various uses of the Go toolchain in untrusted VCS repositories can result in
    unexpected code execution. When using the Go toolchain in directories fetched
    using various VCS tools (such as directly cloning Git or Mercurial repositories)
    can cause the toolchain to execute unexpected commands, if said directory
    contains multiple VCS configuration metadata (such as a '.hg' directory in a Git
    repository). This is due to how the Go toolchain attempts to resolve which VCS
    is being used in order to embed build information in binaries and determine
    module versions.

    The toolchain will now abort attempting to resolve which VCS is being used if it
    detects multiple VCS configuration metadata in a module directory or nested VCS
    configuration metadata (such as a '.git' directoy in a parent directory and a
    '.hg' directory in a child directory). This will not prevent the toolchain from
    building modules, but will result in binaries omitting VCS related build
    information.

    If this behavior is expected by the user, the old behavior can be re-enabled by
    setting GODEBUG=allowmultiplevcs=1. This should only be done in trusted
    repositories.

    Thanks to RyotaK (https://ryotak.net) of GMO Flatt Security Inc for reporting
    this issue.

    This is CVE-2025-4674 and https://go.dev/issue/74380.

View the release notes for more information:
https://go.dev/doc/devel/release#go1.24.5

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-07-08 19:23:57 +02:00
Sebastiaan van Stijn 3302212263
Merge pull request #6163 from Benehiko/env-credential-warn
registry: warn of `DOCKER_AUTH_CONFIG` usage in login and logout
2025-07-08 15:33:07 +02:00
Alano Terblanche ccd5bd8d57
registry: warn of DOCKER_AUTH_CONFIG usage in login and logout
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-07-08 14:07:32 +02:00
Alano Terblanche dec07e6fdf
tui/note: add warning note type
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-07-08 14:07:22 +02:00
Sebastiaan van Stijn 28f19a9d65
Merge pull request #6162 from ArthurFlag/ENGDOCS-2807-cdi-docs-update
docs: cdi isn't experimental
2025-07-07 17:53:48 +02:00
Sebastiaan van Stijn 219e5ca4f2
Merge pull request #6165 from thaJeztah/bump_engine_28.3.1
vendor: github.com/docker/docker v28.3.1
2025-07-07 17:53:31 +02:00
ArthurFlag 7e040d91ef
docs: cdi is not experimental anymore
Signed-off-by: ArthurFlag <arthur.flageul@docker.com>
2025-07-07 16:10:30 +02:00
Sebastiaan van Stijn 76524e7d0e
vendor: github.com/docker/docker v28.3.1
no changes in vendored code

full diff: https://github.com/docker/docker/compare/v28.3.0...v28.3.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-07 15:52:29 +02:00
Alano Terblanche 3262107821
cli/config: export const dockerEnvConfig
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-07-04 14:04:38 +02:00
Sebastiaan van Stijn 8403869122
Merge pull request #6158 from thaJeztah/reduce_strslice
cli/command/container: remove redundant uses of strslice.StrSlice
2025-07-02 17:42:43 +02:00
Sebastiaan van Stijn 1fc7194554
Merge pull request #6159 from thaJeztah/hide_codecov
rename codecov.yml to .codecov.yml
2025-07-02 17:42:11 +02:00
Sebastiaan van Stijn fa2a7f1536
Merge pull request #6154 from thaJeztah/bump_engine
vendor: github.com/docker/docker v28.3.0
2025-07-02 17:41:49 +02:00
Sebastiaan van Stijn 350b3a6e25
Merge pull request #6160 from thaJeztah/fix_otel_debug_logs
cli/debug: fix OTELErrorHandler logging messages if there's no error
2025-07-02 17:41:26 +02:00
Sebastiaan van Stijn 4ea6fbf538
cli/debug: fix OTELErrorHandler logging messages if there's no error
I noticed this in a ticket in the compose issue tracker; with debug logging
enabled, the OTEL error-logger may be logging even if there's no error;

    DEBU[0000] Executing bake with args: [bake --file - --progress rawjson --metadata-file /tmp/compose-build-metadataFile-1203980021.json --allow fs.read=/home/user/dev/project --allow fs.read=/home/user/dev/project --allow fs.read=/home/user/dev/project/nginx --allow fs.read=/home/user/dev/project]
    TRAC[0000] Plugin server listening on @docker_cli_d8df486f78df3b7357995be71bf0cef6
    DEBU[0005] otel error                                    error="<nil>"
    ^CTRAC[0055] Closing plugin server
    TRAC[0055] Closing plugin server
    DEBU[0055] otel error                                    error="<nil>"
    DEBU[0055] otel error                                    error="<nil>"

Update the error-handler to not log if there's no error.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-02 11:59:05 +02:00
Sebastiaan van Stijn 74a896f18c
Merge pull request #6157 from ndeloof/use_api_socket
mount /var/run/docker.sock for --use-api-socket
2025-07-01 17:00:24 +02:00
Sebastiaan van Stijn 94f097da28
rename codecov.yml to .codecov.yml
Make it a hidden file. From the [CodeCov docs][1]:

> Can I name the file .codecov.yml?
>
> Yes, you can name the file `codecov.yml` or `.codecov.yml`. However, the
> file must still be located in the repository root, `dev/`, or `.github/`
> directories

[1]: https://docs.codecov.com/docs/codecov-yaml#can-i-name-the-file-codecovyml

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-01 16:20:54 +02:00
Sebastiaan van Stijn e7e238eb4b
cli/command/container: remove redundant uses of strslice.StrSlice
The strslice.StrSlice type is a string-slice with a custom JSON Unmarshal
function to provide backward-compatibility with older API requests (see
[moby@17d6f00] and [moby@ea4a067]).

Given that the type is assigned implicitly through the fields on HostConfig,
we can just use a regular []string instead.

[moby@17d6f00]: 17d6f00ec2
[moby@ea4a067]: ea4a06740b

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-01 10:09:54 +02:00
Nicolas De Loof 2ba7cb8b44
mount /var/run/docker.sock for --use-api-socket
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
2025-06-30 12:38:15 +02:00
Sebastiaan van Stijn 52e1e4fb21
vendor: github.com/docker/docker v28.3.0
no diff; same commit: https://github.com/docker/docker/compare/v28.3.0-rc.2...v28.3.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-30 09:35:21 +02:00
Sebastiaan van Stijn 7cbee73f19
Merge pull request #6147 from thaJeztah/connhelper_quote
cli/connhelper: quote ssh arguments to prevent shell injection
2025-06-25 17:21:12 +02:00
Paweł Gronowski ae6f8d0021
Merge pull request #6149 from vvoland/gha-tags
gha/bin-image: add major and minor version image tags
2025-06-25 14:35:11 +00:00
Paweł Gronowski 70867e7067
gha/bin-image: add major and minor version image tags
Adding image tags that follow the semver major and minor versions (e.g., `28`
and `28.3`) for the moby-bin images.

This makes it easier for users to reference the latest build within a
major or minor version series without having to know the exact
minor/patch version.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-06-24 23:35:10 +02:00
Paweł Gronowski 38b7060a21
Merge pull request #6148 from thaJeztah/vendor_rc2
vendor: github.com/docker/docker v28.3.0-rc.2
2025-06-24 15:37:19 +00:00
Sebastiaan van Stijn 2d46d162c1
vendor: github.com/docker/docker v28.3.0-rc.2
no diff; same commit, but tagged;
https://github.com/docker/docker/compare/265f70964794...v28.3.0-rc.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-24 16:35:29 +02:00
Sebastiaan van Stijn 88d1133224
cli/connhelper: quote ssh arguments to prevent shell injection
When connecting to a remote daemon through an ssh:// connection,
the CLI connects with the remote host using ssh, executing the
`docker system dial-stdio` command on the remote host to connect
to the daemon API's unix socket.

By default, the `docker system dial-stdio` command connects with the
daemon using the default location (/var/run/docker.sock), or the
location as configured on the remote host.

Commit 25ebf0ec9c (included in docker
CLI v24.0.0-rc.2 and higher) introduced a feature to allow the location
of the socket to be specified through the host connection string, for
example:

     DOCKER_HOST='ssh://example.test/run/custom-docker.sock'

The custom path is included as part of the ssh command executed from
the client machine to connect with the remote host. THe example above
would execute the following command from the client machine;

    ssh -o ConnectTimeout=30 -T -- example.test docker --host unix:///run/custom-docker.sock system dial-stdio

ssh executes remote commands in a shell environment, and no quoting
was in place, which allowed for a connection string to include additional
content, which would be expanded / executed on the remote machine.

For example, the following example would execute `echo hello > /hello.txt`
on the remote machine;

    export DOCKER_HOST='ssh://example.test/var/run/docker.sock $(echo hello > /hello.txt)'
    docker info
    # (output of docker info from the remote machine)

While this doesn't allow the user to do anything they're not already
able to do so (by directly using the same SSH connection), the behavior
is not expected, so this patch adds quoting to prevent such URLs from
resulting in expansion.

This patch updates the cli/connhelper and cli/connhelper/ssh package to
quote parameters used in the ssh command to prevent code execution and
expansion of variables on the remote machine. Quoting is also applied to
other parameters that are obtained from the DOCKER_HOST url, such as username
and hostname.

- The existing `Spec.Args()` method inthe cli/connhelper/ssh package now
  quotes arguments, and returns a nil slice when failing to quote. Users
  of this package should therefore check the returned arguments before
  consuming. This  method did not provide an error-return, and adding
  one would be a breaking change.
- A new `Spec.Command` method is introduced, which (unlike the `Spec.Args()`
  method) provides an error return. Users are recommended to use this new
  method instead of the `Spec.Args()` method.

Some minor additional changes in behavior are included in this patch;

- Connection URLs with a trailing slash (e.g. `ssh://example.test/`)
  would previously result in `unix:///` being used as custom socket
  path. After this patch, the trailing slash is ignored, and no custom
  socket path is used.
- Specifying a remote command is now required. When passing an empty
  remote command, `Spec.Args()` now results in a `nil` value to be
  returned (or an `no remote command specified` error when using
  `Spec.Comnmand()`.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-24 16:26:17 +02:00
Sebastiaan van Stijn 82eda48066
cli/connhelper/internal/syntax: fix linting issues
cli/connhelper/internal/syntax/parser.go:31:2: Duplicate words (the) found (dupword)
        // Note that it shares some features with Bash, due to the the shared
        ^
    cli/connhelper/internal/syntax/quote.go:48:1: cyclomatic complexity 35 of func `Quote` is high (> 16) (gocyclo)
    func Quote(s string, lang LangVariant) (string, error) {
    ^
    cli/connhelper/internal/syntax/quote.go:103:3: shadow: declaration of "offs" shadows declaration at line 56 (govet)
            offs := 0
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-24 16:24:34 +02:00
Sebastiaan van Stijn 52d2a9b5ae
cli/connhelper/internal/syntax: remove unused code from fork
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-24 16:24:29 +02:00
Sebastiaan van Stijn 64a9a6d0c8
cli/connhelper: add fork of mvdan.cc/sh/v3/syntax v3.10.0
This adds a local fork of the mvdan.cc/sh/v3/syntax package to provide the
Quote function without having to introduce additional (indirect) dependencies
of the mvdan.cc/sh module.

This commit does not compile as it references code not forked.

The following files were included:

- https://raw.githubusercontent.com/mvdan/sh/refs/tags/v3.10.0/syntax/quote.go
- https://raw.githubusercontent.com/mvdan/sh/refs/tags/v3.10.0/syntax/parser.go
- https://raw.githubusercontent.com/mvdan/sh/refs/tags/v3.10.0/LICENSE

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-24 10:02:53 +02:00
Sebastiaan van Stijn f03fb6c40b
Merge pull request #6146 from thaJeztah/bump_docker
vendor: github.com/docker/docker 265f70964794 (v28.3.0-rc.2)
2025-06-20 18:33:20 +02:00
Sebastiaan van Stijn 5bb0d7f70c
vendor: github.com/docker/docker 265f70964794 (v28.3.0-rc.2)
full diff: https://github.com/docker/docker/compare/v28.3.0-rc.1...265f709647947fb5a1adf7e4f96f2113dcc377bd

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-20 18:25:22 +02:00
Sebastiaan van Stijn 575d4af72f
vendor: github.com/docker/docker v28.3.0-rc.1
no diff: just tagged; https://github.com/docker/docker/compare/6a1fb46d4805...v28.3.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-20 17:43:37 +02:00
Sebastiaan van Stijn 4b202b9e2b
Merge pull request #6141 from thaJeztah/login_no_tty
prevent login prompt on registry operations with no TTY attached
2025-06-20 12:40:36 +02:00
Akihiro Suda 80d1959ee3
Merge pull request #6144 from thaJeztah/rm_top_level_remove
remove undocumented top-level "docker remove" command
2025-06-20 06:14:15 +09:00
Sebastiaan van Stijn 19a5c5c714
remove undocumented top-level "docker remove" command
This was introduced in 9b54d860cd,
which added `docker container remove` as alias for `docker container rm`.

However, due to the `NewRmCommand` being used both for adding the top-level
`docker rm` command and for adding the `docker container rm` command, it
also introduced a (hidden) top-level `docker remove` command;

    docker remove --help | head -n1
    Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]

The command was not documented, and did not appear in `--help` output,
nor was auto-complete provided;

    docker --help | grep remove

    docker r<TAB>
    rename               (Rename a container)  rm  (Remove one or more containers)  run  (Create and run a new container from an image)
    restart  (Restart one or more containers)  rmi     (Remove one or more images)

This patch adds a dedicated, non-exported `newRemoveCommand` to add sub-
commands for `docker container`, taking a similar approach as was done in
[moby@b993609d5a] for `docker image rm`.

With this patch applied, the hidden command is no longer there, but
the `docker rm`, `docker container rm`, and `docker container remove`
commands stay functional as intended;

    docker remove foo
    docker: unknown command: docker remove

    Run 'docker --help' for more information

    docker rm --help | head -n1
    Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]
    docker container rm --help | head -n1
    Usage:  docker container rm [OPTIONS] CONTAINER [CONTAINER...]
    docker container remove --help | head -n1
    Usage:  docker container rm [OPTIONS] CONTAINER [CONTAINER...]

[moby@b993609d5a]: b993609d5a

Reported-by: Lorenzo Buero <138243046+LorenzoBuero@users.noreply.github.com>
Co-authored-by: Lorenzo Buero <138243046+LorenzoBuero@users.noreply.github.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-19 15:42:54 +02:00
Sebastiaan van Stijn c88268681e
prevent login prompt on registry operations with no TTY attached
When pulling or pushing images, the CLI could prompt for a password
if the push/pull failed and the registry returned a 401 (Unauthorized)

Ironically, this feature did not work when using Docker Hub (and possibly
other registries using basic auth), due to some custom error handling added
in [moby@19a93a6e3d42], which also discards the registry's status code,
changing it to a 404;

    curl -v -XPOST --unix-socket /var/run/docker.sock 'http://localhost/v1.50/images/create?fromImage=docker.io%2Fexample%2Fprivate&tag=latest'
    ...
    < HTTP/1.1 404 Not Found
    < Content-Type: application/json
    ...
    {"message":"pull access denied for example/private, repository does not exist or may require 'docker login'"}

And due to a bug, other registries (not using basic auth) returned a generic
error, which resulted in a 500 Internal Server Error. That bug was fixed in
docker 28.2, now returning the upstream status code and trigger an interactive
prompt;

    docker pull icr.io/my-ns/my-image:latest
    Please login prior to pull:
    Username:

This prompt would be triggered unconditionally, also if the CLI was run
non-interactively and no TTY attached;

    docker pull icr.io/my-ns/my-image:latest < /dev/null
    Please login prior to pull:
    Username:

With this PR, no prompt is shown ;

    # without STDIN attached
    docker pull icr.io/my-ns/my-image:latest < /dev/null
    Error response from daemon: error from registry: Authorization required. See https://cloud.ibm.com/docs/Registry?topic=Registry-troubleshoot-auth-req - Authorization required. See https://cloud.ibm.com/docs/Registry?topic=Registry-troubleshoot-auth-req

For now, the prompt is still shown otherwise;

    docker pull icr.io/my-ns/my-image:latest

    Login prior to pull:
    Username: ^C

[moby@19a93a6e3d42]: 19a93a6e3d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-19 10:25:27 +02:00
Paweł Gronowski 747cb4448f
Merge pull request #6140 from vvoland/image-tree-used
image/tree: Fix top image chip detection
2025-06-18 20:13:03 +00:00
Paweł Gronowski 23fe9ec244
image/tree: Fix top image chip detection
Currently, image tree visualization doesn't properly detect chips for
parent images, only looking at child images. This patch fixes the issue
by checking both parent and child images when determining which chips to
display in the tree view.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-06-18 20:18:58 +02:00
Paweł Gronowski 51025e12e5
Merge pull request #6008 from Benehiko/env-credentials-store
Use `DOCKER_AUTH_CONFIG` env as credential store
2025-06-18 18:07:07 +00:00
Alano Terblanche 9b83d5bbf9
Use `DOCKER_AUTH_CONFIG` env as credential store
This patch enables the CLI to natively pick up the `DOCKER_AUTH_CONFIG`
environment variable and use it as a credential store.

The `DOCKER_AUTH_CONFIG` value should be a JSON object and must store
the credentials in a base64 encoded string under the `auth` key.
Specifying additional fields will cause the parser to fail.

For example:
`printf "username:pat" | openssl base64 -A`

`export DOCKER_AUTH_CONFIG='{
  "auths": {
    "https://index.docker.io/v1/": {
      "auth": "aGk6KTpkY2tyX3BhdF9oZWxsbw=="
    }
  }
}'`

Credentials stored in `DOCKER_AUTH_CONFIG` would take precedence over any
credential stored in the file store (`~/.docker/config.json`) or native store
(credential helper).

Destructive actions, such as deleting a credential would result in a noop if
found in the environment credential. Credentials found in the file or
native store would get removed.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-06-18 18:55:42 +02:00
Sebastiaan van Stijn ab2d683f61
Merge pull request #6137 from thaJeztah/execconfig_detach
cli/command/container: remove use of ExecOptions.Detach as intermediate
2025-06-17 14:22:28 +02:00
Sebastiaan van Stijn 3664c08b73
Merge pull request #6138 from thaJeztah/bump_swarmkit
vendor: github.com/moby/swarmkit/v2 v2.0.0
2025-06-17 14:21:47 +02:00
Sebastiaan van Stijn cccf6d8cc4
vendor: github.com/moby/swarmkit/v2 v2.0.0
full diff: https://github.com/moby/swarmkit/compare/8c1959736554...v2.0.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-17 13:26:30 +02:00
Sebastiaan van Stijn 50da0ad9df
cli/command/container: remove use of ExecOptions.Detach as intermediate
This field was added in [moby@5130fe5d38837302e], which
added it for use as intermediate struct when parsing CLI flags (through
`runconfig.ParseExec`) in [moby@c786a8ee5e9db8f5f].

Commit [moby@9d9dff3d0d9e92adf] rewrote the CLI to use
Cobra, and as part of this introduced a separate `execOptions` type in
`api/client/container`, however the ExecOptions.Detach field was still
used as intermediate field to store the flag's value.

Given that the client doesn't use this field, let's remove its use to
prevent giving the impression that it's used anywhere.

[moby@5130fe5d38837302e]: 5130fe5d38
[moby@c786a8ee5e9db8f5f]: c786a8ee5e
[moby@9d9dff3d0d9e92adf]: 9d9dff3d0d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-17 12:53:44 +02:00
Sebastiaan van Stijn dbb5872b69
Merge pull request #6135 from thaJeztah/fix_login_message
cli/command: RegistryAuthenticationPrivilegedFunc: fix hints for login
2025-06-16 14:35:56 +02:00
Sebastiaan van Stijn e2632c5c4f
cli/command: RegistryAuthenticationPrivilegedFunc: fix hints for login
The RegistryAuthenticationPrivilegedFunc has some conditional logic to
add additional hints when logging in to the default (Docker Hub) registry.
Commit 9f4165ccb8 inadvertently passed the
wrong variable to PromptUserForCredentials, which caused it to show the
additional hints for Docker Hub.

Before this patch, hints were printed for the default (docker hub) registry;

    docker pull icr.io/my-ns/my-image:latest

    Login prior to pull:
    Log in with your Docker ID or email address to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com/ to create one.
    You can log in with your password or a Personal Access Token (PAT). Using a limited-scope PAT grants better security and is required for organizations using SSO. Learn more at https://docs.docker.com/go/access-tokens/

    Username:

With this patch, those hints are omitted;

    docker pull icr.io/my-ns/my-image:latest

    Login prior to pull:
    Username:

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-16 12:14:53 +02:00
Paweł Gronowski f53bb8882f
Merge pull request #6131 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.3.0-dev (6a1fb46d4805)
2025-06-13 16:29:11 +00:00
Paweł Gronowski 4cb0695b49 vendor: github.com/docker/docker v28.3.0-dev (6a1fb46d4805)
full diff: https://github.com/docker/docker/compare/v28.2.2...6a1fb46d4805

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-06-13 18:23:51 +02:00
Paweł Gronowski 3ce5130af6
Merge pull request #6132 from thaJeztah/replace_evt
cli/command/container: replace uses of deprecated event.Status field
2025-06-13 16:23:08 +00:00
Sebastiaan van Stijn 99d4d1f386
cli/command/container: replace uses of deprecated event.Status field
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-13 18:18:28 +02:00
Paweł Gronowski 398fa5aa70
Merge pull request #6130 from thaJeztah/bump_version
bump version to v28.3.0-dev
2025-06-13 13:42:56 +00:00
Sebastiaan van Stijn e225d51919
bump version to v28.3.0-dev
This file is only used as default if no version is specified. We
should probably get rid of this, but let's update it to better
reflect the version that developer builds are building.

d48fb9f9f7/docker.Makefile (L22)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-13 14:11:56 +02:00
Sebastiaan van Stijn 9cc2a2bf2d
Merge pull request #6129 from vvoland/docs-deprecated
docs: deprecate empty Config fields in image inspect API
2025-06-13 14:10:48 +02:00
Paweł Gronowski 181563ee99
docs: deprecate empty Config fields in image inspect API
Image config fields like Cmd, Entrypoint, Env, etc. will be omitted from
/images/{name}/json response when empty, starting in v29.0.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-06-13 13:48:07 +02:00
Paweł Gronowski 082d23d12d
Merge pull request #6127 from thaJeztah/bump_deps
vendor: update buildkit and containerd dependencies
2025-06-12 13:20:31 +00:00
Sebastiaan van Stijn 59e34093bc
vendor: otel v1.35.0, otel/contrib v0.60.0, grpc v1.72.2
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-12 14:16:23 +02:00
Sebastiaan van Stijn a76643bca3
vendor: github.com/prometheus/client_golang v1.22.0
full diff: https://github.com/prometheus/client_golang/compare/v1.20.5...v1.22.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-12 14:12:33 +02:00
Sebastiaan van Stijn f6985b7a27
vendor: google.golang.org/protobuf v1.36.6
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-12 14:11:07 +02:00
Sebastiaan van Stijn bab8478ef3
vendor: golang.org/x/sys v0.33.0
full diff: https://github.com/golang/sys/compare/v0.32.0...v0.33.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-12 14:09:24 +02:00
Sebastiaan van Stijn 9f82d4a791
vendor: golang.org/x/sync v0.14.0
full diff: https://github.com/golang/sync/compare/v0.13.0...v0.14.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-12 13:54:57 +02:00
Cesar Talledo 0ba4362d69 Update markdown docs to indicate multi-platform support in image load/save.
Signed-off-by: Cesar Talledo <cesar.talledo@docker.com>
2025-06-10 16:42:39 -07:00
Cesar Talledo 8993f54fc3 Add support for multiple platforms in docker image save
Signed-off-by: Cesar Talledo <cesar.talledo@docker.com>
2025-06-10 16:34:07 -07:00
Cesar Talledo 38b99adc10 Add support for multiple platforms in docker image load.
Signed-off-by: Cesar Talledo <cesar.talledo@docker.com>
2025-06-10 16:34:02 -07:00
Sebastiaan van Stijn 8b8f558b83
Merge pull request #6124 from vvoland/update-go
update to go1.24.4
2025-06-10 15:12:26 +02:00
Sebastiaan van Stijn 5487986681
Merge pull request #6123 from ndeloof/pluginserver
only close plugin server if actually created
2025-06-10 15:12:06 +02:00
Nicolas De Loof b9c563a581
only close plugin server if actually created
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
2025-06-10 14:57:19 +02:00
Paweł Gronowski fe7fc2ff7f
update to go1.24.4
- https://github.com/golang/go/issues?q=milestone%3AGo1.24.4+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.24.3...go1.24.4

This release includes 3 security fixes following the security policy:

- net/http: sensitive headers not cleared on cross-origin redirect

    Proxy-Authorization and Proxy-Authenticate headers persisted on cross-origin redirects potentially leaking sensitive information.

    Thanks to Takeshi Kaneko (GMO Cybersecurity by Ierae, Inc.) for reporting this issue.

    This is CVE-2025-4673 and Go issue https://go.dev/issue/73816.

- os: inconsistent handling of O_CREATE|O_EXCL on Unix and Windows

    os.OpenFile(path, os.O_CREATE|O_EXCL) behaved differently on Unix and Windows systems when the target path was a dangling symlink. On Unix systems, OpenFile with O_CREATE and O_EXCL flags never follows symlinks. On Windows, when the target path was a symlink to a nonexistent location, OpenFile would create a file in that location.

    OpenFile now always returns an error when the O_CREATE and O_EXCL flags are both set and the target path is a symlink.

    Thanks to Junyoung Park and Dong-uk Kim of KAIST Hacking Lab for discovering this issue.

    This is CVE-2025-0913 and Go issue https://go.dev/issue/73702.

- crypto/x509: usage of ExtKeyUsageAny disables policy validation

    Calling Verify with a VerifyOptions.KeyUsages that contains ExtKeyUsageAny unintentionally disabledpolicy validation. This only affected certificate chains which contain policy graphs, which are rather uncommon.

    Thanks to Krzysztof Skrzętnicki (@Tener) of Teleport for reporting this issue.

    This is CVE-2025-22874 and Go issue https://go.dev/issue/73612.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-06-09 16:25:41 +02:00
Sebastiaan van Stijn 9e506545fd
Merge pull request #6120 from thaJeztah/fix_url
docs: fix link to live-restore
2025-06-02 13:02:40 +02:00
Sebastiaan van Stijn 3c1bbfd82f
docs: fix link to live-restore
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-06-02 12:56:04 +02:00
Sebastiaan van Stijn 0bfd4c9f29
Merge pull request #6119 from thaJeztah/bump_engine
vendor: github.com/docker/docker v28.2.2
2025-06-02 10:15:52 +02:00
Sebastiaan van Stijn 3b25977f82 Merge pull request #50110 from thaJeztah/remove_import_comments
all: remove // import comments
2025-05-30 20:35:54 +02:00
Sebastiaan van Stijn d8f09a1b75
Merge pull request #6117 from vvoland/binimage-nosha
gha/bin-image: Don't push sha tags
2025-05-30 17:42:22 +02:00
Sebastiaan van Stijn 473b248260
vendor: github.com/docker/docker v28.2.2
no diff; same commit, but tagged:
https://github.com/docker/docker/compare/45873be4ae3f...v28.2.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-30 17:37:57 +02:00
Sebastiaan van Stijn 342f8bca25 builder: remove // import comments
These comments were added to enforce using the correct import path for
our packages ("github.com/docker/docker", not "github.com/moby/moby").
However, when working in go module mode (not GOPATH / vendor), they have
no effect, so their impact is limited.

Remove these imports in preparation of migrating our code to become an
actual go module.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-30 15:59:11 +02:00
Paweł Gronowski b2d63d17af
gha/bin-image: Don't push sha tags
This change eliminates the automatic creation of image tags in the
format `dockereng/cli-bin:sha-ad132f5` for every push.

They're not too useful, produce noise and use a lot of space.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-30 12:00:29 +02:00
Paweł Gronowski e6534b4eb7
Merge pull request #6116 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.2.2-dev (45873be4ae3f)
2025-05-30 09:39:08 +00:00
Paweł Gronowski 5c3128e95e
vendor: github.com/docker/docker v28.2.2-dev (45873be4ae3f)
full diff: 0e2cc22d36...45873be4ae

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-30 11:15:35 +02:00
Paweł Gronowski 879ac3f88f
Merge pull request #6110 from thaJeztah/bump_engine
vendor: github.com/docker/docker 0e2cc22d36ae (v28.2-dev)
2025-05-28 13:17:56 +00:00
Sebastiaan van Stijn 92fa1e1fc9
vendor: github.com/docker/docker 0e2cc22d36ae (v28.2-dev)
no changes in vendored code

full diff: 26db31fdab...0e2cc22d36

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-28 15:05:58 +02:00
Sebastiaan van Stijn 4bec3a6795
Merge pull request #6114 from thaJeztah/deprecate_non_compliant_registries
docs: deprecated: fallback for non-OCI-compliant registries is removed
2025-05-28 14:28:52 +02:00
Paweł Gronowski a007d1ae24
Merge pull request #6113 from thaJeztah/config_suppress_err
cli/config/configfile: explicitly ignore error
2025-05-28 12:08:37 +00:00
Sebastiaan van Stijn bbfbd54f4d
docs: deprecated: fallback for non-OCI-compliant registries is removed
GitHub deprecated the legacy registry, and it was [sunset on Feb 24th, 2025][1]
in favor of GitHub Container Registry (GHCR) (ghcr.io), so the fallback
was removed.

[1]: https://github.blog/changelog/2025-01-23-legacy-docker-registry-closing-down/

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-28 10:05:40 +02:00
Sebastiaan van Stijn 2d21e1f7a5
cli/config/configfile: explicitly ignore error
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-28 09:55:33 +02:00
Sebastiaan van Stijn bc9be0bdea
Merge pull request #6112 from thaJeztah/bump_tools
Dockerfile: bump buildx v0.24.0, compose v2.36.2
2025-05-28 09:09:24 +02:00
Sebastiaan van Stijn 3fe7dc5cb4
Dockerfile: update compose to v2.36.2
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-27 22:50:20 +02:00
Sebastiaan van Stijn 9eae2a8976
Dockerfile: update buildx to v0.24.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-27 22:49:34 +02:00
Sebastiaan van Stijn a29e53dab7
Merge pull request #6111 from thaJeztah/update_deprecations
docs: deprecated: update status for non-standard fields in image inspect
2025-05-27 16:57:52 +02:00
Sebastiaan van Stijn da0c976fb0
docs: deprecated: update status for non-standard fields in image inspect
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-27 16:14:00 +02:00
Sebastiaan van Stijn 17dc2880fa
Merge pull request #6109 from thaJeztah/image_rm_platform
image rm: add --platform option
2025-05-27 12:11:26 +02:00
Sebastiaan van Stijn bb0ca9f9ef
image rm: add --platform option
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-27 10:58:11 +02:00
Sebastiaan van Stijn f567263802
Merge pull request #6099 from thaJeztah/bump_engine
vendor: github.com/docker/docker 26db31fdab62 (v28.2-dev)
2025-05-27 10:49:43 +02:00
Sebastiaan van Stijn 7775f01caa
vendor: github.com/docker/docker 26db31fdab62 (v28.2-dev)
full diff: https://github.com/docker/docker/compare/v28.2.0-rc.2...26db31fdab628a2345ed8f179e575099384166a9

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-27 09:20:06 +02:00
Paweł Gronowski 908ff04d6e
Merge pull request #6108 from thaJeztah/bump_engine_28.2
vendor: github.com/docker/docker v28.2.0-rc.2
2025-05-26 13:17:15 +00:00
Sebastiaan van Stijn 519bc2daa1
vendor: github.com/docker/docker v28.2.0-rc.2
no changes in vendored code

full diff: https://github.com/docker/docker/compare/f4ffeb8c38b3...v28.2.0-rc.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-26 14:06:52 +02:00
Paweł Gronowski b2c4452acb
Merge pull request #6101 from thaJeztah/deprecated_api_versions_removed
docs: deprecated: mark API < v1.24 as "removed"
2025-05-22 12:09:34 +00:00
Sebastiaan van Stijn 3e287df661
Merge pull request #6100 from thaJeztah/fluentd_async_connect_removed
docs: deprecated: mark `fluentd-async-connect` as "removed"
2025-05-22 14:09:24 +02:00
Paweł Gronowski f1fb3e3011
Merge pull request #5282 from willww64/fix-configfile-relative-symlink
correctly handle configuration file saving when it is a relative symlink
2025-05-22 12:08:40 +00:00
Sebastiaan van Stijn 9c8666c106
docs: deprecated: mark API < v1.24 as "removed"
Support for API versions lower than v1.24 was removed in v26.0.
The DOCKER_MIN_API_VERSION environment-variable is still present
in the docker daemon, but can currently only be used to raise the
minimum version.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 13:37:44 +02:00
Sebastiaan van Stijn 21d0466ff1
docs: deprecated: mark `fluentd-async-connect` as "removed"
The daemon still has migration code in place, but no longer accepts
the option for new containers, so marking it as "removed";
49ec488036

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 13:28:18 +02:00
Sebastiaan van Stijn 1d3b933ac3
Merge pull request #6098 from thaJeztah/deprecated_inspect_fields
docs: deprecated: set Container and ContainerConfig fields to "removed"
2025-05-22 11:54:10 +02:00
Sebastiaan van Stijn 649d088ddf
Merge pull request #6096 from thaJeztah/graphdriver_plugin_deprecation
docs: update deprecation status of graphdriver-plugins to "removed"
2025-05-22 11:49:53 +02:00
Paweł Gronowski e135563c1f
Merge pull request #6097 from vvoland/28.x
vendor: github.com/docker/docker v28.2.0-dev (f4ffeb8c38b3)
2025-05-22 09:48:20 +00:00
Sebastiaan van Stijn 026ae7a11f
docs: deprecated: set Container and ContainerConfig fields to "removed"
These fields have been removed in v26.0 (API v1.45 and up), and are always
omitted when using the containerd image store;
03cddc62f4

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 11:45:57 +02:00
Paweł Gronowski 681c705be6
vendor: github.com/docker/docker v28.2.0-dev (f4ffeb8c38b3)
full diff: b590eff717...f4ffeb8c38

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-22 11:38:51 +02:00
Sebastiaan van Stijn bdd994b79a
docs: update deprecation status of graphdriver-plugins to "removed"
This functionality, was removed and the DOCKERD_DEPRECATED_GRAPHDRIVER_PLUGINS
no longer can be used in v28.0;
42ca9154e9

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 11:29:37 +02:00
Will Wang 1015d15621
fix bug with config file being a relative symlink
- use filepath.EvalSymlink instead of check with filepath.IsAbs
- allow for dangling symlinks
- extract path from error when NotExist error occurs

Co-authored-by: Paweł Gronowski <me@woland.xyz>
Co-authored-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Will Wang <willww64@gmail.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 11:11:07 +02:00
Sebastiaan van Stijn ae922ec177
Merge pull request #6092 from thaJeztah/hijack_oncefunc
cli/command/container: hijackedIOStreamer.setupInput: use sync.OnceFunc
2025-05-22 10:02:11 +02:00
Sebastiaan van Stijn 881c68f690
Merge pull request #4966 from Benehiko/relative-mount-path
feat: relative parent paths on bind mount src
2025-05-22 08:38:06 +02:00
Alano Terblanche 761285bfee
feat: relative parent paths on bind mount src
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-05-22 08:15:32 +02:00
Sebastiaan van Stijn f23ec25a12
Merge pull request #6095 from thaJeztah/update_schema1_deprecation
docs: move deprecation status of legacy schema1 images to "removed"
2025-05-22 08:06:45 +02:00
Sebastiaan van Stijn 565b0a2822
Merge pull request #6094 from thaJeztah/fix_isautomated_status
docs: fix deprecation status for IsAutomated
2025-05-22 07:58:53 +02:00
Sebastiaan van Stijn 4be9afb801
Merge pull request #6086 from thaJeztah/golangci_tweaks
golangci-lint: enable more linters, and some minor linting fixes
2025-05-22 07:57:53 +02:00
Sebastiaan van Stijn f05025caf9
docs: move deprecation status of legacy schema1 images to "removed"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 01:10:13 +02:00
Sebastiaan van Stijn 32a8f4c420
docs: fix deprecation status for IsAutomated
Follow-up to 6e4315f599, where
I forgot to update the status column.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-22 00:34:13 +02:00
Paweł Gronowski 68ef98d801
Merge pull request #6093 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.2.0-dev (b590eff717b3)
2025-05-21 17:51:04 +00:00
Paweł Gronowski 63f2984336
vendor: github.com/docker/docker v28.2.0-dev (b590eff717b3)
full diff: 8601b22f5d...b590eff717

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-21 19:45:33 +02:00
Sebastiaan van Stijn 0ee20b8543
Merge pull request #5995 from vvoland/swarm-init-cacert
swarm/init: Fix `--external-ca` ignoring `cacert` option
2025-05-21 18:31:14 +02:00
Paweł Gronowski c07cd8aaad
Merge pull request #6091 from thaJeztah/remove_deprecated_isautomated
search: remove deprecated "IsAutomated" placeholder
2025-05-21 15:43:36 +00:00
Sebastiaan van Stijn bf2eea31b5
cli/command/container: hijackedIOStreamer.setupInput: use sync.OnceFunc
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-21 17:34:51 +02:00
Sebastiaan van Stijn 6e4315f599
search: remove deprecated "IsAutomated" placeholder
IsAutomated was deprecated in 4fc3f0e6f6
(docker v25.0), and marked for removal in docker 26.0 (which we missed).
This removes it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-21 17:13:59 +02:00
Paweł Gronowski 97e060e7b1
Merge pull request #6042 from thaJeztah/carry_5804_docker_ps_platform
docker ps: add "Platform" as formatting option
2025-05-21 12:28:57 +00:00
Sebastiaan van Stijn 67c0be4b05
docker ps: allow formatting as JSON
With this patch:

    docker ps --format 'table {{.Names}}\t{{.Platform}}'
    NAMES                    PLATFORM
    optimistic_nightingale   linux/arm64
    mycontainer              linux/arm64/v8
    trusting_goldstine       linux/arm64

    docker ps --format '{{.Platform}}'
    linux/arm64
    linux/arm64/v8
    linux/arm64

    docker ps --format '{{json .Platform}}'
    {"architecture":"arm64","os":"linux"}
    {"architecture":"arm64","os":"linux","variant":"v8"}
    {"architecture":"arm64","os":"linux"}

    docker ps --format 'json'
    {"Command":"\"/bin/bash\"","CreatedAt":"2025-05-13 10:12:19 +0000 UTC","ID":"e8b3b2d604f1","Image":"docker-cli-dev","Labels":"desktop.docker.io/binds/0/Source=/Users/thajeztah/go/src/github.com/docker/cli,desktop.docker.io/binds/0/SourceKind=hostFile,desktop.docker.io/binds/0/Target=/go/src/github.com/docker/cli,desktop.docker.io/mounts/0/Source=/var/run/docker.sock,desktop.docker.io/mounts/0/SourceKind=dockerSocketProxied,desktop.docker.io/mounts/0/Target=/var/run/docker.sock,desktop.docker.io/ports.scheme=v2","LocalVolumes":"1","Mounts":"/host_mnt/User…,docker-cli-dev…,/run/host-serv…","Names":"optimistic_nightingale","Networks":"bridge","Platform":{"architecture":"arm64","os":"linux"},"Ports":"","RunningFor":"38 minutes ago","Size":"0B","State":"running","Status":"Up 38 minutes"}
    {"Command":"\"/docker-entrypoint.…\"","CreatedAt":"2025-05-13 09:58:01 +0000 UTC","ID":"c93b808dd54e","Image":"nginx:alpine","Labels":"desktop.docker.io/ports.scheme=v2,maintainer=NGINX Docker Maintainers \u003cdocker-maint@nginx.com\u003e","LocalVolumes":"0","Mounts":"","Names":"mycontainer","Networks":"bridge","Platform":{"architecture":"arm64","os":"linux","variant":"v8"},"Ports":"80/tcp","RunningFor":"53 minutes ago","Size":"0B","State":"running","Status":"Up 53 minutes"}
    {"Command":"\"/usr/bin/gotty --ti…\"","CreatedAt":"2025-05-13 07:31:18 +0000 UTC","ID":"cbb981b06e46","Image":"thajeztah/dockershell:latest","Labels":"desktop.docker.io/ports.scheme=v2,com.thajeztah.docker-shell=1","LocalVolumes":"0","Mounts":"","Names":"trusting_goldstine","Networks":"bridge","Platform":{"architecture":"arm64","os":"linux"},"Ports":"0.0.0.0:55000-\u003e8080/tcp","RunningFor":"3 hours ago","Size":"0B","State":"running","Status":"Up 3 hours"}

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-21 12:44:38 +02:00
Jonathan A. Sternberg 7aa6c79c0a
docker ps: add "Platform" as formatting option
docker ps --format 'table {{.ID}}\t{{.Image}}{{.Command}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}\t{{.Names}}\t{{.Platform}}'
    CONTAINER ID   IMAGECOMMAND                CREATED          STATUS          PORTS     NAMES              PLATFORM
    e422855eac55   docker-cli-dev"/bin/bash"   12 minutes ago   Up 12 minutes             strange_jennings   linux/arm64

Signed-off-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-21 12:43:01 +02:00
Sebastiaan van Stijn af090512a6
Merge pull request #6084 from thaJeztah/bump_engine
vendor: github.com/docker/docker 8601b22f5db5 (v28.2-dev)
2025-05-20 10:57:13 +02:00
Sebastiaan van Stijn 067587bf15
Merge pull request #6085 from thaJeztah/bump_cli_docs_tool
vendor: github.com/docker/cli-docs-tool v0.10.0
2025-05-20 09:30:29 +02:00
Sebastiaan van Stijn ed5d9757c9
vendor: github.com/docker/docker 8601b22f5db5 (v28.2-dev)
full diff: https://github.com/docker/docker/compare/v28.2.0-rc.1...8601b22f5db511354d643a7722d11d33aa7ae13f

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 22:47:14 +02:00
Sebastiaan van Stijn 89f38282fd
vendor: github.com/docker/docker v28.2.0-rc.1
no diff: same commit, but tagged

full diff: https://github.com/docker/docker/compare/7937f0846c13...v28.2.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 22:40:55 +02:00
Sebastiaan van Stijn 9d027dff40
Dockerfile: update golangci-lint to v2.1.5
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:16:23 +02:00
Sebastiaan van Stijn d1e9946ab8
golangci-lint: enable more linters
Enables the asasalint, exptostd, fatcontext, gocheckcompilerdirectives,
iface, makezero, and spancheck linters.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:14:13 +02:00
Sebastiaan van Stijn 615ffee13b
golangci-lint: enable nosprintfhostport linter
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:14:12 +02:00
Sebastiaan van Stijn c1313a92a0
golangci-lint: enable makezero linter
cli/command/container/formatter_stats_test.go:339:11: append to slice `stats` with non-zero initialized length (makezero)
            stats = append(stats, entry)
                    ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:14:12 +02:00
Sebastiaan van Stijn 18e911c958
cli/command/container: TestContainerStatsContextWriteTrunc: use subtests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:14:12 +02:00
Sebastiaan van Stijn d65f0c9bbf
golangci-lint: enable exhaustive linter
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:14:04 +02:00
Sebastiaan van Stijn b64d9b3b19
golangci-lint: replace nilerr for nilnesserr
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:07:15 +02:00
Sebastiaan van Stijn 062ad57ce2
golangci-lint: enable mirror linter
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 20:07:05 +02:00
Sebastiaan van Stijn 915b3fe992
vendor: github.com/docker/cli-docs-tool v0.10.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 17:44:21 +02:00
Sebastiaan van Stijn 2ef9ab4494
golangci-lint: align comments
Format comments to be the same as in moby/moby for easier comparing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 15:36:11 +02:00
Sebastiaan van Stijn d14b7e8d09
golangci-lint: remove exclusions for ST1020, ST1022
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 15:33:44 +02:00
Sebastiaan van Stijn 0ffb72419a
Merge pull request #6083 from thaJeztah/bump_engine
vendor: github.com/docker/docker 7937f0846c13 (master, v28.x dev)
2025-05-19 14:27:28 +02:00
Sebastiaan van Stijn 4665398a06
vendor: github.com/docker/docker 7937f0846c13 (master, v28.x dev)
full diff: 4b9f0707a0...7937f0846c

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-19 14:07:50 +02:00
Sebastiaan van Stijn d1857decba
Merge pull request #6081 from thaJeztah/unify_cli_opts
cli/command, cli-plugins/plugin: some cleanups in WithInitializeClient, withPluginClientConn
2025-05-19 11:28:11 +02:00
Sebastiaan van Stijn 240b06991b
cli-plugins/plugin: rewrite withPluginClientConn w/ WithAPIClient
The WithInitializeClient looks redundant altogether, so let's
rewrite this function to not depend on it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 23:36:20 +02:00
Sebastiaan van Stijn 7b1f889074
cli/command: make WithInitializeClient a wrapper for WithAPIClient
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 23:31:53 +02:00
Sebastiaan van Stijn 0d82ff4ae1
cli/command: move WithInitializeClient to other options
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 23:29:52 +02:00
Paweł Gronowski 8e5fb5bd07
Merge pull request #6080 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.2.0-dev (4b9f0707a039)
2025-05-16 19:22:18 +00:00
Paweł Gronowski 8c8a81eaea
vendor: github.com/docker/docker v28.2.0-dev (4b9f0707a039)
full diff: b45aa469ca...4b9f0707a0

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-16 21:12:49 +02:00
Sebastiaan van Stijn 0674a0085a
Merge pull request #6079 from thaJeztah/less_errdefs
remove uses of github.com/docker/docker/errdefs
2025-05-16 21:06:21 +02:00
Sebastiaan van Stijn 1058b22800
cli/command: remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:30:00 +02:00
Sebastiaan van Stijn eebf6824fc
cli/command/plugin: remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:30:00 +02:00
Sebastiaan van Stijn 214d2bfb6b
cli/command/image: remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:30:00 +02:00
Sebastiaan van Stijn c4009463a7
cli/command/builder: remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:30:00 +02:00
Sebastiaan van Stijn 3d68a39015
cli/command/system: remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:30:00 +02:00
Sebastiaan van Stijn 251725676e
cli/command/trust: remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:29:50 +02:00
Sebastiaan van Stijn 1168edb259
cli/command/volume: use stdlib errors, remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:29:39 +02:00
Sebastiaan van Stijn 981e75e0f4
cli/command/network: use stdlib errors, remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:28:59 +02:00
Sebastiaan van Stijn 3382ee3e99
cli/command/context: use stdlib errors, remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:18:41 +02:00
Sebastiaan van Stijn b883976531
cli/context/store: use stdlib errors, remove errdefs uses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:18:40 +02:00
Sebastiaan van Stijn bfc6aeca4a
cli/command/container: define local errors instead of errdefs
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 20:18:40 +02:00
Sebastiaan van Stijn eee0cf9117
Merge pull request #6078 from vvoland/info-devices
system/info: Show discovered devices
2025-05-16 19:59:07 +02:00
Paweł Gronowski f6a077a831
system/info: Show discovered devices
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-16 19:35:29 +02:00
Paweł Gronowski be03dc9ce7
vendor: github.com/docker/docker v28.2.0-dev (b45aa469cac7)
full diff: c04dec1143...b45aa469ca

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-16 19:35:27 +02:00
Sebastiaan van Stijn 628b2f1a81
Merge pull request #6074 from thaJeztah/c8d_errdefs_is
switch to github.com/containerd/errdefs for error-matching
2025-05-16 18:11:26 +02:00
Sebastiaan van Stijn d43b7daeb7
Merge pull request #6075 from thaJeztah/bump_engine
vendor: github.com/docker/docker c04dec11437f (master, v28.x dev)
2025-05-16 17:27:37 +02:00
Sebastiaan van Stijn 7e609d491b
vendor: github.com/docker/docker c04dec11437f (master, v28.x dev)
full diff: fd1a78e0a3...c04dec1143

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 17:01:28 +02:00
Sebastiaan van Stijn d956110288
Merge pull request #1581 from thaJeztah/dont_use_tls_for_sockets
Don't use TLS for socket connections
2025-05-16 15:45:13 +02:00
Sebastiaan van Stijn 557cabb71e
switch to github.com/containerd/errdefs for error-matching
replace uses of docker/errdefs.IsXXX utilities with their containerd/errdefs
equivalent.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 15:27:43 +02:00
Sebastiaan van Stijn c108da5d19
Merge pull request #6070 from thaJeztah/enable_importas_linter
golangci-lint: enable importas linter
2025-05-16 15:07:31 +02:00
Sebastiaan van Stijn 12992f76e0
Merge pull request #6073 from thaJeztah/format_cleanups_and_fixes
cli/command/formatter: fix .Labels format being randomized
2025-05-16 15:01:38 +02:00
Sebastiaan van Stijn 5ee17eefe6
cli/command/formatter: fix .Labels format being randomized
The labels are stored as a map, causing the output to be randomized.
This patch sorts the result to get a consistent output.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 14:11:56 +02:00
Sebastiaan van Stijn e6bf6dcd90
cli/command/formatter: minor cleanups
no need to initialize with an empty string

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 14:10:34 +02:00
Sebastiaan van Stijn 43e496b396
cli/command/inspect: minor cleanup and improvements
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 14:10:31 +02:00
Paweł Gronowski cacd86c3f3
Merge pull request #6072 from thaJeztah/bump_version
bump version to v28.2.0-dev
2025-05-16 11:44:29 +00:00
Paweł Gronowski 8752709427
Merge pull request #6071 from thaJeztah/update_authors2
update authors and mailmap
2025-05-16 11:44:12 +00:00
Sebastiaan van Stijn f03aeddfcc
bump version to v28.2.0-dev
This file is only used as default if no version is specified. We
should probably get rid of this, but let's update it to better
reflect the version that developer builds are building.

d48fb9f9f7/docker.Makefile (L22)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 13:00:20 +02:00
Sebastiaan van Stijn 49f2dd0761
update .mailmap and authors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 12:58:03 +02:00
Sebastiaan van Stijn 9f68bc0a2b
golangci-lint: enable importas linter
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 12:36:30 +02:00
Sebastiaan van Stijn 378e754c88
use consistent alias for gotest.tools/v3/assert/cmp
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 12:36:14 +02:00
Sebastiaan van Stijn 7eaae97e37
cli/command/container: use consistent alias for oci-spec
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 12:34:28 +02:00
Sebastiaan van Stijn 67f029ec02
Don't use TLS for socket connections
Before this patch:

    mkdir -p ./tempconfig && touch ./tempconfig/ca.pem ./tempconfig/cert.pem ./tempconfig/key.pem

    DOCKER_TLS_VERIFY=1 DOCKER_CONFIG=./tempconfig DOCKER_HOST=unix:///var/run/docker.sock docker info
    Failed to initialize: failed to retrieve context tls info: ca.pem seems invalid

With this patch:

    DOCKER_TLS_VERIFY=1 DOCKER_CONFIG=./tempconfig DOCKER_HOST=unix:///var/run/docker.sock docker info
    Client:
      Version:    28.1.1-25-g2dfe7b558.m
      Context:    default
    ...

Note that the above is just to illustrate; there's still parts in context-
related code that will check for, and load TLS-related files ahead of time.
We should make some of that code lazy-loading (i.e., don't load these until
we're actually gonna make an API connection). For example, if the TLS files
are missing;

    rm ./tempconfig/*.pem
    DOCKER_TLS_VERIFY=1 DOCKER_CONFIG=./tempconfig DOCKER_HOST=unix:///var/run/docker.sock docker info
    Failed to initialize: unable to resolve docker endpoint: open tempconfig/ca.pem: no such file or directory

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 12:10:50 +02:00
Sebastiaan van Stijn 77fbbc38de
Merge pull request #6063 from giautm/patch-1
cli/cli: use `len()` to check frontend ports in the `port` command
2025-05-16 12:03:15 +02:00
Sebastiaan van Stijn bca09c7ac4
Merge pull request #6019 from thaJeztah/docker_auth_config_socket
cli/command/container: --use-api-socket: support DOCKER_AUTH_CONFIG
2025-05-16 11:57:49 +02:00
Sebastiaan van Stijn 267b5e7982
Merge pull request #6069 from thaJeztah/fluentd_completion
completion: add completion for "fluentd-write-timeout"
2025-05-16 11:46:34 +02:00
Paweł Gronowski fe6241a5f7
Merge pull request #6066 from thaJeztah/bump_engine
vendor: github.com/docker/docker fd1a78e0a388 (master, v28.x dev)
2025-05-16 08:37:11 +00:00
Sebastiaan van Stijn 535ac074d0
completion: add completion for "fluentd-write-timeout"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:27:49 +02:00
Sebastiaan van Stijn 678f7182e2
Merge pull request #6045 from robmry/allow_direct_routing
Docs: Add Linux daemon option --allow-direct-routing
2025-05-16 01:24:16 +02:00
Sebastiaan van Stijn 218c7ad958
cli/command/formatter: use ContainerState consts
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:13:14 +02:00
Sebastiaan van Stijn 6fd9c57744
cli/command/container: use ContainerState consts
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:13:14 +02:00
Sebastiaan van Stijn 21e96eaaa7
cli/command/completion: use ContainerState consts in tests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:13:14 +02:00
Sebastiaan van Stijn c9d04c770a
cli/command/formatter: touch-up godoc for ContainerContext.State()
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:13:14 +02:00
Sebastiaan van Stijn d1c76198ba
cli/command/formatter: TestContainerPsContext add test for State()
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:13:13 +02:00
Sebastiaan van Stijn 54bf220a16
vendor: github.com/docker/docker fd1a78e0a388 (master, v28.x dev)
full diff: cb38cc0fdd...fd1a78e0a3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-16 01:12:36 +02:00
Paweł Gronowski 518ba2b4d8
Merge pull request #6061 from thaJeztah/bump_engine
vendor: github.com/docker/docker cb38cc0fdd55 (master, v28.x dev)
2025-05-13 07:51:58 +00:00
Giau. Tran Minh c409383dbc
cli/cli/port: use `len()` to check frontends ports
This ensure the command won't print an empty output if the `frontends` port is nil

Signed-off-by: Giau. Tran Minh <hello@giautm.dev>
2025-05-13 03:48:15 +07:00
Sebastiaan van Stijn e07abcf433
vendor: github.com/docker/docker cb38cc0fdd55 (master, v28.x dev)
full diff: https://github.com/docker/docker/compare/v28.1.1...cb38cc0fdd555eae6c53be1c427c0a28d52965f6

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-12 17:28:34 +02:00
Sebastiaan van Stijn 75a57131a8
Merge pull request #6060 from vvoland/update-go
update to go1.24.3
2025-05-12 17:15:18 +02:00
Paweł Gronowski b0da72a318
update to go1.24.3
- https://go.dev/doc/go1.24
- https://go.dev/doc/devel/release#go1.24.3

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-05-12 13:25:14 +02:00
Sebastiaan van Stijn dd4536e4d0
Merge pull request #6058 from thaJeztah/restore_terminal
restore terminal when terminating after 3 signals
2025-05-12 10:35:20 +02:00
Sebastiaan van Stijn a09028c837
Merge pull request #6054 from thaJeztah/unify_internal
move cli/internal/ packages to top-level internal/
2025-05-12 10:32:41 +02:00
Sebastiaan van Stijn a17b9c542b
restore terminal when terminating after 3 signals
When attaching to a container, hijack puts the terminal in raw mode,
and local echo is disabled. In normal cases, the terminal is restored
once the container detaches;
6f856263c2/cli/command/container/hijack.go (L40-L44)

However, when the CLI is forced to exit (after 3 signals), we `os.Exit(1)`,
which causes defers to not be executed, and because of this, the terminal
not being restored.

For example; start a container that's attached;

    docker run -it --rm --sig-proxy=false alpine sleep 20

In another terminal send a SIGINT 3 times to force terminate;

    kill -sINT $(pgrep -af docker\ run)
    kill -sINT $(pgrep -af docker\ run)
    kill -sINT $(pgrep -af docker\ run)

The first terminal shows that the docker cli was terminated;

    got 3 SIGTERM/SIGINTs, forcefully exiting

However, the terminal was not restored, so local echo is disabled, and
typing any command in the terminal does not show output (a manual `stty echo`
is needed to restore).

With this patch, the terminal is restored before we forcefully exit the
docker CLI. Restoring is a no-op if there's no previous state, so we
can unconditionally execute this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-09 15:26:57 +02:00
Sebastiaan van Stijn 6f856263c2
Merge pull request #6053 from thaJeztah/import_docs
docs: import: assorted fixes and touch-ups
2025-05-08 12:53:29 +02:00
Sebastiaan van Stijn a2a13765f7
Merge pull request #6052 from thaJeztah/inspect_completion
inspect: add shell completion, improve flag-description for `--type` and improve validation
2025-05-06 20:29:54 +02:00
Sebastiaan van Stijn 12c0c13c3b
Merge pull request #6051 from thaJeztah/inspect_fix_flags
docs: move flag examples to right section
2025-05-06 20:29:27 +02:00
Sebastiaan van Stijn 479c7add4d
cli/internal/oauth: move to top-level "internal"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 20:09:28 +02:00
Sebastiaan van Stijn b6059af164
cli/internal/logdetails: move to top-level "internal"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 20:04:25 +02:00
Sebastiaan van Stijn d0d8d1dc72
cli/internal/jsonstream: move to top-level "internal"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 20:04:21 +02:00
Sebastiaan van Stijn 4520a390d2
docs: import: add example for multiple --change flags
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 19:40:53 +02:00
Sebastiaan van Stijn 763ae3e0fb
docs: import: update documentation for --platform
The `--platform` flag originally was added for the experimental LCOW
feature and only accepted the target operating system. Current versions
of Docker allow passing both OS and Architecture, so updating the
documentation to reflect this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 19:40:53 +02:00
Sebastiaan van Stijn 2a67d601ad
docs: import: update list of supported options for --change
Update the list of accepted "change" commands to match what's accepted
by the daemon. This list is the same for "docker commit" and "docker import",
which is defined by the [`validCommitCommands`] variable.

[`validCommitCommands`]: https://github.com/moby/moby/blob/v28.1.1/builder/dockerfile/builder.go#L30-L42

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 19:40:52 +02:00
Sebastiaan van Stijn 79207281fb
docs: import: fix anchor-links and minor touch-up
- Put the content related to `--changes` under a heading with the correct
  anchor, so that it will be linked from the "options" table.
- Move note about `sudo` to be under the right example.
- Update  some examples to directly read from a file instead of piping.
- Add heading for the `--message` flag.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 19:40:47 +02:00
Sebastiaan van Stijn 52752f3aa2
inspect: improve (flag) validation
Produce an error if the `--type` flag was set, but an empty value
was passed.

Before this patch:

    docker inspect --type "" foo
    # json output

    docker inspect --type unknown foo
    "unknown" is not a valid value for --type

With this patch:

    docker inspect --type "" foo
    type is empty: must be one of "config", "container", "image", "network", "node", "plugin", "secret", "service", "task", "volume"

    docker inspect --type unknown foo
    unknown type: "unknown": must be one of "config", "container", "image", "network", "node", "plugin", "secret", "service", "task", "volume"

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 15:54:29 +02:00
Sebastiaan van Stijn 8c5aaff57f
inspect: update flag description of "--type" flag
Before this patch:

    docker inspect --help | grep '\-\-type'
          --type string     Return JSON for specified type

With this patch:

    docker inspect --help | grep '\-\-type'
          --type string     Only inspect objects of the given type

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 15:45:38 +02:00
Sebastiaan van Stijn 7203340f53
inspect: add shell-completion for "--type" flag
With this patch:

    docker inspect --type <TAB>
    config     image    node    secret   task
    container  network  plugin  service  volume

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 15:43:55 +02:00
Sebastiaan van Stijn 877ea1ce35
inspect: disable default (file) completion
Before this patch, flags and arguments would complete using filenames
from the current directory;

    docker inspect --type <TAB>
    AUTHORS       CONTRIBUTING.md             docs/             Makefile            SECURITY.md
    ...

    docker inspect <TAB>

With this patch, no completion is provided;

    docker inspect --type <TAB>
    # no results

    docker inspect <TAB>
    # no results

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 15:43:55 +02:00
Sebastiaan van Stijn f61e2bb6f1
inspect: add consts / enum for object-types
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 15:43:55 +02:00
Sebastiaan van Stijn 25a168106a
Merge pull request #6050 from brlin-tw/patch-1
docs: run: Drop unnecessary command options of the --workdir example
2025-05-06 15:22:33 +02:00
Sebastiaan van Stijn fc3ed90e3a
docs: move flag examples to right section
When generating our docs, flag-descriptions are currently expected
to be under the "examples" section for them to be linked correctly.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-06 13:32:30 +02:00
林博仁 Buo-ren Lin 75d54ac613
run: Drop unnecessary command options of the --workdir example
The `-i` and `-t` options are not needed, as the `pwd` command does not require a TTY nor an interactive session.  Drop them to simplify the example and avoid causing unnecessary confusion to the reader.

Signed-off-by: 林博仁(Buo-ren Lin) <buo.ren.lin@gmail.com>
2025-05-06 18:53:42 +08:00
Sebastiaan van Stijn 7422403164 Merge pull request #49885 from mmorel-35/fix-staticcheck
fix staticcheck linting issues for golangci-lint v2
2025-05-01 17:08:40 +02:00
Matthieu MOREL 09a3c93f96 fix(QF1001): Apply De Morgan’s law
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-05-01 14:16:44 +02:00
Rob Murray f3a812f8f4 Add Linux daemon option --allow-direct-routing
Signed-off-by: Rob Murray <rob.murray@docker.com>
2025-05-01 10:46:21 +01:00
Sebastiaan van Stijn 58d318b990
Merge pull request #6036 from thaJeztah/improve_username_handling
cli/command/registry: login: improve flag validation
2025-04-30 19:09:18 +02:00
Sebastiaan van Stijn 3707d07381
Merge pull request #6041 from thaJeztah/bump_creds_helper_0.9.3
vendor: github.com/docker/docker-credential-helpers v0.9.3
2025-04-29 16:41:25 +02:00
Sebastiaan van Stijn 1af8ae4be4
Merge pull request #6040 from thaJeztah/bump_md2man
vendor github.com/cpuguy83/go-md2man/v2 v2.0.7
2025-04-29 16:40:06 +02:00
Sebastiaan van Stijn fb261fdd0c
Merge pull request #6037 from mmorel-35/staticcheck/quickfixes
fix(QF1003): Convert if/else-if chain to tagged switch
2025-04-28 21:20:22 +02:00
Matthieu MOREL 54efe295f0 fix(QF1003): Convert if/else-if chain to tagged switch
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
2025-04-28 18:35:09 +02:00
Sebastiaan van Stijn 09863a702c
vendor: github.com/docker/docker-credential-helpers v0.9.3
no changes in vendored code

full diff: https://github.com/docker/docker-credential-helpers/compare/v0.9.2...v0.9.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-26 16:30:02 +02:00
Sebastiaan van Stijn 4679278636
vendor github.com/cpuguy83/go-md2man/v2 v2.0.7
full diff: https://github.com/cpuguy83/go-md2man/compare/v2.0.6...v2.0.7

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-26 16:27:49 +02:00
Sebastiaan van Stijn a10a1e619b builder/remotecontext: remove unused named and "naked" returns
Also renamed some vars for clarity, renamed a error-returns to prevent
shadowing, and fixed some linter warnings about unhandled errors.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-26 15:47:11 +02:00
Sebastiaan van Stijn e7af1812cf
cli/command/registry: login: improve flag validation
Before this change, some errors could be ambiguous as they did not
distinguish a flag to be omitted, or set, but with an empty value.

For example, if a user would try to loging but with an empty username,
the error would suggest that the `--username` flag was not set (which
it was);

I don't have `MY_USERNAME` set in this shell;

    printenv MY_USERNAME || echo 'variable not set'
    variable not set

Now, attempting to do a non-interactive login would result in an
ambiguous error;

        echo "supersecret" | docker login --password-stdin --username "$MY_USERNAME"
        Must provide --username with --password-stdin

With this patch applied, the error indicates that the username was empty,
or not set;

        echo "supersecret" | docker login --password-stdin --username "$MY_USERNAME"
        username is empty
        echo "supersecret" | docker login --password-stdin
        the --password-stdin option requires --username to be set
        echo "supersecret" | docker login --password-stdin --password "supersecret"
        conflicting options: cannot specify both --password and --password-stdin

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-25 17:11:05 +02:00
Sebastiaan van Stijn 8845ccd60f
cli/command/registry: login: add unit test for flag validation
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-25 16:39:55 +02:00
Sebastiaan van Stijn c80675bfe1
Merge pull request #6028 from mmorel-35/golangci-lint@v2
chore: bump golangci-lint to v2
2025-04-24 18:37:34 +02:00
Sebastiaan van Stijn aadd7879c9
Merge pull request #6034 from thaJeztah/connhelper_cleanups_step2
cli/connhelper/ssh: add NewSpec utility to prevent parsing URL twice
2025-04-23 16:00:07 +02:00
Sebastiaan van Stijn 8638ceff2c
Merge pull request #6032 from thaJeztah/deprecate_ListOpts_GetAll
opts: deprecate ListOpts.GetAll in favor of ListOpts.GetSlice
2025-04-23 15:56:38 +02:00
Matthieu MOREL ef0a5eb694 chore: bump golangci-lint to v2
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
2025-04-23 13:11:58 +00:00
Sebastiaan van Stijn 5215b1eca4
opts: deprecate ListOpts.GetAll in favor of ListOpts.GetSlice
The `GetSlice()` function is part of cobra's [cobra.SliceValue] interface,
and duplicates the older `GetAll()` method. This patch deprecates the
`GetAll()` method in favor of `GetSlice()`.

[cobra.SliceValue]: https://pkg.go.dev/github.com/spf13/cobra@v1.9.1#SliceValue

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 14:31:50 +02:00
Sebastiaan van Stijn ca199577a9
Merge pull request #6031 from thaJeztah/change_flag_uses
cli/command: change uses of ListOpts.GetAll for GetSlice
2025-04-23 14:31:28 +02:00
Sebastiaan van Stijn f105e964da
cli/connhelper: don't parse URL twice
This function was parsing the same URL twice; first to detect the
scheme, then again (through ssh.ParseURL) to construct a ssh.Spec.

Change the function to use the URL that's parsed, and use ssh.NewSpec
instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 14:29:44 +02:00
Sebastiaan van Stijn 11b53dabc6
cli/connhelper/ssh: add NewSpec utility
This allows creating a spec from an existing url.URL

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 14:29:42 +02:00
Sebastiaan van Stijn 55073c404c
cli/connhelper/ssh: tweak error-message (capitalize SSH)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 14:27:49 +02:00
Sebastiaan van Stijn 22a573649d
cli/command: change uses of ListOpts.GetAll for GetSlice
The `GetSlice()` function is part of cobra's [cobra.SliceValue] interface,
and duplicates the older `GetAll()` method. This patch changes our use
of the `GetAll()` method with the intent to deprecated it in future.

[cobra.SliceValue]: https://pkg.go.dev/github.com/spf13/cobra@v1.9.1#SliceValue

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 13:51:37 +02:00
Sebastiaan van Stijn 81a5db6b82
Merge pull request #6030 from thaJeztah/flag_multiple_completion
opts: ListOpts: implement cobra.SliceValue to fix shell completion
2025-04-23 13:51:11 +02:00
Sebastiaan van Stijn 11fea00142
Merge pull request #6022 from thaJeztah/connhelper_cleanups_step1
cli/connhelper: cleanups and test improvements
2025-04-23 13:37:27 +02:00
Paweł Gronowski eeda0af3f4
Merge pull request #6029 from thaJeztah/stack_deploy_failearly
stack deploy: fail early on invalid image reference format
2025-04-23 11:32:35 +00:00
Sebastiaan van Stijn aa065b43c1
Merge pull request #6033 from thaJeztah/fix_import_heading
docs: image import: fix heading to be included in online docs
2025-04-23 13:27:47 +02:00
Sebastiaan van Stijn f36b28eae4
Merge pull request #6024 from thaJeztah/move_otel
move hack/otel to contrib
2025-04-23 13:26:47 +02:00
Sebastiaan van Stijn 572e3f1c53
opts: ListOpts: implement cobra.SliceValue to fix shell completion
Cobra's shell completion has specific rules to decide whether a flag can
be accepted multiple times. If a flag does not meet that rule, it only
completes the flag name once; some of those rules depend on the "type"
of the option to end with "Array" or "Slice", which most of our options
don't.

Starting with Cobra 1.9, it also checks whether an option implements
the [cobra.SliceValue] interface (see [spf13/cobra 2210]).

This patch implements the [cobra.SliceValue] interface on ListOpts, so
that these options can be completed multiple times.

In a follow-up, we can update our code to replace our uses of `GetAll()`,
which is identical with the `GetSlice()` method, and potentially deprecate
the old method.

Before this patch, ListOpts would only be completed once when completing
flag names. For example, the following would show the `--label` flag the
first time, but omit it if a `--label` flag was already set;

    docker run--l<TAB>
    --label                  (Set meta data on a container)  --link-local-ip  (Container IPv4/IPv6 link-local addresses)
    --label-file  (Read in a line delimited file of labels)  --log-driver             (Logging driver for the container)
    --link                  (Add link to another container)  --log-opt                              (Log driver options)

    docker run --label hello --l<TAB>
    --label-file  (Read in a line delimited file of labels)  --link-local-ip  (Container IPv4/IPv6 link-local addresses)  --log-opt  (Log driver options)
    --link                  (Add link to another container)  --log-driver             (Logging driver for the container)

With this patch, the completion script correctly identifies the `--label`
flag to be accepted multiple times, and also completes it when already
set;

    docker run --label hello --l<TAB>
    --label                  (Set meta data on a container)  --link-local-ip  (Container IPv4/IPv6 link-local addresses)
    --label-file  (Read in a line delimited file of labels)  --log-driver             (Logging driver for the container)
    --link                  (Add link to another container)  --log-opt                              (Log driver options)

[cobra.SliceValue]: https://pkg.go.dev/github.com/spf13/cobra@v1.9.1#SliceValue
[spf13/cobra 2210]: https://github.com/spf13/cobra/pull/2210

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 12:22:42 +02:00
Sebastiaan van Stijn 3c4bcce81e
docs: image import: fix heading to be included in online docs
The online docs looks for level-3 headings under the "examples"
to be included.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-23 09:57:08 +02:00
Sebastiaan van Stijn bcb36e26cb
stack deploy: fail early on invalid image reference format
Before this patch, `docker stack deploy` would not validate the image
reference on the client side, depending on the daemon to return an error,
which was not always easy to interpret;

    docker stack deploy -c docker-compose.yaml mystack
    Creating service mystack_myservice
    failed to create service mystack_myservice: Error response from daemon: rpc error: code = InvalidArgument desc = ContainerSpec: image reference must be provided

    IMAGE_NAME=FOOBAR  docker stack deploy -c docker-compose.yaml mystack
    Creating service mystack_myservice
    failed to create service mystack_myservice: Error response from daemon: rpc error: code = InvalidArgument desc = ContainerSpec: "FOOBAR" is not a valid repository/tag

With this patch, the CLI validates the image-reference for each service,
producing an error if the reference is empty or invalid.

    docker stack config -c docker-compose.yaml
    invalid service myservice: no image specified

    IMAGE_NAME=FOOBAR  ~/Projects/cli/build/docker stack deploy -c docker-compose.yaml mystack
    invalid image reference for service myservice: invalid reference format: repository name (library/FOOBAR) must be lowercase

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-22 16:23:41 +02:00
Sebastiaan van Stijn 61c6818f0b
Merge pull request #6026 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.1.1
2025-04-18 21:46:44 +02:00
Paweł Gronowski f3deb28111
vendor: github.com/docker/docker v28.1.1
full diff: https://github.com/docker/docker/compare/v28.1.0...v28.1.1

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-04-18 13:46:36 +02:00
Paweł Gronowski 4eba377327
Merge pull request #6025 from thaJeztah/bump_compose
Dockerfile: update compose to v2.35.1
2025-04-18 09:44:47 +00:00
Sebastiaan van Stijn 9cd35577fc
Dockerfile: update compose to v2.35.1
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-18 00:04:38 +02:00
Sebastiaan van Stijn 1ca0a7d57a
move hack/otel to contrib
Aligning with where we put this in moby, and contrib is a slightly
more suitable location for this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 23:57:50 +02:00
Sebastiaan van Stijn c77159623b
cli/connhelper: use stdlib errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 21:42:55 +02:00
Sebastiaan van Stijn 2c24fb2bcd
cli/connhelper/commandcon: use stdlib errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 21:42:55 +02:00
Sebastiaan van Stijn 8c0c1db679
cli/connhelper/ssh: use stdlib errors and improve errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 21:38:52 +02:00
Sebastiaan van Stijn 6ca9766897
cli/connhelper/ssh: improve GoDoc for ParseURL
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 21:34:18 +02:00
Sebastiaan van Stijn 126713648e
cli/connhelper/ssh: TestParseURL: various improvements
- use designated example domains as example value
- swap "expected" and "actual" values in assertions
- add doc / name for each test
- add test-cases for remote commands
- also test the Spec that's produced, not just the args
- merge two test-cases that could be combined

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 21:28:09 +02:00
Sebastiaan van Stijn cf87480ab5
Merge pull request #6020 from thaJeztah/bump_engine_28.1
vendor: github.com/docker/docker v28.1.0
2025-04-17 17:02:28 +02:00
Sebastiaan van Stijn adb0d29504
vendor: github.com/docker/docker v28.1.0
no diff; same commit, but tagged

full diff: https://github.com/docker/docker/compare/v28.1.0-rc.2...v28.1.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 16:12:40 +02:00
Sebastiaan van Stijn 73be7342a6
cli/command/container: --use-api-socket: support DOCKER_AUTH_CONFIG
With this patch, the `--use-api-socket` flag can obtain credentials from
a validly formatted `DOCKER_AUTH_CONFIG` environment-variable. If the
env-var is not set, or doesn't contain credentials, it falls back to
attempting to read credentials from the CLI's configured credentials
store.

With this patch:

    # Make sure there's no auth on disk first
    mkdir -p tmpConfig
    export DOCKER_CONFIG=$PWD/tmpConfig
    rm -f $PWD/tmpConfig/config.json

    # no credentials
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    cat: can't open '/run/secrets/docker/config.json': No such file or directory

    # pass credentials through DOCKER_AUTH_CONFIG
    DOCKER_AUTH_CONFIG='{"auths": {"https://index.docker.io/v1/": {"auth": "am9lam9lOmhlbGxv"}}}' docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "am9lam9lOmhlbGxv"
            }
        }
    }

    # credentials from file if no DOCKER_AUTH_CONFIG is set
    echo '{"auths": {"https://index.docker.io/v1/": {"auth": "am9lam9lOmhlbGxv"}}}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "am9lam9lOmhlbGxv"
            }
        }
    }

    # same if DOCKER_AUTH_CONFIG is set, but doesn't contain credentials
    DOCKER_AUTH_CONFIG='{}' docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "am9lam9lOmhlbGxv"
            }
        }
    }

    DOCKER_AUTH_CONFIG='{"auths": {}}' docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "am9lam9lOmhlbGxv"
            }
        }
    }

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 12:15:57 +02:00
Sebastiaan van Stijn 2002204ce9
cli/command/container: createContainer: move fn closer to where used
The "use-api-socket" code got in between, putting a lot of distance
between the declaration and use.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 12:15:57 +02:00
Paweł Gronowski 4d8c241ff0
Merge pull request #6018 from thaJeztah/use_api_socket_no_empty
cli/command/container: --use-api-socket: don't write empty credentials
2025-04-17 09:52:28 +00:00
Sebastiaan van Stijn 711fcaeb25
cli/command/container: --use-api-socket: don't write empty credentials
Before this patch, a valid, but empty set of credentials would still
write a config-file to the container and set `DOCKER_CONFIG`:

    mkdir -p tmpConfig
    export DOCKER_CONFIG=$PWD/tmpConfig

    echo '{}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {}
    }

    echo '{"auths": {}}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {}
    }

    echo '{"auths": {"https://index.docker.io/v1/": {"auth": "am9lam9lOmhlbGxv"}}}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "am9lam9lOmhlbGxv"
            }
        }
    }

With this patch, the `DOCKER_CONFIG` env-var and config-file are only created
if we have credentials to set;

    mkdir -p tmpConfig
    export DOCKER_CONFIG=$PWD/tmpConfig

    echo '{}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    cat: can't open '/run/secrets/docker/config.json': No such file or directory

    echo '{"auths": {}}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    cat: can't open '/run/secrets/docker/config.json': No such file or directory

    echo '{"auths": {"https://index.docker.io/v1/": {"auth": "am9lam9lOmhlbGxv"}}}' > "${DOCKER_CONFIG}/config.json"
    docker run --rm --use-api-socket alpine cat /run/secrets/docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "am9lam9lOmhlbGxv"
            }
        }
    }

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 11:36:06 +02:00
Paweł Gronowski ed694dbbef
Merge pull request #5868 from thaJeztah/bump_go_version
update minimum go version to go1.23
2025-04-17 09:20:56 +00:00
Paweł Gronowski 79ab3cb0e8
Merge pull request #6017 from thaJeztah/bump_engine_28.1
vendor: github.com/docker/docker v28.1.0-rc.2
2025-04-17 08:58:07 +00:00
Sebastiaan van Stijn 1d768f8983
update go:build tags to go1.23 to align with vendor.mod
Go maintainers started to unconditionally update the minimum go version
for golang.org/x/ dependencies to go1.23, which means that we'll no longer
be able to support any version below that when updating those dependencies;

> all: upgrade go directive to at least 1.23.0 [generated]
>
> By now Go 1.24.0 has been released, and Go 1.22 is no longer supported
> per the Go Release Policy (https://go.dev/doc/devel/release#policy).
>
> For golang/go#69095.

This updates our minimum version to go1.23, as we won't be able to maintain
compatibility with older versions because of the above.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 10:43:47 +02:00
Paweł Gronowski 0e75283292
Merge pull request #6016 from thaJeztah/context_completion
context: add shell-completion for context-names
2025-04-17 08:41:48 +00:00
Sebastiaan van Stijn a5b6efa29d
vendor: github.com/docker/docker v28.1.0-rc.2
no diff, same commit, but tagged:
https://github.com/docker/docker/compare/3f46cadf398a...v28.1.0-rc.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 10:34:50 +02:00
Sebastiaan van Stijn 6fd72c6333
context: add shell-completion for context-names
For now, these are not exported and included in the cli/commands/contexts
package; a copy of this also lives in cmd/docker, but we need to find a
good place for these completions, as some of them bring in additional
dependencies.

Commands that accept multiple arguments provide completion, but removing
duplicates:

    docker context inspect<TAB>
    default  desktop-linux  (current)  production  tcd

    docker context inspec default<TAB>
    desktop-linux  (current)  production  tcd

    docker context inspect default tcd<TAB>
    desktop-linux  (current)  production

For "context export", we provide completion for the first argument, after
which file-completion is provided:

    # provides context names completion for the first argument
    docker context export production<TAB>
    default  desktop-linux  (current)  production  tcd

    # then provides completion for filenames
    docker context export desktop-linux<TAB>
    build/           man/                TESTING.md
    cli/             docker.Makefile     go.mod
    ...

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-17 10:32:18 +02:00
Alano Terblanche 659b026b7f
Merge pull request #6015 from Benehiko/fix-login-hints
Fix login hints should only show on hub registry
2025-04-16 18:15:47 +02:00
Alano Terblanche 6c271162c5
Fix login hints should only show on hub registry
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-04-16 17:17:23 +02:00
Paweł Gronowski b8857225a0
Merge pull request #6013 from thaJeztah/bump_engine
vendor: github.com/docker/docker 3f46cadf398a (master, v28.0.0-rc.2)
2025-04-16 12:28:40 +00:00
Sebastiaan van Stijn fc04a49c35
vendor: github.com/docker/docker 3f46cadf398a (master, v28.0.0-rc.2)
full diff: https://github.com/docker/docker/compare/v28.1.0-rc.1...3f46cadf398abdf3196230fea41dac96b5d4016e

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-16 14:22:08 +02:00
Sebastiaan van Stijn 129ab99109
Merge pull request #6011 from thaJeztah/bump_archive
vendor: github.com/moby/go-archive v0.1.0
2025-04-16 13:39:56 +02:00
Sebastiaan van Stijn 59a723bda6
Merge pull request #6012 from thaJeztah/bump_dev_tools
Dockerfile: update buildx to v0.23.0, compose v2.33.1
2025-04-16 13:39:33 +02:00
Sebastiaan van Stijn 6ca77b6529
Merge pull request #6009 from zhangwenlong8911/master
set CGO_ENABLED=1 on loong64
2025-04-16 13:28:57 +02:00
Sebastiaan van Stijn 50900c0da7
Dockerfile: update compose to v2.33.1
Looks like later versions are currently missing on Docker Hub

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-16 13:24:28 +02:00
Sebastiaan van Stijn 2dcc881d4d
Dockerfile: update buildx to v0.23.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-16 13:19:14 +02:00
Sebastiaan van Stijn e7a091eceb
vendor: github.com/moby/go-archive v0.1.0
full diff: https://github.com/moby/go-archive/compare/21f3f3385ab7...v0.1.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-16 13:08:08 +02:00
Paweł Gronowski e04b67f51d
Merge pull request #6010 from thaJeztah/tweak_platform_completion
completion: remove generic "os-only" for platforms
2025-04-16 09:44:31 +00:00
Sebastiaan van Stijn 557d721299
completion: remove generic "os-only" for platforms
Using `--platform=linux` or `--platform=windows` is not commonly
used (or recommended). Let's remove these from the list of suggested
platforms.

We should tweak this completion further, and sort the list based
on the daemon's platform (putting linux first for a Linux daemon,
and windows first on a Windows daemon), possibly with the correct
architecture (and os-version) included, but we don't yet provide
that information in `/_ping`.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-16 11:30:26 +02:00
Sebastiaan van Stijn 219d3fe25a
Merge pull request #5858 from stevvooe/sjd/include-docker-socket
run: flag to include the docker socket
2025-04-16 10:49:27 +02:00
Wenlong Zhang 2b28bb649b set CGO_ENABLED=1 on loong64
Signed-off-by: Wenlong Zhang <zhangwenlong@loongson.cn>
2025-04-16 14:52:19 +08:00
Stephen Day 1a502e91c9
run: flag to include the Docker API socket
Adds a flag to the create and run command, `--use-api-socket`, that can
be used to start a container with the correctly configured parameters to
ensure that accessing the docker socket will work with out managing bind
mounts and authentication injection.

The implementation in this PR resolves the tokens for the current
credential set in the client and then copies it into a container at the
well know location of /run/secrets/docker/config.json, setting
DOCKER_CONFIG to ensure it is resolved by existing tooling. We use a
compose-compatible secret location with the hope that the CLI and
compose can work together seamlessly.

The bind mount for the socket is resolved from the current context,
erroring out if the flag is set and the provided socket is not a unix
socket.

There are a few drawbacks to this approach but it resolves a long
standing pain point. We'll continue to develop this as we understand
more use cases but it is marked as experimental for now.

Signed-off-by: Stephen Day <stephen.day@docker.com>
2025-04-15 10:57:44 -07:00
Sebastiaan van Stijn 1adc1583a7
Merge pull request #6006 from thaJeztah/bump_engine_28.1
vendor: github.com/docker/docker v28.1.0-rc.1
2025-04-15 17:01:40 +02:00
Sebastiaan van Stijn 785a12eeef
vendor: github.com/docker/docker v28.1.0-rc.1
no diff; same commit, but tagged;
https://github.com/docker/docker/compare/250792c1a540...v28.1.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-12 08:15:26 +02:00
Sebastiaan van Stijn fc99fe2d08
Merge pull request #5994 from aevesdocker/oss-5
docs: replace sshfs with rclone
2025-04-11 17:00:42 +02:00
aevesdocker b501283743
docs: replace sshfs with rclone
Signed-off-by: aevesdocker <allie.sadler@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 16:54:46 +02:00
Sebastiaan van Stijn 3372bcf821
Merge pull request #6001 from thaJeztah/tweak_prompt
Dockerfile: fix and clean up shell prompt
2025-04-11 16:53:28 +02:00
Paweł Gronowski c528504434
Merge pull request #5947 from thaJeztah/docker_bake
add top-level "docker bake" command as alias for "docker buildx bake"
2025-04-11 14:44:08 +00:00
Sebastiaan van Stijn adb0abaec5
add top-level "docker bake" command as alias for "docker buildx bake"
The [`docker buildx bake`][1] command has reached GA; this patch adds
a top-level `docker bake` command as alias for `docker buildx bake` to
improve discoverability and make it more convenient to use.

With this patch:

    docker --help

    Usage:  docker [OPTIONS] COMMAND

    A self-sufficient runtime for containers

    Common Commands:
      run         Create and run a new container from an image
      exec        Execute a command in a running container
      ps          List containers
      build       Build an image from a Dockerfile
      bake        Build from a file
      pull        Download an image from a registry
      push        Upload an image to a registry
      images      List images
    ...

The command is hidden if buildx is not installed;

    docker --help
    Usage:  docker [OPTIONS] COMMAND

    A self-sufficient runtime for containers

    Common Commands:
      run         Create and run a new container from an image
      exec        Execute a command in a running container
      ps          List containers
      build       Build an image from a Dockerfile
      pull        Download an image from a registry
      push        Upload an image to a registry
      images      List images
    ...

We can do some tweaking after this; currently it show an error
in situations where buildx is missing. We don't account for
"DOCKER_BUILDKIT=0", because this is a new feature that requires
buildx, and cannot be "disabled";

buildx missing;

    docker bake
    ERROR: bake requires the buildx component but it is missing or broken.
           Install the buildx component to use bake:
           https://docs.docker.com/go/buildx/

BuildKit disabled:

    DOCKER_BUILDKIT=0 docker bake
    ERROR: bake requires the buildx component but it is missing or broken.
           Install the buildx component to use bake:
           https://docs.docker.com/go/buildx/

[1]: https://www.docker.com/blog/ga-launch-docker-bake/

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 16:28:47 +02:00
Paweł Gronowski 18178e079f
Merge pull request #5981 from thaJeztah/remove_ContextType
context list: remove temporary ContextType from JSON output
2025-04-11 14:21:27 +00:00
Paweł Gronowski e937b52210
Merge pull request #5953 from thaJeztah/opts_remove_deprecated
opts: remove deprecated PortOpt, ConfigOpt, SecretOpt aliases
2025-04-11 14:13:10 +00:00
Sebastiaan van Stijn 6aa93d1f40
Merge pull request #5952 from thaJeztah/move_prompt_utils_step1
cli/command: move prompt utilities to separate package
2025-04-11 16:11:12 +02:00
Sebastiaan van Stijn a85062bcdc
Merge pull request #5934 from vvoland/inspect-platform
image/inspect: Add --platform flag
2025-04-11 16:08:46 +02:00
Paweł Gronowski 0d9d187f31
image/inspect: Add --platform flag
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-04-11 15:53:41 +02:00
Sebastiaan van Stijn 559c0121c8
Merge pull request #6002 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.1.0-dev (250792c1a540)
2025-04-11 15:47:59 +02:00
Paweł Gronowski ec9e729f76
vendor: github.com/docker/docker v28.1.0-dev (250792c1a540)
full diff: 511cd1c0a7...250792c1a5

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-04-11 15:23:24 +02:00
Paweł Gronowski 07b203e2f2
Merge pull request #5924 from thaJeztah/hide_untagged
docker images --tree: hide both untagged and dangling images by default
2025-04-11 13:14:59 +00:00
Sebastiaan van Stijn f18e239a53
docker images --tree: hide both untagged and dangling images by default
Before this patch, `docker image ls` / `docker image ls` would always
show untagged images, but hide "dangling" images (which effectively
only were produced by the legacy builder) unless `-a` / `--all` was
used. This often resulted in many `<none>:<none>` or `<untagged>` images
to be shown, which had little value to interact with, other than to
garbage collect (`docker system prune`).

In future, we want to take more advantage of containerd's garbage-collecting
features (removing unused images automatically), and this UX change is
a stepping stone toward that.

For now, this patch only changes the behavior for `docker image ls --tree`,
but we should make this the same for "non" --tree as well.

This patch:

- changes `docker image ls` to hide both "untagged" and "dangling" images
  by default.
- changes the behavior of `--all` on the client side to make them visible

The API response remains the same for now, but this is something we can
consider changing in future (possibly more granular than a single boolean).

Before this patch;

    docker image ls --tree
                                                                           i Info →   U  In Use

    IMAGE                                      ID             DISK USAGE   CONTENT SIZE   EXTRA
    docker:cli                                 28fb556c1ea1        276MB         69.8MB
    ├─ linux/amd64                             828f4f57525d           0B             0B
    ├─ linux/arm/v6                            563c0b58e54b           0B             0B
    ├─ linux/arm/v7                            6045d4846c59           0B             0B
    └─ linux/arm64/v8                          11e8dfd68841        276MB         69.8MB

    alpine:latest                              a8560b36e8b8       12.8MB         3.99MB    U
    ├─ linux/amd64                             1c4eef651f65           0B             0B
    ├─ linux/arm/v6                            903bfe2ae994           0B             0B
    ├─ linux/arm/v7                            9c2d245b3c01           0B             0B
    ├─ linux/arm64/v8                          757d680068d7       12.8MB         3.99MB    U
    ├─ linux/386                               2436f2b3b7d2           0B             0B
    ├─ linux/ppc64le                           9ed53fd3b831           0B             0B
    ├─ linux/riscv64                           1de5eb4a9a67           0B             0B
    └─ linux/s390x                             fe0dcdd1f783           0B             0B

    <untagged>                                 c6c1bcb0fd8d       12.8MB         3.99MB
    └─ linux/arm64                             cb171c618ae8       12.8MB         3.99MB

    <untagged>                                 7361ef970703       12.8MB         3.99MB
    └─ linux/arm64                             07033f43e44a       12.8MB         3.99MB

    <untagged>                                 0c62c63b81ec       12.8MB         3.99MB
    └─ linux/arm64                             94742272117f       12.8MB         3.99MB

    <untagged>                                 91dd947eebd0       12.8MB         3.99MB
    └─ linux/arm64                             ee55d203e26f       12.8MB         3.99MB

    <untagged>                                 382d9f57e8d8       12.8MB         3.99MB
    └─ linux/arm64                             5256d47804e3       12.8MB         3.99MB

    <untagged>                                 56fa17d2a7e7       12.8MB         3.99MB
    ├─ linux/amd64                             483f502c0e6a           0B             0B
    ├─ linux/arm/v6                            c79529000bdf           0B             0B
    ├─ linux/arm/v7                            cc455d4b2c47           0B             0B
    ├─ linux/arm64/v8                          508c1b94e1d2       12.8MB         3.99MB
    ├─ linux/386                               f32403957113           0B             0B
    ├─ linux/ppc64le                           23dbce23b88f           0B             0B
    ├─ linux/riscv64                           f9d2da150cee           0B             0B
    └─ linux/s390x                             6bb03952a007           0B             0B

After this patch

    docker image ls --tree
                                                                           i Info →   U  In Use

    IMAGE                                      ID             DISK USAGE   CONTENT SIZE   EXTRA
    docker:cli                                 28fb556c1ea1        276MB         69.8MB
    ├─ linux/amd64                             828f4f57525d           0B             0B
    ├─ linux/arm/v6                            563c0b58e54b           0B             0B
    ├─ linux/arm/v7                            6045d4846c59           0B             0B
    └─ linux/arm64/v8                          11e8dfd68841        276MB         69.8MB

    alpine:latest                              a8560b36e8b8       12.8MB         3.99MB    U
    ├─ linux/amd64                             1c4eef651f65           0B             0B
    ├─ linux/arm/v6                            903bfe2ae994           0B             0B
    ├─ linux/arm/v7                            9c2d245b3c01           0B             0B
    ├─ linux/arm64/v8                          757d680068d7       12.8MB         3.99MB    U
    ├─ linux/386                               2436f2b3b7d2           0B             0B
    ├─ linux/ppc64le                           9ed53fd3b831           0B             0B
    ├─ linux/riscv64                           1de5eb4a9a67           0B             0B
    └─ linux/s390x                             fe0dcdd1f783           0B             0B

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 14:58:23 +02:00
Sebastiaan van Stijn 1f9a55de6a
Dockerfile: fix and clean up shell prompt
The existing approach had some issues with how the control-chars
were escaped; also switching to use Dockerfile here-doc to make
it a bit more readable, and add some comments to the `.bashrc`.

Also make sure the MOTD isn't printed multiple times, and only
for interactive shells, and slightly tweak it with some colors.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 13:48:30 +02:00
Sebastiaan van Stijn c718d3f13c
Merge pull request #6000 from vvoland/image-tree-totalcontent
cli/command/image: Fix total content size calculation in image tree
2025-04-11 13:45:35 +02:00
Paweł Gronowski 1a950db5ce
cli/command/image: Fix total content size calculation in image tree
Before this patch, image total content size would only include
container images content size.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-04-11 13:30:20 +02:00
Sebastiaan van Stijn e2865628ae
Merge pull request #5983 from thaJeztah/fix_context_non_default
cli/command: DockerCli.Initialize: make sure context-store config is set
2025-04-11 12:46:15 +02:00
Sebastiaan van Stijn e578f156c0
Merge pull request #5998 from thaJeztah/lazy_regexp
use lazyregexp to compile regexes on first use
2025-04-11 12:29:53 +02:00
Sebastiaan van Stijn b74b7b3c40
internal/prompt: TestConfirm: don't use un-keyed structs
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 12:23:24 +02:00
Sebastiaan van Stijn ecde8c38a5
internal/prompt: skip fmt.Printf and use writer directly
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 12:23:21 +02:00
Sebastiaan van Stijn b37d84fd10
cli/command: move prompt utilities to separate package
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 12:23:16 +02:00
Sebastiaan van Stijn af85e1e2f7
cli/command: implement ErrPromptTerminated without errdefs package
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-11 12:15:11 +02:00
Sebastiaan van Stijn 8633197105
Merge pull request #5914 from thaJeztah/use_atomicwriter
cli/command: deprecate CopyToFile and reimplement with atomicwriter
2025-04-11 12:10:46 +02:00
Sebastiaan van Stijn 94afbc1116
Merge pull request #5999 from thaJeztah/bump_engine
vendor: github.com/docker/docker 511cd1c0a736 (master, v28.x-dev)
2025-04-11 12:09:28 +02:00
Sebastiaan van Stijn 4530417f6b
vendor: github.com/docker/docker 511cd1c0a736 (master, v28.x-dev)
full diff: 185651d26b...511cd1c0a7

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 22:03:48 +02:00
Sebastiaan van Stijn 23d7346f75
Merge pull request #5977 from thaJeztah/deprecate_config_experimental
cli/config/configfile: deprecate ConfigFile.Experimental field
2025-04-10 14:36:11 +02:00
Sebastiaan van Stijn 4c820d3ac0
golangci-lint: add forbidigo rules to prevent regex.MustCompile
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:27 +02:00
Sebastiaan van Stijn ced66f22d6
cli/compose/template: use lazyregexp to compile regexes on first use
This package needed an (internal) interface to abstract the lazy-regexp.
For this, I split the implementation from the exported implementation; this
also revealed that some functions are not used (at least not in our code
base), and we could consider deprecating these.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:26 +02:00
Sebastiaan van Stijn 0b0fc106dc
cli/compose/template: rename vars that shadowed
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:26 +02:00
Sebastiaan van Stijn 56c2fa6c0e
e2e/cli-plugins: use regexp.Compile to prevent panic in tests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:26 +02:00
Sebastiaan van Stijn 1ed3859879
cli-plugins/manager: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:26 +02:00
Sebastiaan van Stijn 7fde1f799f
cli/context/store: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:25 +02:00
Sebastiaan van Stijn d5a8cd4093
cli/command/trust: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:25 +02:00
Sebastiaan van Stijn 01d8642c7e
cli/command/system: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:25 +02:00
Sebastiaan van Stijn a16c3a49c8
cli/command/image: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:25 +02:00
Sebastiaan van Stijn d76057210a
cli/command/container: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:25 +02:00
Sebastiaan van Stijn 9a849ba00c
opts: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:24 +02:00
Sebastiaan van Stijn 481e6f1477
implement lazyregexp package
Based on the "lazyregexp" package in golang.org/x/mod;
https://cs.opensource.google/go/x/mod/+/refs/tags/v0.19.0:internal/lazyregexp/lazyre.go;l=66-78

This package allows defining regular expressions that should not be
compiled until used, but still providing validation to prevent
invalid regular expressions from producing a panic at runtime.

This is largely a copy of the package from golang.org/x/mod,
with FindAllStringSubmatch and ReplaceAllStringFunc added

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 12:22:24 +02:00
Paweł Gronowski 6c2d023d87
swarm/init: Fix `--external-ca` ignoring `cacert` option
31d6292458 mistakenly changed the `ToSpec`
function to set all certs passed via `external-ca` to empty strings.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-04-10 11:41:13 +02:00
Paweł Gronowski bcd9c885e3
Merge pull request #5997 from thaJeztah/fastpath_needs_serverinfo
cli/command/system: needsServerInfo: add fast-paths
2025-04-10 09:24:06 +00:00
Paweł Gronowski e587e8a269
Merge pull request #5996 from thaJeztah/bump_x_deps
vendor: update golang.org/x/.. dependencies
2025-04-10 09:23:17 +00:00
Sebastiaan van Stijn 932574363f
cli/command/system: needsServerInfo: add fast-paths
We can return early without executing the regular expression or evaluating
the template for `--format=json` or `--format='{{json .}}'`.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 10:50:04 +02:00
Sebastiaan van Stijn ac375caa87
Merge pull request #5918 from Benehiko/info-exit-code
system/info: failure to connect to docker socket should propagate error
2025-04-10 10:31:05 +02:00
Sebastiaan van Stijn 7cc6b8ebf4
cli/command: deprecate CopyToFile and reimplement with atomicwriter
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 09:46:06 +02:00
Sebastiaan van Stijn b8bcf6f5ad
container export: implement file-write with atomicwriter
Same functionality, but implemented with atomicwriter. There's a slight
difference in error-messages produced (but can be adjusted if we want).

Before:

    docker container export -o ./no/such/foo mycontainer
    failed to export container: invalid output path: directory "no/such" does not exist

    docker container export -o /no/permissions mycontainer
    failed to export container: stat /no/permissions: permission denied

After:

    docker container export -o ./no/such/foo mycontainer
    failed to export container: invalid file path: stat no/such: no such file or directory

    docker container export -o /no/permissions mycontainer
    failed to export container: failed to stat output path: lstat /no/permissions: permission denied

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 09:46:06 +02:00
Sebastiaan van Stijn d47d2338b7
image save: implement file-write with atomicwriter
Same functionality, but implemented with atomicwriter. There's a slight
difference in error-messages produced (but can be adjusted if we want).

Before:

    docker image save -o ./no/such/foo busybox:latest
    failed to save image: invalid output path: directory "no/such" does not exist

    docker image save -o /no/permissions busybox:latest
    failed to save image: stat /no/permissions: permission denied

After:

    docker image save -o ./no/such/foo busybox:latest
    failed to save image: invalid file path: stat no/such: no such file or directory

    docker image save -o /no/permissions busybox:latest
    failed to save image: failed to stat output path: lstat /no/permissions: permission denied

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 09:46:05 +02:00
Sebastiaan van Stijn 410c0baadd
Merge pull request #5992 from thaJeztah/migrate_archive
migrate to use github.com/moby/go-archive
2025-04-10 09:10:41 +02:00
Sebastiaan van Stijn d83a1b777c
vendor: golang.org/x/net v0.39.0
full diff: https://github.com/golang/net/compare/v0.36.0...v0.39.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 00:01:30 +02:00
Sebastiaan van Stijn b515831508
vendor: golang.org/x/crypto v0.37.0
full diff: https://github.com/golang/crypto/compare/v0.35.0...v0.37.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-10 00:00:46 +02:00
Sebastiaan van Stijn 2d3a81642a
vendor: golang.org/x/text v0.24.0
no changes in vendored files

full diff: https://github.com/golang/text/compare/v0.22.0...v0.24.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-09 23:59:55 +02:00
Sebastiaan van Stijn 69d903e706
vendor: golang.org/x/sync v0.13.0
full diff: https://github.com/golang/sync/compare/v0.11.0...v0.13.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-09 23:59:03 +02:00
Sebastiaan van Stijn e0fa0596a7
vendor: golang.org/x/time v0.11.0
full diff: https://github.com/golang/time/compare/v0.6.0...v0.11.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-09 23:58:09 +02:00
Sebastiaan van Stijn a91d194d7f
vendor: golang.org/x/sys v0.32.0
full diff: https://github.com/golang/sys/compare/v0.31.0...v0.32.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-09 23:57:22 +02:00
Paweł Gronowski a0385bf042
swarm/init: Test `init --external-ca` with custom cert
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-04-09 16:56:26 +02:00
Sebastiaan van Stijn 342a01a9ff
migrate to use github.com/moby/go-archive
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-09 13:18:58 +02:00
Sebastiaan van Stijn 6714b50288
Merge pull request #5921 from thaJeztah/bump_engine
vendor: github.com/docker/docker 185651d26bc6 (master, v28.0-dev)
2025-04-09 13:12:32 +02:00
Sebastiaan van Stijn 2bf317ad5f
vendor: github.com/docker/docker 185651d26bc6 (master, v28.0-dev)
full diff: https://github.com/moby/moby/compare/v28.0.4...185651d26bc6281b199a5b7ff1942b53e4f17b96

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>

vendor: moby with atomicwriter

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-07 19:20:39 +02:00
Sebastiaan van Stijn 91cbde67c5
Merge pull request #5991 from thaJeztah/bump_x_sys
vendor: golang.org/x/sys v0.31.0
2025-04-07 16:02:14 +02:00
Sebastiaan van Stijn 49a36daebe
vendor: golang.org/x/sys v0.31.0
no changes in vendored code

full diff: https://github.com/golang/sys/compare/v0.30.0...v0.31.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-07 13:57:55 +02:00
Sebastiaan van Stijn 90b48f8eb5
Merge pull request #5988 from thaJeztah/bump_sys_user_0.4.0
vendor: github.com/moby/sys/user v0.4.0
2025-04-07 09:37:14 +02:00
Sebastiaan van Stijn 763be9b3f8
Merge pull request #5990 from thaJeztah/bump_compress
vendor: github.com/klauspost/compress v1.18.0
2025-04-07 09:36:52 +02:00
Sebastiaan van Stijn 527998e6ee
Merge pull request #5989 from thaJeztah/bump_go_cmp
vendor: github.com/google/go-cmp v0.7.0
2025-04-07 09:36:33 +02:00
Sebastiaan van Stijn 77f40b8e99
vendor: github.com/klauspost/compress v1.18.0
full diff: https://github.com/klauspost/compress/compare/v1.17.11...v1.18.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-05 16:40:12 +02:00
Sebastiaan van Stijn 205241bcc6
vendor: github.com/google/go-cmp v0.7.0
full diff: https://github.com/google/go-cmp/v0.6.0...v0.7.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-05 16:38:43 +02:00
Sebastiaan van Stijn edd2f7d9fb
vendor: github.com/moby/sys/user v0.4.0
full diff: https://github.com/moby/sys/compare/user/v0.3.0...user/v0.4.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-04 22:01:29 +02:00
Sebastiaan van Stijn bd03f1154f
opts: remove deprecated PortOpt, ConfigOpt, SecretOpt aliases
These options were moved to opts/swarmopts in ad21055bac
and have no known external consumers.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-04 21:45:59 +02:00
Sebastiaan van Stijn 2631d5ba99
Merge pull request #5985 from thaJeztah/command_fix_tests
cli/command: minor test-fixes and cleanups
2025-04-04 18:21:24 +02:00
Sebastiaan van Stijn a2e179457e
Merge pull request #5946 from thaJeztah/prunefilter_cleanup
cli/command: PruneFilters: slight cleanup
2025-04-04 18:19:45 +02:00
Sebastiaan van Stijn 2c3cf8db0f
Merge pull request #5984 from thaJeztah/fix_prune_cancel_errormessage
cli/command/network: fix error-message for cancelled prune
2025-04-04 18:18:46 +02:00
Sebastiaan van Stijn b65f52fd64
Merge pull request #5982 from thaJeztah/context_unexport_limitreader
cli/context/store: un-export LimitedReader
2025-04-04 18:14:52 +02:00
Paweł Gronowski 58fba25b09
Merge pull request #5986 from thaJeztah/bump_golang_1.23.8
update to go1.23.8 (fix CVE-2025-22871)
2025-04-03 11:24:41 +00:00
Sebastiaan van Stijn 64413c20ef
update to go1.23.8 (fix CVE-2025-22871)
full diff: https://github.com/golang/go/compare/go1.23.7...go1.23.8
release notes: https://go.dev/doc/devel/release#go1.24.2

go1.23.8 (released 2025-04-01) includes security fixes to the net/http package,
as well as bug fixes to the runtime and the go command. See the Go 1.23.8
milestone on our issue tracker for details;

https://github.com/golang/go/issues?q=milestone%3AGo1.23.8+label%3ACherryPickApproved

From the mailing list:

Hello gophers,

We have just released Go versions 1.24.2 and 1.23.8, minor point releases.
These minor releases include 1 security fixes following the security policy:

- net/http: request smuggling through invalid chunked data
  The net/http package accepted data in the chunked transfer encoding
  containing an invalid chunk-size line terminated by a bare LF.
  When used in conjunction with a server or proxy which incorrectly
  interprets a bare LF in a chunk extension as part of the extension,
  this could permit request smuggling.
  The net/http package now rejects chunk-size lines containing a bare LF.
  Thanks to Jeppe Bonde Weikop for reporting this issue.
  This is CVE-2025-22871 and Go issue https://go.dev/issue/71988.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-03 12:34:54 +02:00
Sebastiaan van Stijn db44e59be7
cli/command: use stdlib for temp-dirs
gotest.tools' fs package only provides very minimal benefits here;
use stdlib functions to make things slightly more transparent.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-02 16:45:05 +02:00
Sebastiaan van Stijn ce4b752274
cli/command: TestNewDockerCliAndOperators fix unhandled errors
Assert that the write succeeded; also changing `Fprintf` to `Fprint`,
because we were not using templating (we should check why no linter
complained about this).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-02 16:06:10 +02:00
Sebastiaan van Stijn f66c5a33d0
cli/command: TestHooksEnabled: fix test when config file is present
This test verifies the default behavior, but when running the test
in an environment that already has a ~/.docker/config.json present,
it may fail.

This patch updates the test to configure the config-directory to
point to an empty directory, making sure it's not affected by
state.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-02 16:06:07 +02:00
Paweł Gronowski 6523832c73
Merge pull request #5976 from thaJeztah/cli_move_TestExperimentalCLI
cli/command: move TestExperimentalCLI to cli/config
2025-04-02 12:47:32 +00:00
Sebastiaan van Stijn 3122b8e7f5
cli/command/network: fix error-message for cancelled prune
This error-message was updated in 7c722c08d0,
but looks like the typo was overlooked in review.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 23:44:00 +02:00
Sebastiaan van Stijn ed0511251d
cli/command: DockerCli.Initialize: make sure context-store config is set
In most situations, the CLI is created through the `NewDockerCli` constructor,
however, it's possible to construct a CLI manually (`&DockerCli{}`). We
should probably prevent this (and un-export the `DockerCli` implementation),
but currently have some code-paths that depend on the type being exported.

When constructing the CLI with this approach, the CLI would not be fully
initialized and not have the context-store configuration set up.

 Using the default context store without a config set will result in Endpoints
 from contexts not being type-mapped correctly, and used as a generic
 `map[string]any`, instead of a [docker.EndpointMeta].

When looking up the API endpoint (using [EndpointFromContext]), no endpoint
will be found, and a default, empty endpoint will be used instead which in
its turn, causes [newAPIClientFromEndpoint] to be initialized with the default
config instead of settings for the current context (which may mean; connecting
with the wrong endpoint and/or TLS Config to be missing).

I'm not sure if this situation could happen in practice, but it caused some
of our unit-tests ([TestInitializeFromClient] among others) to fail when
running outside of the dev-container on a host that used Docker Desktop's
"desktop-linux" context. In that situation, the test would produce the wrong
"Ping" results (using defaults, instead of the results produced in the test).

This patch:

- updates the contextStoreConfig field to be a pointer, so that we are
  able to detect if a config was already set.
- updates the `Initialize` function to set the default context-store config
  if no config was found (technically the field is mostly immutable, and
  can only set through `WithDefaultContextStoreConfig`, so this may be
  slightly redundant).

We should update this code to be less error-prone to use; the combination
of an exported type (`DockerCli`), a constructor `NewDockerCli` and a
`Initialize` function (as well as some internal contructors to allow
lazy initialization) make constructing the "CLI" hard to use, and there's
various codepaths where it can be in a partially initialized state. The
same applies to the default context store, which also requires too much
"domain" knowledge to use properly.

I'm leaving improvements around that for a follow-up.

[EndpointFromContext]: 33494921b8/cli/context/docker/load.go (L139-L149)
[docker.EndpointMeta]: 33494921b8/cli/context/docker/load.go (L19-L21)
[newAPIClientFromEndpoint]: 33494921b8/cli/command/cli.go (L295-L305)
[TestInitializeFromClient]: 33494921b8/cli/command/cli_test.go (L157-L205)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 23:24:29 +02:00
Sebastiaan van Stijn ce61ea015c
cli/context/store: un-export LimitedReader
It was created for internal use, and is not part of the context-store
public API. It was introduced as part of the "zip import" functionality
added in 291e86289b. Initially it was
[non-exported][1], but during review, some suggestions were made to improve
the implementation, and the [suggested implementation][2] was based on
Go stdlib, but review overlooked that the implementation was now exported.

Let's un-export it, as this was (as outlined) never meant to be a public
type.

[1]: https://github.com/docker/cli/pull/1895#discussion_r287514522
[2]: https://github.com/docker/cli/pull/1895#discussion_r288688768

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 22:03:27 +02:00
Sebastiaan van Stijn cda7235c81
context list: remove temporary ContextType from JSON output
This reverts commit fed9fa0f72.

This removes the ContextType field, which was temporarily added to provide
compatibility with the "compose-cli" wrapper that shipped with Docker Desktop.
The compose-cli wrapper extended the context struct with an additional field
that was not part of the CLI itself, but was used by Visual Studio to detect
the type of context.

This temporary field shipped as part of Docker 27.0 June 2024), which should
be enough time for Visual Studio to have adjusted their integration.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 19:46:36 +02:00
Sebastiaan van Stijn c8f9187157
cli/config/configfile: deprecate ConfigFile.Experimental field
Configuration options for experimental CLI features were deprecated in
docker 19.03 (3172219932), and enabled by
default since docker 20.10 (977d3ae046).

This deprecates the corresponding field in the config-file.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 17:08:05 +02:00
Sebastiaan van Stijn 0dabdd1a0d
cli/command: move TestExperimentalCLI to cli/config
This test was only testing whether we could load a legacy config-file that
contained the "experimental" (experimental CLI) option. Experimental cli
options are disabled since 977d3ae046 (20.10),
and now enabled by default, but we should not fail to start the cli if the
config-file contains the option.

Move the test to the config package, as it doesn't need the cli for this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 17:06:39 +02:00
Sebastiaan van Stijn 33494921b8
Merge pull request #5980 from thaJeztah/container_use_subtests
cli/command/container: TestNewCreateCommandWithContentTrustErrors use subtests
2025-04-01 16:24:05 +02:00
Sebastiaan van Stijn c911ced1a4
Merge pull request #5979 from thaJeztah/fix_TestNewPortCommandOutput
cli/command/container: TestNewPortCommandOutput: remove DCT
2025-04-01 15:47:12 +02:00
Sebastiaan van Stijn d726a9b4cd
Merge pull request #5978 from thaJeztah/cli_command_update_TestNewDockerCliAndOperators
cli/command: TestNewDockerCliAndOperators: update test without DCT
2025-04-01 15:46:32 +02:00
Sebastiaan van Stijn 1c54b0ba66
Merge pull request #5975 from thaJeztah/internalize_image_runsave
cli/command/image: deprecate RunPull and make internal
2025-04-01 15:14:17 +02:00
Sebastiaan van Stijn 4a3466eeb6
cli/command/container: TestNewCreateCommandWithContentTrustErrors use-subtests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 14:53:51 +02:00
Sebastiaan van Stijn 12d637c1b5
cli/command/container: TestNewPortCommandOutput: remove DCT
This looks like a copy/paste from other tests, because this test
does not test anything related to docker content trust.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 14:48:02 +02:00
Sebastiaan van Stijn 8f9fec11ab
cli/command: TestNewDockerCliAndOperators: update test without DCT
Use something more generic to verify the behavior.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 13:07:02 +02:00
Sebastiaan van Stijn 2328745f92
cli/command/image: deprecate RunPull and make internal
This function was exported in 812f113685
for use in other parts of the CLI, but it's now only used locally.

Make it internal again, as it was never designed to be exported. There
are no known external consumers of this function, but deprecating it
first, in case there are.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 09:33:04 +02:00
Sebastiaan van Stijn b557e37a49
cli/command/image: un-export RunSave
This function was exported in e43c7920ea
for use of "docker app", which is now deprecated. The signature of this
function also depended on a non-exported type, so it could not be used
externally.

Make it internal again, as it was never designed to be exported. There
are no known external consumers of this function.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 09:32:58 +02:00
Sebastiaan van Stijn 9b2479dca7
cli/command/image: un-export RunPush
This function was exported in e43c7920ea
for use of "docker app", which is now deprecated. The signature of this
function also depended on a non-exported type so it could not be used
externally.

Make it internal again, as it was never designed to be exported. There
are no known external consumers of this function.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-04-01 09:31:57 +02:00
Paweł Gronowski 2b84421520
Merge pull request #5974 from thaJeztah/bump_docker_28.0.4
vendor: github.com/docker/docker v28.0.4
2025-03-31 17:04:12 +00:00
Sebastiaan van Stijn 207a1a0dd8
Merge pull request #5973 from thaJeztah/remove_deprecated_isautomated_docs
docs/reference: search: remove mention of deprecated "IsAutomated"
2025-03-31 19:02:58 +02:00
Sebastiaan van Stijn 850fea8023
vendor: github.com/docker/docker v28.0.4
no changes in vendored files

full diff: https://github.com/docker/docker/compare/v28.0.3...v28.0.4

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-31 18:13:45 +02:00
Sebastiaan van Stijn 8b222aedfa
docs/reference: search: remove mention of deprecated "IsAutomated"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-31 17:45:20 +02:00
Sebastiaan van Stijn 0c4912b0ec
Merge pull request #5958 from thaJeztah/login_message
cli/command/registry: loginClientSide: use locally defined message
2025-03-31 14:46:18 +02:00
Paweł Gronowski 8e6de54d18
Merge pull request #5961 from thaJeztah/trust_remove_intermediate_var
cli/trust: GetNotaryRepository: remove intermediate var
2025-03-31 11:40:13 +00:00
Paweł Gronowski fc817a1367
Merge pull request #5970 from thaJeztah/swarm_completion_cleanup
cli/command/service: un-export CompletionFn
2025-03-31 11:39:37 +00:00
Sebastiaan van Stijn 30c20d5c8c
Merge pull request #5966 from thaJeztah/man_rewrite
man: rewrite to use cli-docs-tool manpage generator
2025-03-27 21:01:51 +01:00
Sebastiaan van Stijn 99a6126cfe
Merge pull request #5959 from thaJeztah/registry_client_skip_RepositoryInfo
cli/registry/client: skip RepositoryInfo as intermediate
2025-03-27 18:46:39 +01:00
Sebastiaan van Stijn 491e8fdaf8
cli/registry/client: skip RepositoryInfo as intermediate
Remove RepositoryInfo as intermediate struct in some places; we want
to remove the use of this additional abstration. More changes are
needed to fully remove it, but chipping away its use in small bits.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-27 13:34:05 +01:00
Sebastiaan van Stijn 930173a2ab
Merge pull request #5969 from thaJeztah/simplify_auth_fixed
cli/command: Reapply "remove uses of GetAuthConfigKey, ParseRepositoryInfo" and add test
2025-03-27 13:24:10 +01:00
Sebastiaan van Stijn 242422bbb3
cli/command/service: un-export CompletionFn
It's only used internally, and has no external consumers. Un-export
it, rename it to something more descriptive, and move it to a separate
file to align with other packages.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-27 09:59:29 +01:00
Sebastiaan van Stijn 3fe40e5ea9
Merge pull request #5950 from thaJeztah/dockerfile_linting
Dockerfile: fix JSONArgsRecommended warning
2025-03-26 19:17:42 +01:00
Sebastiaan van Stijn f1385df2a7
Merge pull request #5968 from albers/completion-service-scale
Improve completion of `service scale` args
2025-03-26 17:41:50 +01:00
Sebastiaan van Stijn 0e32baf115
cli/command: fix regression in resolving auth from config
This was introduced in 79141ce5eb, which
was reverted in f596202125, and re-applied
in the previous commit.

Before this patch, saving credentials worked correctly;

    docker login -u thajeztah
    Password:
    Login Succeeded

    cat ~/.docker/config.json
    {
        "auths": {
            "https://index.docker.io/v1/": {
                "auth": "REDACTED"
            }
        }
    }

But when resolving the credentials, the credentials stored would not be found;

    docker pull -q thajeztah/private-test-image
    Error response from daemon: pull access denied for thajeztah/private-test-image, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

With this patch applied:

    docker pull -q thajeztah/private-test-image
    docker.io/thajeztah/private-test-image:latest

Thanks to mtrmac (Miloslav Trmač) for spotting this mistake!

Suggested-by: Miloslav Trmač <mitr@redhat.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-26 14:43:57 +01:00
Sebastiaan van Stijn 9f4165ccb8
Reapply "cli/command: remove uses of GetAuthConfigKey, ParseRepositoryInfo"
This reverts commit f596202125, and reapplies
79141ce5eb.

> cli/command: remove uses of GetAuthConfigKey, ParseRepositoryInfo
>
> Re-implement locally, based on the code in github.com/docker/docker/registry,
> but leaving out bits that are not used on the client-side, such as
> configuration of Mirrors, and configurable insecure-registry, which
> are not used on the client side.

This commit contains a regression due to a typo in `authConfigKey`;

    const authConfigKey = "https:/index.docker.io/v1/"

Which is missing a `/` after the scheme.

Which currently fails the TestRetrieveAuthTokenFromImage test.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-26 14:30:06 +01:00
Sebastiaan van Stijn 15b95beac7
cli/command: add unit-test for RetrieveAuthTokenFromImage
It's currently slower because it calls registry.ParseRepositoryInfo,
which does a DNS lookup for hostnames to determine if they're a loopback
address (and marked "insecure");

    go test -v -run TestRetrieveAuthTokenFromImage
    === RUN   TestRetrieveAuthTokenFromImage
    === RUN   TestRetrieveAuthTokenFromImage/no-prefix
    === RUN   TestRetrieveAuthTokenFromImage/docker.io
    === RUN   TestRetrieveAuthTokenFromImage/index.docker.io
    === RUN   TestRetrieveAuthTokenFromImage/registry-1.docker.io
    === RUN   TestRetrieveAuthTokenFromImage/registry.hub.docker.com
    === RUN   TestRetrieveAuthTokenFromImage/[::1]
    === RUN   TestRetrieveAuthTokenFromImage/[::1]:5000
    === RUN   TestRetrieveAuthTokenFromImage/127.0.0.1
    === RUN   TestRetrieveAuthTokenFromImage/localhost
    === RUN   TestRetrieveAuthTokenFromImage/localhost:5000
    === RUN   TestRetrieveAuthTokenFromImage/no-auth.example.com
    --- PASS: TestRetrieveAuthTokenFromImage (0.35s)
        --- PASS: TestRetrieveAuthTokenFromImage/no-prefix (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/docker.io (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/index.docker.io (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/registry-1.docker.io (0.08s)
        --- PASS: TestRetrieveAuthTokenFromImage/registry.hub.docker.com (0.12s)
        --- PASS: TestRetrieveAuthTokenFromImage/[::1] (0.13s)
        --- PASS: TestRetrieveAuthTokenFromImage/[::1]:5000 (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/127.0.0.1 (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/localhost (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/localhost:5000 (0.00s)
        --- PASS: TestRetrieveAuthTokenFromImage/no-auth.example.com (0.01s)
    PASS
    ok  	github.com/docker/cli/cli/command	1.367s

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-26 14:25:50 +01:00
albers ee275d5733 Improve completion of `service scale` args
Signed-off-by: albers <github@albersweb.de>
2025-03-25 21:46:44 +00:00
Sebastiaan van Stijn 80bca8eb1d
man: rewrite to use cli-docs-tool manpage generator
It's a wrapper around Cobra's generator, but handles some special
cases. While rewriting, also rewrite the generator code to align
with the mddocs/yamldocs counterpart in docs/generate/

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-25 17:07:40 +01:00
Sebastiaan van Stijn 1a14abb748
cli/command/registry: loginClientSide: use locally defined message
The "Service.Auth" pretended to return a message from the registry,
but the message returned is hard-coded in the registry package.

Remove its use to make this more transparent, and not to pretend
this is anything returned by the registry.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-25 16:07:48 +01:00
Paweł Gronowski b8034c0ed7
Merge pull request #5962 from thaJeztah/bump_docker_28.0.3
vendor: github.com/docker/docker v28.0.3
2025-03-25 15:03:35 +00:00
Sebastiaan van Stijn 3e699a351f
Merge pull request #5964 from vvoland/fix-auth-regressionq
Revert "cli/command: remove uses of GetAuthConfigKey, ParseRepositoryInfo"
2025-03-25 15:52:46 +01:00
Paweł Gronowski f596202125
Revert "cli/command: remove uses of GetAuthConfigKey, ParseRepositoryInfo"
This reverts commit 79141ce5eb.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-25 15:37:51 +01:00
Sebastiaan van Stijn ee2f787634
cli/config: update link to current version
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-25 14:37:59 +01:00
Sebastiaan van Stijn d8432cdf23
vendor: github.com/docker/docker v28.0.3
no diff; same commit, but tagged

full diff: https://github.com/docker/docker/compare/330857ad0ffb...v28.0.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-25 14:37:53 +01:00
Sebastiaan van Stijn 60645d29f4
cli/trust: GetNotaryRepository: remove intermediate var
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-25 11:48:41 +01:00
Paweł Gronowski 2b0631f45e
Merge pull request #5941 from thaJeztah/TestUserTerminatedError_handle_errs
cmd/dockerd: TestUserTerminatedError: fix unhandled errors
2025-03-25 10:01:34 +00:00
Paweł Gronowski 84828b0eb8
Merge pull request #5960 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.0.3-dev (330857ad0ffb)
2025-03-25 09:55:03 +00:00
Paweł Gronowski b5ca7e8e6b
vendor: github.com/docker/docker v28.0.3-dev (330857ad0ffb)
full diff: https://github.com/docker/docker/compare/v28.0.2...330857ad0ffb

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-25 10:30:54 +01:00
Paweł Gronowski cfaaeb0982
Merge pull request #5957 from vvoland/stdout-trunc
container/run: Fix stdout/err truncation after container exit
2025-03-24 16:14:50 +00:00
Paweł Gronowski 5a8120c809
container/run: Fix TestRunAttachTermination
Restore part of the code removed by 966b44183f
that closed the stream. It's required now because the Run command won't
finish before the output stream was processed by the caller.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-24 17:09:35 +01:00
Paweł Gronowski c27751fcfe
container/run: Fix stdout/err truncation after container exit
Fix a regression introduced by 30c4637f03
which made the `docker run` command produce potentially truncated
stdout/stderr output.

Previous implementation stopped the content streaming as soon as the
container exited which would potentially truncate a long outputs.

This change fixes the issue by only canceling the IO stream immediately
if neither stdout nor stderr is attached.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-24 17:09:32 +01:00
Sebastiaan van Stijn 7b348e4e94
Dockerfile: fix JSONArgsRecommended warning
1 warning found (use docker --debug to expand):
    - JSONArgsRecommended: JSON arguments recommended for CMD to prevent unintended behavior related to OS signals (line 120)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-21 20:42:17 +01:00
Sebastiaan van Stijn ff5fdfae35
Merge pull request #5829 from thaJeztah/bump_cobra
vendor: github.com/spf13/cobra v1.9.1
2025-03-21 20:42:08 +01:00
Sebastiaan van Stijn 9f19820f88
cli/command/completion: deprecate ValidArgsFn
Cobra now defines a CompletionFunc for the same, so we can alias
it to that, and stop using our own definition.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-21 20:30:58 +01:00
Sebastiaan van Stijn 7607c3f945
vendor: github.com/spf13/cobra v1.9.1
full diff: https://github.com/spf13/cobra/compare/v1.8.1...v1.9.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-21 20:30:54 +01:00
Sebastiaan van Stijn 61cd986723
Merge pull request #4903 from thaJeztah/carry_docs_no_internet
docs: include required tools in source tree
2025-03-21 18:49:27 +01:00
Sebastiaan van Stijn d97f65c4da
cli/command: PruneFilters: slight cleanup
- remove pruneFilters.Contains for checks, as this is already
  handled by pruneFilters.ExactMatch.
- Update GoDoc to better describe the function's functionality
- Use a swtich instead of if/else.

This function should be moved to a separate package; possibly splitting
it out to a "Merge" function that accepts two filter.Args as argument.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-21 13:50:09 +01:00
Sebastiaan van Stijn 30cac75693
Merge pull request #5945 from stevvooe/sjd/remove-flaky-test
e2e: skip flaky test
2025-03-21 13:49:19 +01:00
Sebastiaan van Stijn 255a5f630e
Merge pull request #5876 from thaJeztah/less_notary
cli/command, cil/command/image: remove deprecated methods and functions
2025-03-21 09:31:23 +01:00
Sebastiaan van Stijn 535bb6c85c
rewrite using "with-go-mod.sh" script and "go run"
Use the same script as is used in moby/moby, which more gracefully
handles an existing `go.mod` (which can be symlinked) into account.

- keep the scripts called generic, and update the Makefile to invoke
  them with the "with-go-mod.sh" script.
- use "go run" instead of building temporary binaries
- check if go-md2man exists before building a binary

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-21 00:36:47 +01:00
Aleksa Sarai 47775a8fa0
docs: include required tools in source tree
In order to be able to build the documentation without internet access
(as is required by some distribution build systems), all of the source
code needed for the build needs to be available in the source tarball.

This used to be possible with the docker-cli sources but was
accidentally broken with some CI changes that switched to downloading
the tools (by modifying go.mod as part of the docs build script).

This pattern also maked documentation builds less reproducible since the
tool version used was not based on the source code version.

Fixes: 7dc35c03fc ("validate manpages target")
Fixes: a650f4ddd0 ("switch to cli-docs-tool for yaml docs generation")
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-21 00:13:56 +01:00
Stephen Day 4a80c6da83
e2e: skip flaky test
Signed-off-by: Stephen Day <stephen.day@docker.com>
2025-03-20 07:56:28 -07:00
Sebastiaan van Stijn b199ece92a
Merge pull request #5939 from thaJeztah/cmd_dockerd_stdlib_errs
cmd/dockerd: use stdlib errors
2025-03-20 15:20:20 +01:00
Paweł Gronowski 48741f72ff
Merge pull request #5944 from thaJeztah/vendor_docker_28.0.2
vendor: github.com/docker/docker v28.0.2
2025-03-20 11:58:58 +00:00
Sebastiaan van Stijn 4541df21e5
cli/command/image: remove deprecated TagTrusted
This function was only used internally, and has no known external consumers.
It was deprecated in e37d814ce96b01393a400c081666ea1cca2eb8bd; this commit
removes it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-20 11:11:39 +01:00
Sebastiaan van Stijn eaf98b2202
cli/command/image: remove deprecated PushTrustedReference
This function was only used internally, and has no known external consumers.
It was deprecated in d80436021c21c26b492f0014511f13f41d8b42d9; this commit
removes it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-20 11:11:39 +01:00
Sebastiaan van Stijn 98d0b0cc14
cli/command/image: remove deprecated TrustedPush
This function was only used by "docker trust sign", and has no known external
consumers. It was deprecated in c6f456bc90574f4180f3b990e8a4e216485e35b7;
this commit removes it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-20 11:11:39 +01:00
Sebastiaan van Stijn 5ea072d936
cli/command: remove deprecated RegistryClient from CLI interface
This method was a shallow wrapper around registryclient.NewRegistryClient but
due to its signature resulted in various dependencies becoming a dependency
of the "command" package. Consequence of this was that cli-plugins, which
need the cli/command package, would also get those dependencies. It is no
longer used, and was deprecated in 8ad07217dc.

This patch removes the RegistryClient method from the interface

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-20 11:11:38 +01:00
Sebastiaan van Stijn 08f86507b4
cli/command: remove deprecated ManifestStore from CLI interface
This method is a shallow wrapper around manifeststore.NewStore, but
due to its signature resulted in various dependencies becoming a dependency
of the "command" package. Consequence of this was that cli-plugins, which
need the cli/command package, would also get those dependencies. It is no
longer used, and was deprecated in e32d5d56f5.

This patch removes the ManifestStore method from the interface

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-20 11:11:38 +01:00
Sebastiaan van Stijn 66eb27a487
cli/command: remove deprecated NotaryClient from CLI interface
This method is a shallow wrapper around trust.GetNotaryRepository, but
due to its signature resulted in the trust package, and notary dependencies
to become a dependency of the CLI. Consequence of this was that cli-plugins,
which need the cli/command package, would also get notary and its
dependencies as a dependency. It is no longer used, and was deprecated
in 9bc16bbde0.

This patch removes the NotaryClient method from the interface

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-20 11:11:35 +01:00
Sebastiaan van Stijn e002576821
Merge pull request #5942 from thaJeztah/simplify_auth_step1
cli/command: remove uses of GetAuthConfigKey, ParseRepositoryInfo
2025-03-20 11:10:47 +01:00
Sebastiaan van Stijn a9ac6fa376
vendor: github.com/docker/docker v28.0.2
no diff; same commit, but tagged:

full diff: https://github.com/docker/docker/compare/bea4de25004d...v28.0.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 18:27:29 +01:00
Sebastiaan van Stijn 23eadcd950
Merge pull request #5936 from thaJeztah/plugin_manager_cleanups
cli-plugins/manager: minor cleanups and refactoring
2025-03-19 16:13:13 +01:00
Sebastiaan van Stijn 3b45f3c09a
Merge pull request #5926 from Benehiko/fix-attach-test-flake
test: fix flaky TestRunAttachTermination
2025-03-19 16:10:49 +01:00
Sebastiaan van Stijn 79141ce5eb
cli/command: remove uses of GetAuthConfigKey, ParseRepositoryInfo
Re-implement locally, based on the code in github.com/docker/docker/registry,
but leaving out bits that are not used on the client-side, such as
configuration of Mirrors, and configurable insecure-registry, which
are not used on the client side.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 15:34:57 +01:00
Paweł Gronowski 0442a7378f
Merge pull request #5929 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.0.2-dev (bea4de25004d)
2025-03-19 13:13:31 +00:00
Sebastiaan van Stijn 082dfb7360
cmd/dockerd: use stdlib errors
This package is not imported externally, and we don't need the added
functionality of pkg/errors here, so use stdlib errors.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 14:04:44 +01:00
Sebastiaan van Stijn f519a8648d
cmd/dockerd: TestUserTerminatedError: fix unhandled errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 14:01:38 +01:00
Sebastiaan van Stijn bb0e9adbc0
remove redundant error-handling for registry.ParseRepositoryInfo
Since [moby@c2c3d59], [registry.ParseRepositoryInfo] now always returns
a nil error, so we can remove the error handling.

[registry.ParseRepositoryInfo]: 5f0d6731eb/registry/config.go (L414-L443)
[moby@c2c3d59]: c2c3d593cf

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-19 13:55:38 +01:00
Sebastiaan van Stijn e0979b3adf
cli/command: remove ValidateMountWithAPIVersion
This validation is now handled by the API-client since [moby@5d6b566],
so no longer needed to be done in the cli. This function was only used
internally and has no external consumers, so removing it without
deprecating first.

[moby@5d6b566]: 5d6b56699d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-19 13:53:24 +01:00
Paweł Gronowski cab5164877
vendor: github.com/docker/docker v28.0.2-dev (bea4de25004d)
full diff: https://github.com/docker/docker/compare/v28.0.1...bea4de25004d

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-19 13:21:19 +01:00
Paweł Gronowski 888716aa59
Merge pull request #5932 from vvoland/TestConnectAndWait-flaky
test/cli-plugins: Attempt to make TestConnectAndWait less flaky
2025-03-19 12:19:18 +00:00
Sebastiaan van Stijn 667fa7bc92
cli: remove uses of deprecated registry.SetCertsDir
Starting with [moby@b633c4c], the registry package handles this internally
and there's no longer a need to set the path manually for rootlessKit

[moby@b633c4c]: b633c4cc33

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-19 13:18:23 +01:00
Sebastiaan van Stijn 63f5930c17
Merge pull request #5784 from thaJeztah/docs_gen_no_pkg_errors
docs/generate: remove uses of pkg/errors
2025-03-19 13:09:16 +01:00
Sebastiaan van Stijn 0f75059e9f
Merge pull request #5938 from thaJeztah/man_cleans
man: fix minor linting issues
2025-03-19 12:49:12 +01:00
Paweł Gronowski 0ce8989a78
test/cli-plugins: Try to make TestConnectAndWait less flaky
- Add runtime.Gosched() calls to encourage goroutine scheduling
- Increase the timeout from 10ms to 500ms
- Use poll.WaitOn with appropriate delays to ensure the goroutine has
  spawned before checking
- Lock the test goroutines to its own thread

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-19 11:52:07 +01:00
Sebastiaan van Stijn 2f795987d6
docs/generate: remove uses of pkg/errors
While there may be reasons to keep pkg/errors in production code,
we don't need them for this generator code.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 10:49:16 +01:00
Sebastiaan van Stijn 5185ab89fe
man: loadLongDescription: rename arg to avoid shadowing
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 10:48:11 +01:00
Sebastiaan van Stijn 344a85eae6
man: fix unhandled error in loadLongDescription
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 10:48:11 +01:00
Sebastiaan van Stijn c81f38feac
man: remove legacy build-tags
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-19 10:48:10 +01:00
Alano Terblanche 353230d978
system/info: failure to connect to docker socket on `docker info` should propagate error
This patch propagates the error up the stack when running `docker info`
and a connection error to the server occurs.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-03-18 16:58:59 +01:00
Alano Terblanche 966b44183f
test: fix flaky TestRunAttachTermination
This patch fixes the `TestRunAttachTermination` flaky runs.
It seems like we weren't halting on the `waitFunc` so if the
process was fast enough to setup the signal handler and execute
`waitExitOrRemoved`. We now instead wait for the `killCh` channel
to close inside the mocked `waitFunc`.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-03-18 16:11:54 +01:00
Sebastiaan van Stijn ecfdf74115
Merge pull request #5912 from thaJeztah/refactor_secret_config_create
secret create, config create: refactor, use limit reader, and touch up errors
2025-03-18 15:52:36 +01:00
Sebastiaan van Stijn d6d8ca6ebe
config create: refactor, use limit reader, and touch up errors
Swarm has size constraints on the size of configs, but the client-side would
read content into memory, regardless its size. This could lead to either the
client reading too much into memory, or it sending data that's larger than
the size limit of gRPC, which resulted in the error not being handled by
SwarmKit and a generic gRPC error returned.

Reading a config from a file used a system.OpenSequential for reading
([FILE_FLAG_SEQUENTIAL_SCAN]). While there could be a very marginal benefit
to prevent polluting the system's cache (Windows won’t aggressively keep it
in the cache, freeing up system memory for other tasks). These details were
not documented in code, and possibly may be too marginal, but adding a comment
to outline won't hurt so this patch also adds a comment.

This patch:

- Factors out the reading code to a readConfigData, analogous to the
  equivalent in secret create.
- Implements reading the data with a limit-reader to prevent reading
  large files into memory.
- The limit is based on SwarmKits limits ([MaxConfigSize]), but made
  twice that size, just in case larger sizes are supported in future;
  the main goal is to have some constraints, and to prevent hitting
  the gRPC limit.
- Updates some error messages to include STDIN (when used), or the
  filename (when used).

Before this patch:

    ls -lh largefile
    -rw-------  1 thajeztah  staff   8.1M Mar  9 00:19 largefile

    docker config create nosuchfile ./nosuchfile
    Error reading content from "./nosuchfile": open ./nosuchfile: no such file or directory

    docker config create toolarge ./largefile
    Error response from daemon: rpc error: code = ResourceExhausted desc = grpc: received message larger than max (8462870 vs. 4194304)

    docker config create empty ./emptyfile
    Error response from daemon: rpc error: code = InvalidArgument desc = config data must be larger than 0 and less than 1024000 bytes

    cat ./largefile | docker config create toolarge -
    Error response from daemon: rpc error: code = ResourceExhausted desc = grpc: received message larger than max (8462870 vs. 4194304)

    cat ./emptyfile | docker config create empty -
    Error response from daemon: rpc error: code = InvalidArgument desc = config data must be larger than 0 and less than 1024000 bytes

With this patch:

    docker config create nosuchfile ./nosuchfile
    error reading from ./nosuchfile: open ./nosuchfile: no such file or directory

    docker config create empty ./emptyfile
    error reading from ./emptyfile: data is empty

    docker config create toolarge ./largefile
    Error response from daemon: rpc error: code = InvalidArgument desc = config data must be larger than 0 and less than 1024000 bytes

    cat ./largefile | docker config create toolarge -
    Error response from daemon: rpc error: code = InvalidArgument desc = secret data must be larger than 0 and less than 1024000 bytes

    cat ./emptyfile | docker config create empty -
    error reading from STDIN: data is empty

[FILE_FLAG_SEQUENTIAL_SCAN]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#FILE_FLAG_SEQUENTIAL_SCAN
[MaxConfigSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/manager/controlapi#MaxConfigSize

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 14:48:15 +01:00
Sebastiaan van Stijn 3a35b16669
secret create: refactor, use limit reader, and touch up errors
Swarm has size constraints on the size of secrets, but the client-side would
read content into memory, regardless its size. This could lead to either the
client reading too much into memory, or it sending data that's larger than
the size limit of gRPC, which resulted in the error not being handled by
SwarmKit and a generic gRPC error returned.

Reading a secret from a file was added in [moby@c6f0b7f], which used a
system.OpenSequential for reading ([FILE_FLAG_SEQUENTIAL_SCAN]). While
there could be a very marginal benefit to prevent polluting the system's
cache (Windows won’t aggressively keep it in the cache, freeing up system
memory for other tasks). These details were not documented in code, and
possibly may be too marginal, but adding a comment to outline won't hurt
so this patch also adds a comment.

This patch:

- Rewrites readSecretData to not return a nil-error if no file was
  set, in stead only calling it when not using a driver.
- Implements reading the data with a limit-reader to prevent reading
  large files into memory.
- The limit is based on SwarmKits limits ([MaxSecretSize]), but made
  twice that size, just in case larger sizes are supported in future;
  the main goal is to have some constraints, and to prevent hitting
  the gRPC limit.
- Updates some error messages to include STDIN (when used), or the
  filename (when used).

Before this patch:

    ls -lh largefile
    -rw-------  1 thajeztah  staff   8.1M Mar  9 00:19 largefile

    docker secret create nosuchfile ./nosuchfile
    Error reading content from "./nosuchfile": open ./nosuchfile: no such file or directory

    docker secret create toolarge ./largefile
    Error response from daemon: rpc error: code = ResourceExhausted desc = grpc: received message larger than max (8462870 vs. 4194304)

    docker secret create empty ./emptyfile
    Error response from daemon: rpc error: code = InvalidArgument desc = secret data must be larger than 0 and less than 512000 bytes

    cat ./largefile | docker secret create toolarge -
    Error response from daemon: rpc error: code = ResourceExhausted desc = grpc: received message larger than max (8462870 vs. 4194304)

    cat ./emptyfile | docker secret create empty -
    Error response from daemon: rpc error: code = InvalidArgument desc = secret data must be larger than 0 and less than 512000 bytes

With this patch:

    docker secret create nosuchfile ./nosuchfile
    error reading from ./nosuchfile: open ./nosuchfile: no such file or directory

    docker secret create empty ./emptyfile
    error reading from ./emptyfile: data is empty

    docker secret create toolarge ./largefile
    Error response from daemon: rpc error: code = InvalidArgument desc = secret data must be larger than 0 and less than 512000 bytes

    cat ./largefile | docker secret create toolarge -
    Error response from daemon: rpc error: code = InvalidArgument desc = secret data must be larger than 0 and less than 512000 bytes

    cat ./emptyfile | docker secret create empty -
    error reading from STDIN: data is empty

[moby@c6f0b7f]: c6f0b7f448
[FILE_FLAG_SEQUENTIAL_SCAN]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#FILE_FLAG_SEQUENTIAL_SCAN
[MaxSecretSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/api/validation#MaxSecretSize

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 14:47:56 +01:00
Sebastiaan van Stijn 091421f13f
cli-plugins/manager: getPluginDirs: remove redundant error-return
This function returned an error (if any) from [config.Path]. However, the
only situation in which an error could be returned was if the given path
to append to `config.Dir` was outside of the config directory. This can
only happen if the path to append would try to traverse directories (e.g.,
passing `../../cli-plugins`).

Given that we're passing a hard-coded value, that would not be the case,
so we can simplify the code to join the path directly, and don't have to
handle errors.

[config.Path]: 2d74733942/cli/config/config.go (L100-L107)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 12:10:38 +01:00
Sebastiaan van Stijn d1a19d4476
cli-plugins/manager: ListPlugins: return early if no candidates
Skip the other logic, which includes listing all commands provided; if
there's no plugin-candidates, those steps won't be needed.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 12:10:38 +01:00
Sebastiaan van Stijn 40725aea3c
cli-plugins/manager: add test for empty / non-existing plugin dirs
Verify that listPluginCandidates returns an empty result if nothing was
found.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 12:10:38 +01:00
Sebastiaan van Stijn fdcfd229aa
cli-plugins/manager: rename var that shadowed arg in test
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 12:10:38 +01:00
Sebastiaan van Stijn abd02b6a23
cli-plugins/manager: ListPlugins: pass context to error-group
This error-group was added in 89583b92b7, but
passed a context.TODO because the function didn't have a context as argument.

However, it does get the root-command passed, which holds the context, so
we can pass that.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-18 12:10:28 +01:00
Sebastiaan van Stijn 2d74733942
Merge pull request #5869 from thaJeztah/bump_crypto
vendor: golang.org/x/crypto v0.35.0
2025-03-11 10:10:04 +01:00
Sebastiaan van Stijn d421dea843
Merge pull request #5908 from thaJeztah/client_api_version
remove uses of cli.DefaultVersion()
2025-03-11 10:07:31 +01:00
Sebastiaan van Stijn 4bdfd3b684
vendor: golang.org/x/crypto v0.35.0
We have tagged version v0.35.0 of golang.org/x/crypto in order to address
a security issue. Version v0.35.0 of golang.org/x/crypto fixes a vulnerability
in the golang.org/x/crypto/ssh package which could cause a denial of service.
SSH servers which implement file transfer protocols are vulnerable to a denial
of service attack from clients which complete the key exchange slowly, or not
at all, causing pending content to be read into memory, but never transmitted.
Thanks to Yuichi Watanabe for reporting this issue.
This is CVE-2025-22869 and Go issue https://go.dev/issue/71931.

full diff: https://github.com/golang/crypto/compare/v0.31.0...v0.35.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 20:04:11 +01:00
Sebastiaan van Stijn 09caaa312d
vendor: golang.org/x/crypto v0.34.0
No code-changes, but updates the minimum go version to go1.23:

> all: upgrade go directive to at least 1.23.0 [generated]
>
> By now Go 1.24.0 has been released, and Go 1.22 is no longer supported
> per the Go Release Policy (https://go.dev/doc/devel/release#policy).
>
> For golang/go#69095.

full diff: https://github.com/golang/crypto/compare/v0.31.0...v0.34.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 20:04:11 +01:00
Sebastiaan van Stijn 4dfe7ad85e
vendor: golang.org/x/text v0.22.0
no code-changes in vendored files.

full diff: https://github.com/golang/text/compare/v0.21.0...v0.22.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 20:04:11 +01:00
Sebastiaan van Stijn 3cdc44568d
vendor: golang.org/x/sync v0.11.0
no code-changes, only a godoc comment updated

full diff: https://github.com/golang/sync/compare/v0.10.0...v0.11.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 20:04:11 +01:00
Sebastiaan van Stijn 19ce7f2eaf
vendor: golang.org/x/sys v0.30.0
full diff: https://github.com/golang/sys/compare/v0.29.0...v0.30.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 20:04:10 +01:00
Sebastiaan van Stijn 1673cd88a8
Merge pull request #5920 from thaJeztah/vendor_min_go_version
vendor.mod: update minimum go version to go1.23
2025-03-10 20:03:11 +01:00
Sebastiaan van Stijn a9e6180cd8
vendor.mod: update minimum go version to go1.23
Go maintainers started to unconditionally update the minimum go version
for golang.org/x/ dependencies to go1.23, which means that we'll no longer
be able to support any version below that when updating those dependencies;

> all: upgrade go directive to at least 1.23.0 [generated]
>
> By now Go 1.24.0 has been released, and Go 1.22 is no longer supported
> per the Go Release Policy (https://go.dev/doc/devel/release#policy).
>
> For golang/go#69095.

This updates our minimum version to go1.23, as we won't be able to maintain
compatibility with older versions because of the above.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 18:29:49 +01:00
Sebastiaan van Stijn 3d3f78028a
Merge pull request #5919 from thaJeztah/no_generics
cli/command/formatter: add missing go:build tag
2025-03-10 18:18:06 +01:00
Sebastiaan van Stijn 64b56179b5
Merge pull request #5907 from thaJeztah/opts_cleanup
opts: remove uses pkg/errors, and move swarm-specific opts to a separate package
2025-03-10 18:03:49 +01:00
Sebastiaan van Stijn 29c1ababd7
Merge pull request #5903 from thaJeztah/cli_plugins_no_pkg_errors
cli-plugins/manager: use stdlib errors, and minor cleanup
2025-03-10 18:02:58 +01:00
Sebastiaan van Stijn 2cd4786630
cli/command/formatter: add missing go:build tag
Seen failing when used elsewhere;

    vendor/github.com/docker/cli/cli/command/formatter/displayutils.go:78:20: predeclared any requires go1.18 or later (-lang was set to go1.16; check go.mod)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-10 17:39:06 +01:00
Sebastiaan van Stijn 571124d4b0
Merge pull request #5909 from thaJeztah/move_winresources
move winresources into cmd/docker
2025-03-10 16:30:38 +01:00
Sebastiaan van Stijn 60ae1bb1fc
Merge pull request #5910 from thaJeztah/move_service_logs
service/logs: move to cli/internal/logdetails
2025-03-10 16:14:22 +01:00
Sebastiaan van Stijn 879acd15ff
Merge pull request #5911 from thaJeztah/builder_nits
cli/command/image: fix some minor linting issues
2025-03-10 16:12:24 +01:00
Sebastiaan van Stijn a07391c65d
Merge pull request #5906 from thaJeztah/remove_client_warnings
fix duplicate warnings on docker run / docker create, and slight refactor
2025-03-10 16:03:38 +01:00
Sebastiaan van Stijn 650b45a42a
Merge pull request #5915 from thaJeztah/remove_StringSliceReplaceAt
cli/command: remove StringSliceReplaceAt utility
2025-03-10 13:37:31 +01:00
Sebastiaan van Stijn bc57a035c4
Merge pull request #5916 from thaJeztah/move_command_prettyprint
cli/command: move PrettyPrint utility to cli/command/formatter
2025-03-10 13:35:03 +01:00
Sebastiaan van Stijn a390a32da1
Merge pull request #5917 from thaJeztah/prunefilters_shallow_interface
cli/command: PruneFilters: require smaller interface
2025-03-10 13:33:00 +01:00
Sebastiaan van Stijn 70bf6cb7c5
Merge pull request #5863 from Benehiko/only-experimental-workflow
workflow/e2e: only run experimental daemon
2025-03-10 13:32:13 +01:00
Paweł Gronowski e9cf371b56
Merge pull request #5913 from thaJeztah/image_load_cleanup
image load: combine checks to a single switch
2025-03-10 11:54:30 +00:00
Alano Terblanche c26090bd3e
workflow/e2e: only run experimental daemon
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-03-10 12:26:20 +01:00
Sebastiaan van Stijn 7ec69def79
Merge pull request #5904 from thaJeztah/cleanup_buildtags
remove legacy build-tags
2025-03-10 11:41:58 +01:00
Sebastiaan van Stijn d2b751ce58
cli/command: PruneFilters: require smaller interface
This function only needs access to the CLI's configfile; use the
config.Prider interface to be more clear on what's expected.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-09 22:30:05 +01:00
Sebastiaan van Stijn a5ec6c2963
cli/command: remove StringSliceReplaceAt utility
It was only used internally in cmd/docker and has no known external
consumers. Move it to cmd/docker and un-export it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-09 22:22:29 +01:00
Sebastiaan van Stijn ce3090ccc4
cli/command: move PrettyPrint utility to cli/command/formatter
This utility was only used internally, and has no external consumers;
move it to the "formatter" package, which is also imported in all files
using this utility.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-09 22:20:12 +01:00
Sebastiaan van Stijn 802d8e801a
image load: combine checks to a single switch
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-09 14:43:57 +01:00
Sebastiaan van Stijn 6bd6b3e8ac
service/logs: move to cli/internal/logdetails
This package is only used by cli/command/service, and has no
external consumers.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 22:51:11 +01:00
Sebastiaan van Stijn 2c0f9f476d
cli/command/image: explicitly ignore some unhandled errs
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 22:47:56 +01:00
Sebastiaan van Stijn e73fb7d2f6
cli/command/image: rename var that shadowed type
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 22:43:21 +01:00
Sebastiaan van Stijn 1bd58b0936
service/logs: remove pkg/errors, and minor cleanups
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 22:23:18 +01:00
Sebastiaan van Stijn 44e5100232
move winresources into cmd/docker
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 22:20:09 +01:00
Sebastiaan van Stijn 79c9c7e3e4
cli/command/system: ignore unhandled errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 19:32:35 +01:00
Sebastiaan van Stijn 5f13d0f2b5
remove uses of cli.DefaultVersion()
It's hard-coded to the API defaultversion, so we can use
that const directly. Ultimately, this should be something
returned by the API client configured on the CLI, not the
CLI itself.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 19:32:31 +01:00
Sebastiaan van Stijn d0d91bb0cd
opts/swarmopts: remove redundant import aliases
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 18:39:12 +01:00
Sebastiaan van Stijn ad21055bac
opts: move swarm-specific options to a separate package
This prevents users of the CLI that don't implement swarm-related
features from depending on the swarm API types.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 18:39:07 +01:00
Sebastiaan van Stijn 4c882e0f6c
opts: use stdlib errors and touch-up some errors
- remove uses of github.com/pkg/errors
- slight improvement on handling parsing errors
- add some test-cases

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 18:15:51 +01:00
Sebastiaan van Stijn bc90bb6855
container create: combine client-side warning with daemon-side
Use a consistent approach for producing warnings, but add a TODO for moving
this warning to the daemon, which can make a better call if it will work
or not (depending on networking mode).

This warning was originally added in [moby@afa92a9], before integration with
libnetwork, and this warning may be incorrect in many scenarios.

While updating, also removing the custom regular expression used to
detect if the IP is a loopback address, and using go's netip package
instead.

[moby@afa92a9]: afa92a9af0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 16:15:50 +01:00
Sebastiaan van Stijn 58a35692d6
remove duplicate `--oom-kill-disable` warnings on docker run / docker create
This warning was originally added in [moby@3aa70c1], and moved to be printed
on both `run` and `create` in commit 7c514a31c9.

However, [moby@57f1305] (docker 19.03, API 1.40) moved such warnings to
the daemon side. The patch mentioned this issue:

> This patch will have one side-effect; docker cli's that also perform this check
> client-side will print the warning twice; this can be addressed by disabling
> the cli-side check for newer API versions, but will generate a bit of extra
> noise when using an older CLI.

The CLI does not take this into account currently, and still prints warnings
twice; even in cases where the option is not supported by the daemon, and
discarded:

On a host without OomKillDisable support:

    docker create --oom-kill-disable alpine
    WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.
    WARNING: Your kernel does not support OomKillDisable. OomKillDisable discarded.

On a host that supports it:

    docker create --oom-kill-disable alpine
    WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.
    WARNING: OOM killer is disabled for the container, but no memory limit is set, this can result in the system running out of resources.

This patch removes the client-side warning, leaving it to the daemon to
report if any warnings should produced (and the client to print them).

With this patch applied:

On a host without OomKillDisable support:

    docker create --oom-kill-disable alpine
    WARNING: Your kernel does not support OomKillDisable. OomKillDisable discarded.

On a host that supports it:

    docker create --oom-kill-disable alpine
    WARNING: OOM killer is disabled for the container, but no memory limit is set, this can result in the system running out of resources.

[moby@3aa70c1]: 3aa70c1948
[moby@57f1305]: 57f1305e74

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 15:39:21 +01:00
Sebastiaan van Stijn f6d49e9ca4
docs: remove legacy build-tags
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 12:47:19 +01:00
Sebastiaan van Stijn 46caf5697c
remove legacy build-tags
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-08 12:47:03 +01:00
Sebastiaan van Stijn 2eec74659e
Merge pull request #5901 from NinaLua/master
chore: make function comment match function name
2025-03-07 20:42:38 +01:00
Sebastiaan van Stijn 8fc0c74f9a
cli-plugins/manager: use stdlib errors, and minor cleanup
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-07 19:14:32 +01:00
Sebastiaan van Stijn e201b4e8a5
Merge pull request #5902 from thaJeztah/cli_plugin_metadata
move cli-plugins metadata types/consts to a separate package
2025-03-07 19:13:02 +01:00
Sebastiaan van Stijn 292713c887
move cli-plugins annotation consts to a separate package
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-07 12:46:11 +01:00
Sebastiaan van Stijn 4321293972
move cli-plugins metadata types/consts to a separate package
This prevents cli-plugins having to import the plugin-manager.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-07 12:38:06 +01:00
NinaLua aa66f07a3e chore: make function comment match function name
Signed-off-by: NinaLua <iturf@sina.cn>
2025-03-07 14:21:27 +08:00
Sebastiaan van Stijn ceef542046
Merge pull request #5894 from thaJeztah/more_internalize
move some trust-related code to trust package
2025-03-06 18:10:20 +01:00
Sebastiaan van Stijn f9b3c8ce10
Merge pull request #5875 from thaJeztah/bump_creds_helper_0.9.0
vendor: github.com/docker/docker-credential-helpers v0.9.2
2025-03-06 00:34:34 +01:00
Sebastiaan van Stijn b2a669fb56
vendor: github.com/docker/docker-credential-helpers v0.9.2
full diff: https://github.com/docker/docker-credential-helpers/compare/v0.8.2...v0.9.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 22:38:56 +01:00
Sebastiaan van Stijn e37d814ce9
cli/command/image: deprecate TagTrusted, move to cli/trust
This function was shared between "image" and "container" packages,
all of which needed the trust package, so move it there instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 21:36:53 +01:00
Sebastiaan van Stijn d80436021c
cli/command/image: deprecate PushTrustedReference, move to trust
This function was shared between "trust" "image" and "plugin" packages,
all of which needed the trust package, so move it there instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 18:29:12 +01:00
Sebastiaan van Stijn c6f456bc90
cli/command/image: deprecate and internalize TrustedPush
This function was only used by "docker trust sign"; inline the code
and deprecate the function.

This function has no known external consumers, so we should remove
it on the first possible ocassion (which could be a minor release).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 18:29:08 +01:00
Sebastiaan van Stijn e558b915c2
Merge pull request #5892 from thaJeztah/pluginmanager_smaller_interface
cli-plugins/manager: use shallower interface
2025-03-05 13:18:57 +01:00
Sebastiaan van Stijn a9e530999e
Merge pull request #5893 from thaJeztah/hooks_optim
small performance optimizations for running hooks
2025-03-05 12:59:04 +01:00
Sebastiaan van Stijn a89a15a85c
Merge pull request #5890 from vvoland/update-go
update to go1.23.7
2025-03-05 12:56:31 +01:00
Sebastiaan van Stijn 4be2ddedd3
cli/command: Cli: embed config.Provider interface
Makes sure we implement that interface, and don't diverge.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 12:05:56 +01:00
Sebastiaan van Stijn 8dcde50b6e
cli-plugins/manager: use shallower interface
The manager only requires the CLI's configuration; define a shallow interface
for this so that we don't have to import cli/command.

In addition to the CLI's configuration, `runHooks` also used the CLI's configured
StdErr output. We set the Cobra input and output streams to be the same as the
DockerCLI outputs in [newDockerCommand] and [newPluginCommand], so we can
get this from the Cobra command.

[newDockerCommand]: ea1f10b440/cmd/docker/docker.go (L148-L150)
[newPluginCommand]: ea1f10b440/cli-plugins/plugin/plugin.go (L166-L168)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 12:04:49 +01:00
Sebastiaan van Stijn 6d551e0a5a
cli/command: DockerCli.HooksEnabled check current before legacy
The DOCKER_CLI_HINTS env-var is replaced by DOCKER_CLI_HOOKS; check the
new env-var first, and only fall back to checking the legacy env-var
if it's not set.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 11:52:01 +01:00
Sebastiaan van Stijn a2d78071c1
cmd/docker: small performance optimizations for running hooks
Order conditions to check for lightweight ones first;

- checck if the command is not nil
- dockerCli.Out().IsTerminal() is a lightweight getter
- dockerCli.HooksEnabled() checks for env-vars, parses booleans, and
  reading the CLI config-file

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-05 11:51:58 +01:00
Paweł Gronowski df209212cf
update to go1.23.7
- https://github.com/golang/go/issues?q=milestone%3AGo1.23.7+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.23.6...go1.23.7

These minor releases include 1 security fixes following the security policy:

net/http, x/net/proxy, x/net/http/httpproxy: proxy bypass using IPv6 zone IDs

Matching of hosts against proxy patterns could improperly treat an IPv6
zone ID as a hostname component. For example, when the NO_PROXY
environment variable was set to "*.example.com", a request to
"[::1%25.example.com]:80` would incorrectly match and not be proxied.

Thanks to Juho Forsén of Mattermost for reporting this issue.

This is CVE-2025-22870 and Go issue https://go.dev/issue/71984.

View the release notes for more information:
https://go.dev/doc/devel/release#go1.23.7

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-03-04 22:59:28 +01:00
Sebastiaan van Stijn ea1f10b440
Merge pull request #5889 from thaJeztah/internalize_manifest
cli/command: deprecate Cli.ManifestStore, Cli.RegistryClient
2025-03-04 20:31:55 +01:00
Sebastiaan van Stijn 7bcbe0837b
Merge pull request #5888 from thaJeztah/command_no_go_connections
cli/command: remove direct import of docker/go-connections
2025-03-04 20:30:53 +01:00
Sebastiaan van Stijn 0b985e74f1
Merge pull request #5881 from thaJeztah/cleanup_otel
cli/command: un-export ResourceAttributesEnvvar, DockerCliAttributePrefix
2025-03-04 18:14:50 +01:00
Sebastiaan van Stijn 95ac11e714
cli/command: remove direct import of docker/go-connections
It was only used to check if the value was nil; pass a boolean instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 18:00:58 +01:00
Sebastiaan van Stijn 8ad07217dc
cli/command: deprecate Cli.RegistryClient
This method was a shallow wrapper around registryclient.NewRegistryClient but
due to its signature resulted in various dependencies becoming a dependency
of the "command" package. Consequence of this was that cli-plugins, which
need the cli/command package, would also get those dependencies. It is no
longer used in our code, which constructs the client in packages that need it,
so we can deprecate this method.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:48:43 +01:00
Sebastiaan van Stijn e32d5d56f5
cli/command: deprecate Cli.ManifestStore
This method is a shallow wrapper around manifeststore.NewStore, but
due to its signature resulted in various dependencies becoming a dependency
of the "command" package. Consequence of this was that cli-plugins, which
need the cli/command package, would also get those dependencies. It is no
longer used in our code, which constructs the client in packages that need it,
so we can deprecate this method.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:48:43 +01:00
Sebastiaan van Stijn 985b58e7e1
cli/command: internalize constructing RegistryClient
The CLI.RegistryClient method is a shallow wrapper around registryclient.NewRegistryClient
but due to its signature resulted in various dependencies becoming a dependency
of the "command" package. Consequence of this was that cli-plugins, which
need the cli/command package, would also get those dependencies.

This patch inlines the code where needed, skipping the wrapper

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:48:42 +01:00
Sebastiaan van Stijn 3b5dff2783
cli/command: internalize constructing ManifestStore
The CLI.ManifestStore method is a shallow wrapper around manifeststore.NewStore
and has no dependency on the CLI itself. However, due to its signature resulted
in various dependencies becoming a dependency of the "command" package.
Consequence of this was that cli-plugins, which need the cli/command package,
would also get those dependencies.

- This patch inlines the code to produce the store, skipping the wrapper.
- Define a local interface for some tests where a dummy store was used.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:48:42 +01:00
Sebastiaan van Stijn c775585e6c
Merge pull request #5885 from thaJeztah/internalize_notaryclient
cli/command: internalize and deprecate Cli.NotaryClient
2025-03-04 17:48:17 +01:00
Sebastiaan van Stijn 9bc16bbde0
cli/command: deprecate Cli.NotaryClient
This method is a shallow wrapper around trust.GetNotaryRepository, but
due to its signature resulted in the trust package, and notary dependencies
to become a dependency of the CLI. Consequence of this was that cli-plugins,
which need the cli/command package, would also get notary and its
dependencies as a dependency. It is no longer used in our code, which
constructs the client in packages that need it, so we can deprecate this
method.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:40:08 +01:00
Sebastiaan van Stijn 2793731977
cli/command: internalize constructing Notary client
The CLI.NotaryClient method is a shallow wrapper around trust.GetNotaryRepository
and only depends on the CLI itself to pass its StdErr/StrOut streams.

- This patch inlines the code to produce the client, skipping the wrapper.
- Define a local interface for some tests where a dummy notary client was used.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:40:06 +01:00
Albin Kerouanton 539f6de682
Merge pull request #5887 from thaJeztah/gha_bump_ubuntu
gha: validate-pr: update to ubuntu 24.04
2025-03-04 17:39:16 +01:00
Sebastiaan van Stijn cdc2cdc2a8
gha: validate-pr: update to ubuntu 24.04
Github is phasing out Ubuntu 20.04, and currently is doing
brownouts; https://github.com/actions/runner-images/issues/11101

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-04 17:00:14 +01:00
Sebastiaan van Stijn d962a90517
Merge pull request #5882 from thaJeztah/regclient_cleanup
cli/registry/client: remove unused types, and deprecate RepoNameForReference
2025-03-04 14:00:55 +01:00
Sebastiaan van Stijn 6f46cd2f4b
cli/registry/client: deprecate RepoNameForReference
This function was added in 02719bdbb5, and
used newDefaultRepositoryEndpoint to get repository info for the given
image-reference.

newDefaultRepositoryEndpoint uses registry.ParseRepositoryInfo under the
hood, but the only information used from the result was the Name field,
which is set using `reference.TrimNamed(name)`. The possible error returned
was based on the domain-name of the image, and only checked for the domain
to not start, or end with a hyphen ("-").

This patch removes the use of RepoNameForReference, deprecates it, and
inlines the code used by it.

There are no known consumers of this function, so we can consider removing
it in the first possible release after this (which can be a minor release).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 15:48:06 +01:00
Sebastiaan van Stijn 1a165fd535
cli/registry/client: un-export ErrHTTPProto
This type was added in 02719bdbb5, but was
never used outside of the package itself. This patch un-exports it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 15:32:58 +01:00
Sebastiaan van Stijn 293bbb44a0
cli/registry/client: remove unused PutManifestOptions
This type was added in 02719bdbb5, but was
never used;

    git rev-parse --verify HEAD
    02719bdbb5

    git grep 'PutManifestOptions'
    cli/registry/client/client.go:// PutManifestOptions is the data sent to push a manifest
    cli/registry/client/client.go:type PutManifestOptions struct {

This patch removes it, because it's not used.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 15:22:42 +01:00
Sebastiaan van Stijn 8bedb69f2c
cli-plugins/manager: move OTEL-related code to separate file
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 14:24:00 +01:00
Sebastiaan van Stijn 9dc175d6ef
cli/command: un-export ResourceAttributesEnvvar, DockerCliAttributePrefix
These utility functions were added in 8890a1c929,
and are all related to OTEL. The ResourceAttributesEnvvar const defines
the "OTEL_RESOURCE_ATTRIBUTES" environment-variable to use, which is part
of the [OpenTelemetry specification], so should be considered a well-known
env-var, and not up to us to define a const for. These code-changes were not
yet included in a release, so we don't have to deprecate.

This patch:

- Moves the utility functions to the telemetry files, so that all code related
  to OpenTelemetry is together.
- Un-exports the ResourceAttributesEnvvar to reduce our public API.
- Un-exports the DockerCliAttributePrefix to reduce depdency on cli/command
  in CLI-plugins, but adds a TODO to move telemetry-related code to a common
  (internal) package.
- Deprecates the cli-plugins/manager.ResourceAttributesEnvvar const. This
  const has no known consumers, so we could skip deprecation, but just in
  case some codebase uses this.

[OpenTelemetry specification]: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 14:21:45 +01:00
Sebastiaan van Stijn 43a2fcf5d7
Merge pull request #5880 from thaJeztah/registry_decouple_trust
cli/registry/client: remove dependency on trust / notary
2025-03-03 12:49:54 +01:00
Sebastiaan van Stijn e3da0cc584
cli/registry/client: remove dependency on trust / notary
The client was only using the Actions consts, but the trust package
also has a dependency on notary. Remove the import to prevent Notary
becoming a dependency for uses of the cli code.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 12:19:20 +01:00
Sebastiaan van Stijn 076ec3b56e
Merge pull request #5878 from thaJeztah/trust_cleans
Assorted cleanups to reduce trust / notary imports
2025-03-03 12:18:47 +01:00
Sebastiaan van Stijn 124716ba6b
Merge pull request #5879 from thaJeztah/google_uuid
cli/command: remove dependency on distribution/uuid
2025-03-03 12:18:19 +01:00
Sebastiaan van Stijn fda7da2303
cli/command: remove dependency on distribution/uuid
This uuid package was introduced in 89db01ef97,
but we want to reduce dependency on the old docker/distribution module.

Replace it with google/uuid, which is a commonly used module for this
and already a dependency.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-03 11:41:17 +01:00
Sebastiaan van Stijn 3f154adf70
Merge pull request #5877 from thaJeztah/remove_redundant_ParseRepositoryInfo
cli/command/manifest: remove redundant uses of ParseRepositoryInfo
2025-03-03 11:36:16 +01:00
Sebastiaan van Stijn c7072a885d
cli/command/image: rename vars that shadowed type
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:38 +01:00
Sebastiaan van Stijn 7a6270d190
cli/command/image: move AddTargetToAllSignableRoles to cli/trust
This utility was shared between the "image" and "trust" packages, and a
shallow wrapper around features in the cli/trust package. Move it there
instead and rename it to `trust.AddToAllSignableRoles`.

There are no known external consumers of this utility, so skipping a
deprecation.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:38 +01:00
Sebastiaan van Stijn d95385057f
cli/command/trust: use gotest.tools in tests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:37 +01:00
Sebastiaan van Stijn e6382db10e
cli/command/image: move trust unit-tests to trust package
These tests were not testing functionality that was implemented
in the image package. Move them to the trust package, where
they belong.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:37 +01:00
Sebastiaan van Stijn 55bc30a784
cli/command/image: use t.SetEnv in trust tests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:37 +01:00
Sebastiaan van Stijn 049f84c94d
cli/command/image: remove TestAddTargetToAllSignableRolesError
This test was only testing trust.GetSignableRoles to return an error
if it's offline, which was duplicating the [TestGetSignableRolesError]
test in the cli/trust package.

[TestGetSignableRolesError]: fe0a8d2791/cli/trust/trust_test.go (L49-L55)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:37 +01:00
Sebastiaan van Stijn 791bdf7b3c
cli/command/trust: add testPassRetriever helper
Add a basic helper to provide the equivalent of passphrase.ConstantRetriever
with a fixed passphrase for testing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:32 +01:00
Sebastiaan van Stijn 1d8f87a2fb
cli/command/trust: remove TestGetSignableRolesForTargetAndRemoveError
This test was only testing trust.GetSignableRoles to return an error
if it's offline, which was duplicating the [TestGetSignableRolesError]
test.

[TestGetSignableRolesError]: fe0a8d2791/cli/trust/trust_test.go (L49-L55)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:04 +01:00
Sebastiaan van Stijn d4217eb205
cli/command/trust: remove TestGetOrGenerateNotaryKeyAndInitRepo
This test was only testing trust.GetSignableRoles to return an error
if it's offline, which was duplicating the [TestGetSignableRolesError]
test.

[TestGetSignableRolesError]: fe0a8d2791/cli/trust/trust_test.go (L49-L55)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:04 +01:00
Sebastiaan van Stijn dd617b1464
cli/command/trust: remove unused passphrase-retriever from test
The test only validates that an error is produced because the notary
server is offline, and does not sent a passphrase.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:16:04 +01:00
Sebastiaan van Stijn eae4c38023
internal/test/notary: add testPassRetriever helper
Add a basic helper to provide the equivalent of passphrase.ConstantRetriever
with a fixed passphrase for testing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 14:15:57 +01:00
Sebastiaan van Stijn eb82fe87a5
cli/trust: make NotaryServer a const
This var used to be vendored from github.com/docker/docker/registry, but was
removed there, and made a local var in a1cbaa827b.

It is (and should never be) modified, so let's change it into a const.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-02 12:42:13 +01:00
Sebastiaan van Stijn 55a83aff23
cli/command/manifest: remove redundant uses of ParseRepositoryInfo
[ParseRepositoryInfo] parses an image reference and returns information
about the Repository and the registry. As part of this, it validates if
the registry's hostname is considered valid using [ValidateIndexName],
as well as normalizing the image reference to strip tags and digests
using [reference.TrimNamed].

ValidateIndexName only provides very limited value; the only validation
happening is to check for the hostname to not start, or end with a hyphen.

The cli/command/manifest package used ParseRepositoryInfo in various
locations where only the repository name was used (i.e., the result
of `reference.TrimNamed` on the given reference), and in one location
only used it to validate the registry name.

For buildPushRequest, the call was fully redundant, as [RepoNameForReference]
was used on the result, calling [newDefaultRepositoryEndpoint], which
uses ParseRepositoryInfo internally, so we were only repeating that work.

This patch removes uses of ParseRepositoryInfo in those places, and instead
calling [reference.TrimNamed] directly.

[ParseRepositoryInfo]: 41f781fab3/registry/config.go (L375-L381)
[ValidateIndexName]: 41f781fab3/registry/config.go (L288-L299)
[reference.TrimNamed]: 41f781fab3/registry/config.go (L369)
[RepoNameForReference]: fe0a8d2791/cli/registry/client/endpoint.go (L107-L110)
[newDefaultRepositoryEndpoint]: fe0a8d2791/cli/registry/client/endpoint.go (L33-L38)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-03-01 15:40:29 +01:00
Sebastiaan van Stijn fe0a8d2791
Merge pull request #5842 from jsternberg/otel-resource-attributes-merge
cli-plugins: merge OTEL_RESOURCE_ATTRIBUTES environment variable
2025-02-28 10:45:17 +01:00
Sebastiaan van Stijn b414752ef8
Merge pull request #5851 from thaJeztah/err_handle_explicit
explicitly handle errors when wrapping them
2025-02-26 16:23:35 +01:00
Sebastiaan van Stijn 7b78eabcab
Merge pull request #5872 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.0.1
2025-02-26 15:40:13 +01:00
Paweł Gronowski 9e997a57fa
vendor: github.com/docker/docker v28.0.1
full diff: https://github.com/docker/docker/compare/af898abe4466...v28.0.1

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-26 15:32:31 +01:00
Sebastiaan van Stijn 068a01ea94
Merge pull request #5870 from thaJeztah/carry_5855
Add detailed descriptions for --ulimit options in docker run documentation
2025-02-25 18:52:55 +01:00
MHM0098 d75f8d83d3
Add detailed descriptions for --ulimit options in docker run documentation
Signed-off-by: MHM0098 <mhm98035@gmail.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-25 16:15:21 +01:00
Sebastiaan van Stijn ffdfc5f94d
Merge pull request #5742 from mertssmnoglu/fix-dockerfile-exec-form
fix/dockerfiles: Update CMD instruction in 'Dockerfile.dev' to use exec form
2025-02-25 15:59:09 +01:00
Paweł Gronowski 6bd9908388
Merge pull request #5867 from thaJeztah/bump_go_jose
vendor: github.com/go-jose/go-jose/v4 v4.0.5
2025-02-25 13:03:21 +00:00
Sebastiaan van Stijn 75595836f2
vendor: github.com/go-jose/go-jose/v4 v4.0.5
- Don't allow unbounded amounts of splits.
  Fixes GHSA-c6gw-w398-hv78 / CVE-2025-27144
- Various other dependency updates, small fixes, and documentation
  updates in the full changelog

full diff: https://github.com/go-jose/go-jose/compare/v4.0.4...v4.0.5

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-25 11:55:06 +01:00
Rob Murray 41277f53d5
Merge pull request #5865 from robmry/doc_default_bridge
Update dockerd command line ref
2025-02-24 18:14:39 +00:00
Rob Murray 4e7497e9cf Update dockerd command line ref, default bridge opts
Signed-off-by: Rob Murray <rob.murray@docker.com>
2025-02-24 18:07:06 +00:00
Rob Murray be669099cb Update dockerd command line ref, changes in 28.0
Signed-off-by: Rob Murray <rob.murray@docker.com>
2025-02-24 18:07:06 +00:00
Paweł Gronowski 111468ccd6
Merge pull request #5864 from thaJeztah/gha_bump_docker
gha: add docker 28 to test matrix
2025-02-24 16:39:27 +00:00
Sebastiaan van Stijn 427c1361c5
gha: add docker 28 to test matrix
- set default to 28
- remove minor version from matrix; docker:dind images also provide a
  "docker:28-dind" which point to the latest minor version.
- remove TODO for 19.03, which is really out of scope now.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-24 15:14:53 +01:00
Sebastiaan van Stijn 656523e20d
Merge pull request #5859 from thaJeztah/fix_docs
docs: minor fixes and touch-ups for anchor links
2025-02-24 12:05:34 +01:00
Sebastiaan van Stijn aad2ae50e8
docs: network ls add heading and anchor for "--no-trunc"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-21 23:51:04 +01:00
Sebastiaan van Stijn 8a1b096e76
docs: fix missing anchors in swarm reference pages
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-21 23:46:07 +01:00
Sebastiaan van Stijn c99d3312eb
docs: fix broken anchor-link in "container restart" reference
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-21 23:45:32 +01:00
Paweł Gronowski 77a8a8c6ca
Merge pull request #5854 from Benehiko/fix-exec-msg
cmd/docker: do not print error status on exec/run
2025-02-21 12:20:31 +00:00
Alano Terblanche 0cff340983
cmd/docker: do not print error status on exec/run
Co-authored-by: Fabio Pugliese Ornellas <fabio.ornellas@gmail.com>
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-02-21 12:55:57 +01:00
Bjorn Neergaard eb48cad302
Merge pull request #5848 from thaJeztah/improve_swarm_completion
completion: fix / add completion for service names and node-names
2025-02-20 12:24:31 -07:00
Sebastiaan van Stijn 2493a96027
Merge pull request #5850 from thaJeztah/fix_context_err
cli/command/context: fix error-handling of skip-tls-verify
2025-02-20 18:37:04 +01:00
Sebastiaan van Stijn 8f55738579
completion: add completion for docker service flags
Not all flags have completions yet, and for those that don't have completion,
we disable completion to prevent it completing with filenames.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-20 18:33:17 +01:00
Sebastiaan van Stijn 768d10767f
completion: add completion for docker node flags
With this patch:

    docker node update --role
    manager  worker

    docker node update --availability
    active  drain   pause

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-20 18:33:17 +01:00
Sebastiaan van Stijn d5e6e2ec6e
completion: add completion for node names
Change completion for nodes to use names by default, and bring back
support for the `DOCKER_COMPLETION_SHOW_NODE_IDS` env-var
f9ced58158/contrib/completion/bash/docker (L38)

With this patch:

    docker node ps <tab>
    docker-desktop            self

    export DOCKER_COMPLETION_SHOW_NODE_IDS=yes
    docker node ps <TAB>
    docker-desktop             qyeriqk20al6hy4y869d08ff5  self

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-20 18:33:09 +01:00
Sebastiaan van Stijn da4b6275ba
explicitly handle errors when wrapping them
The errors.Wrap and errors.Wrapf functions gracefully handle nil-errors.
This allows them to be used unconditionally regardless if an error
was produced.

While this can be convenient, it can also be err-prone, as replacing
these with stdlib errors means they unconditionally produce an error.

This patch replaces code uses of errors.Wrap to be gated by a check
for nil-errors to future-proof our code.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-20 18:10:36 +01:00
Sebastiaan van Stijn 7e71782ba6
cli/command/context: fix error-handling of skip-tls-verify
Before 2b9a4d5f4c, this function
would use "errors.Wrap" which returns nil if the original error
was nil. fmt.Errorf does not do this, so without a nil check,
it would unconditionally return an error;

    docker context create arm64 --docker host=ssh://172.17.101.26,skip-tls-verify=False

    unable to create docker endpoint config: name: %!w(<nil>)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-20 17:49:58 +01:00
Sebastiaan van Stijn 762d59359e
completion: use service names, and support DOCKER_COMPLETION_SHOW_SERVICE_IDS
Change completion for services to use names by default, and bring back
support for the `DOCKER_COMPLETION_SHOW_SERVICE_IDS` env-var
f9ced58158/contrib/completion/bash/docker (L41-L43)

Before this patch:

    docker service ps
    c9vrp2pwni9gx5ghat20rjpcy  hmthf0tqws9xpmd87ok7diqly

With this patch:

    docker service ps<TAB>
    databaseservice  webservice

    export DOCKER_COMPLETION_SHOW_SERVICE_IDS=yes
    docker service ps<TAB>
    c9vrp2pwni9gx5ghat20rjpcy  databaseservice            hmthf0tqws9xpmd87ok7diqly  webservice

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-20 13:51:38 +01:00
Paweł Gronowski f9ced58158
Merge pull request #5845 from vvoland/vendor-docker
vendor: github.com/docker/docker v28.0.0-dev (af898abe4466)
2025-02-19 22:05:47 +00:00
Paweł Gronowski 33f327a98f
vendor: github.com/docker/docker v28.0.0-dev (af898abe4466)
full diff: https://github.com/docker/docker/compare/v28.0.0-rc.3...af898abe4466

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-19 22:55:43 +01:00
Jonathan A. Sternberg 8890a1c929
cli-plugins: remove docker.cli specific otel attributes after usage
Remove the `docker.cli` prefixed attributes from
`OTEL_RESOURCE_ATTRIBUTES` after the telemetry provider has been created
within a plugin. This prevents accidentally sending the attributes to
something downstream for the user.

This also fixes an issue with compose where the self-injected `OTEL_RESOURCE_ATTRIBUTES`
would override an existing attribute in the environment file because the
"user environment" overrode the environment file, but the "user
environment" was created by the `docker` tool rather than by the user's
environment.

When `OTEL_RESOURCE_ATTRIBUTES` is empty after pruning, the environment
variable is unset.

Signed-off-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
2025-02-19 10:19:00 -06:00
Sebastiaan van Stijn 9e60cfe42e
Merge pull request #5843 from thaJeztah/bump_engine_28.0_rc3
vendor: github.com/docker/docker v28.0.0-rc.3
2025-02-19 17:08:38 +01:00
Sebastiaan van Stijn 96eb1e97da
Merge pull request #5841 from sarahsanders-docker/reference-styling-issue
reference docs: fix missing link from heading
2025-02-19 17:08:08 +01:00
Sarah Sanders f977b923cd
Fix missing link from Configure node healthcheck heading
Update name to dispatcher-heartbeat

Signed-off-by: Sarah Sanders <sarah.sanders@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-19 16:56:28 +01:00
Sebastiaan van Stijn f53cee5dd1
vendor: github.com/docker/docker v28.0.0-rc.3
no diff; same commit, but tagged:

https://github.com/docker/docker/compare/00ab386b5a2e...v28.0.0-rc.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-19 13:48:22 +01:00
Paweł Gronowski 1dcfd230bf
Merge pull request #5840 from thaJeztah/bump_engine_28.0_rc3
vendor: github.com/docker/docker 62bc5979908f (master, v28.0.0-rc.3)
2025-02-18 22:17:28 +00:00
Sebastiaan van Stijn fe349e6a6c vendor: github.com/docker/docker 00ab386b5a2e (master, v28.0.0-rc.3)
no code changes, only updated swagger (docs)

full diff: https://github.com/docker/docker/compare/v28.0.0-rc.2...00ab386b5a2e

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-18 23:04:48 +01:00
Jonathan A. Sternberg cfe0605616
cli-plugins: merge OTEL_RESOURCE_ATTRIBUTES environment variable
Merge `OTEL_RESOURCE_ATTRIBUTES` when there is one already in the
environment. This allows user-specified resource attributes to be passed
on to CLI plugins while still allowing the extra attributes added for
telemetry information.

This was the original intended use-case but it seems to have never made
it in. The reason `OTEL_RESOURCE_ATTRIBUTES` was used is because we
could combine it with user-centric ones.

Signed-off-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
2025-02-18 12:06:46 -06:00
Sebastiaan van Stijn a8f888677b
Merge pull request #5838 from thaJeztah/bump_engine
vendor: github.com/docker/docker v28.0.0-rc.2
2025-02-18 13:55:15 +01:00
Sebastiaan van Stijn 136901961d
vendor: github.com/docker/docker v28.0.0-rc.2
no diff; same commit, but tagged;

https://github.com/docker/docker/compare/57d4d23825f4...v28.0.0-rc.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-18 13:40:15 +01:00
Sebastiaan van Stijn bfd49b1ec3
Merge pull request #5836 from thaJeztah/nakedret
golangci-lint: fix invalid nakedret config, disallow for any func length
2025-02-18 13:15:28 +01:00
Sebastiaan van Stijn 5e32ccefac
Merge pull request #5835 from thaJeztah/bump_golangci_lint
Dockerfile: update golangci-lint to v1.64.5, replace deprecated `tenv` linter in favor of `usetesting`
2025-02-18 13:15:06 +01:00
Sebastiaan van Stijn e3abf7f5d1
Merge pull request #5834 from thaJeztah/more_linters
golangci-lint: enable revive line-length-limit, unused-receiver linters
2025-02-18 13:14:22 +01:00
Sebastiaan van Stijn a8affefeea
golangci-lint: replace deprecated `tenv` linter in favor of `usetesting`
WARN The linter 'tenv' is deprecated (since v1.64.0) due to: Duplicate feature another linter. Replaced by usetesting.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-18 12:25:13 +01:00
Sebastiaan van Stijn 1c8243cc95
golangci-lint: fix invalid nakedret config, disallow for any func length
The regex was added before we migrateed from gometalinter in
dbd96badb6, and got migrated to golangci-lint
in b7e06f2845. The format used for the config
was invalid, and migrating it to the right format didn't make a difference,
so we can remove it.

As naked returns are generally not desirable, also setting the minimum func
length to 0 (i.e., don't allow any naked returns), instead of the default

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-18 09:36:12 +01:00
Sebastiaan van Stijn a5020ea165
cli/command/container: don't use naked returns (nakedret)
cli/command/container/cp.go:206:3: naked return in func `resolveLocalPath` with 5 lines of code (nakedret)
            return
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-18 09:36:11 +01:00
Sebastiaan van Stijn e569b9f74a
cli/internal/oauth: don't use naked returns (nakedret)
cli/internal/oauth/jwt.go:62:3: naked return in func `GetClaims` with 9 lines of code (nakedret)
            return
            ^
    cli/internal/oauth/jwt.go:67:2: naked return in func `GetClaims` with 9 lines of code (nakedret)
        return
        ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-18 09:36:11 +01:00
Sebastiaan van Stijn 3e9fa43ef8
cli/command/trust: fix "usetesting" linting errors
Also fix some unhandled errors

    cli/debug/debug_test.go:12:3: os.Setenv() could be replaced by t.Setenv() in TestEnable (usetesting)
            os.Setenv("DEBUG", "")
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 23:00:13 +01:00
Sebastiaan van Stijn aca0bd7757
cli/command/trust: fix "usetesting" linting errors
cli/command/trust/signer_add_test.go:71:18: os.CreateTemp("", ...) could be replaced by os.CreateTemp(t.TempDir(), ...) in TestSignerAddCommandNoTargetsKey (usetesting)
        tmpfile, err := os.CreateTemp("", "pemfile")
                        ^
    cli/command/trust/signer_add_test.go:133:18: os.CreateTemp("", ...) could be replaced by os.CreateTemp(t.TempDir(), ...) in TestIngestPublicKeys (usetesting)
        tmpfile, err := os.CreateTemp("", "pemfile")
                        ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 22:59:41 +01:00
Sebastiaan van Stijn b2f3c12497
Dockerfile: update golangci-lint to v1.64.5
adds go1.24 support

full diff: https://github.com/golangci/golangci-lint/compare/v1.63.4...v1.64.5
changelog: https://golangci-lint.run/product/changelog/#v1645

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 22:51:49 +01:00
Sebastiaan van Stijn 2b169c1ab5
golangci-lint: enable revive "line-length-limit" linter
also disable "lll" linter as it did the same.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:58 +01:00
Sebastiaan van Stijn a67c656579
golangci-lint: enable revive "unused-receiver" rule
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:58 +01:00
Sebastiaan van Stijn 71c40dfa71
golangci-lint: sort revive rules
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:57 +01:00
Sebastiaan van Stijn a35b899dfe
cmd/docker: fix "unused-receiver" linting
cmd/docker/docker.go:35:7: unused-receiver: method receiver 'e' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (e errCtxSignalTerminated) Error() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:57 +01:00
Sebastiaan van Stijn 1a4491f8c6
cli/command/stack: fix "unused-receiver" linting
cli/command/stack/swarm/client_test.go:47:7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *fakeClient) ServerVersion(context.Context) (types.Version, error) {
          ^
    cli/command/stack/swarm/deploy_composefile_test.go:17:7: unused-receiver: method receiver 'n' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (n notFound) NotFound() {}
          ^
    cli/command/stack/client_test.go:47:7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *fakeClient) ServerVersion(context.Context) (types.Version, error) {
          ^
    cli/command/stack/client_test.go:183:7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *fakeClient) ServiceInspectWithRaw(_ context.Context, serviceID string, _ types.ServiceInspectOptions) (swarm.Service, []byte, error) {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:57 +01:00
Sebastiaan van Stijn 994e1b7cad
cli/command/service: fix "unused-receiver" linting
cli/command/service/update_test.go:511:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s secretAPIClientMock) SecretCreate(context.Context, swarm.SecretSpec) (types.SecretCreateResponse, error) {
          ^
    cli/command/service/update_test.go:515:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s secretAPIClientMock) SecretRemove(context.Context, string) error {
          ^
    cli/command/service/update_test.go:519:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s secretAPIClientMock) SecretInspectWithRaw(context.Context, string) (swarm.Secret, []byte, error) {
          ^
    cli/command/service/generic_resource_opts.go:46: line-length-limit: line is 206 characters, out of limit 200 (revive)
                return nil, fmt.Errorf("invalid generic-resource request `%s=%s`, Named Generic Resources is not supported for service create or update", res.NamedResourceSpec.Kind, res.NamedResourceSpec.Value)
    cli/command/service/create_test.go:24:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeConfigAPIClientList) ConfigCreate(_ context.Context, _ swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
          ^
    cli/command/service/logs.go:320:7: unused-receiver: method receiver 'lw' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (lw *logWriter) parseContext(details map[string]string) (logContext, error) {
          ^
    cli/command/service/opts.go:45:7: unused-receiver: method receiver 'i' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (i *Uint64Opt) Type() string {
          ^
    cli/command/service/update_test.go:523:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s secretAPIClientMock) SecretUpdate(context.Context, string, swarm.Version, swarm.SecretSpec) error {
          ^
    cli/command/service/create_test.go:28:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeConfigAPIClientList) ConfigRemove(_ context.Context, _ string) error {
          ^
    cli/command/service/opts.go:70:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f *floatValue) Type() string {
          ^
    cli/command/service/opts.go:117:7: unused-receiver: method receiver 'o' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (o *placementPrefOpts) Type() string {
          ^
    cli/command/service/create_test.go:32:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeConfigAPIClientList) ConfigInspectWithRaw(_ context.Context, _ string) (swarm.Config, []byte, error) {
          ^
    cli/command/service/create_test.go:36:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeConfigAPIClientList) ConfigUpdate(_ context.Context, _ string, _ swarm.Version, _ swarm.ConfigSpec) error {
          ^
    cli/command/service/opts.go:135:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s *ShlexOpt) Type() string {
          ^
    cli/command/service/opts.go:366:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *credentialSpecOpt) Type() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:57 +01:00
Sebastiaan van Stijn 5ef673bb14
cli/command/system: fix "unused-receiver" linting
cli/command/system/dial_stdio.go:113:7: unused-receiver: method receiver 'x' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (x *nopCloseReader) CloseRead() error {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:57 +01:00
Sebastiaan van Stijn e71380eb5b
cli/command/container: fix "unused-receiver" linting
cli/command/container/client_test.go:78:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f *fakeClient) ContainerExecStart(context.Context, string, container.ExecStartOptions) error {
          ^
    cli/command/container/create_test.go:383:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeNotFound) NotFound()     {}
          ^
    cli/command/container/create_test.go:384:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeNotFound) Error() string { return "error fake not found" }
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:56 +01:00
Sebastiaan van Stijn 4827fdef91
cli/command/trust: fix "unused-receiver" linting
cli/command/trust/inspect_pretty_test.go:31:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *fakeClient) Info(context.Context) (system.Info, error) {
          ^
    cli/command/trust/inspect_pretty_test.go:35:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *fakeClient) ImageInspect(context.Context, string, ...client.ImageInspectOption) (image.InspectResponse, error) {
          ^
    cli/command/trust/inspect_pretty_test.go:39:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *fakeClient) ImagePush(context.Context, string, image.PushOptions) (io.ReadCloser, error) {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:56 +01:00
Sebastiaan van Stijn 3e44cc4d00
cli/command/image: fix "unused-receiver", "line-length-limit" linting
cli/command/image/remove_test.go:24:7: unused-receiver: method receiver 'n' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (n notFound) NotFound() {}
          ^
    cli/command/image/formatter_history_test.go:110: line-length-limit: line is 558 characters, out of limit 200 (revive)
        withTabs := `/bin/sh -c apt-key adv --keyserver hkp://pgp.mit.edu:80	--recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62	&& echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list  && apt-get update  && apt-get install --no-install-recommends --no-install-suggests -y       ca-certificates       nginx=${NGINX_VERSION}       nginx-module-xslt       nginx-module-geoip       nginx-module-image-filter       nginx-module-perl       nginx-module-njs       gettext-base  && rm -rf /var/lib/apt/lists/*` //nolint:lll
    cli/command/image/formatter_history_test.go:111: line-length-limit: line is 552 characters, out of limit 200 (revive)
        expected := `/bin/sh -c apt-key adv --keyserver hkp://pgp.mit.edu:80 --recv-keys 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 && echo "deb http://nginx.org/packages/mainline/debian/ jessie nginx" >> /etc/apt/sources.list  && apt-get update  && apt-get install --no-install-recommends --no-install-suggests -y       ca-certificates       nginx=${NGINX_VERSION}       nginx-module-xslt       nginx-module-geoip       nginx-module-image-filter       nginx-module-perl       nginx-module-njs       gettext-base  && rm -rf /var/lib/apt/lists/*` //nolint:lll

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:56 +01:00
Sebastiaan van Stijn e2f28fac47
cli/command/registry: fix "unused-receiver" linting
cli/command/registry/login_test.go:36:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *fakeClient) Info(context.Context) (system.Info, error) {
          ^
    cli/command/registry/login_test.go:40:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *fakeClient) RegistryLogin(_ context.Context, auth registrytypes.AuthConfig) (registrytypes.AuthenticateOKBody, error) {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:56 +01:00
Sebastiaan van Stijn a54d356a7b
cli/command/swarm: fix "unused-receiver" linting
cli/command/swarm/opts.go:71:7: unused-receiver: method receiver 'a' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (a *NodeAddrOption) Type() string {
          ^
    cli/command/swarm/opts.go:107:7: unused-receiver: method receiver 'm' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (m *ExternalCAOption) Type() string {
          ^
    cli/command/swarm/opts.go:132:7: unused-receiver: method receiver 'p' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (p *PEMFile) Type() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:56 +01:00
Sebastiaan van Stijn 25e6b2da04
cli/command/formatter: fix "unused-receiver" linting
cli/command/formatter/custom.go:35:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c SubHeaderContext) Label(name string) string {
          ^
    cli/command/formatter/container_test.go:334: line-length-limit: line is 204 characters, out of limit 200 (revive)
                context:  Context{Format: NewContainerFormat(`table {{truncate .ID 5}}\t{{json .Image}} {{.RunningFor}}/{{title .Status}}/{{pad .Ports 2 2}}.{{upper .Names}} {{lower .Status}}`, false, true)},
    cli/command/formatter/container_test.go:831: line-length-limit: line is 247 characters, out of limit 200 (revive)
                expected: "80/tcp, 80/udp, 1024/tcp, 1024/udp, 12345/sctp, 1.1.1.1:1024->80/tcp, 1.1.1.1:1024->80/udp, 2.1.1.1:1024->80/tcp, 2.1.1.1:1024->80/udp, 1.1.1.1:80->1024/tcp, 1.1.1.1:80->1024/udp, 2.1.1.1:80->1024/tcp, 2.1.1.1:80->1024/udp",
    cli/command/formatter/disk_usage.go:273:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *diskUsageImagesContext) Type() string {
          ^
    cli/command/formatter/formatter_test.go:31:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f fakeSubContext) FullHeader() any {
          ^
    cli/command/formatter/reflect_test.go:13:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *dummy) Func1() string {
          ^
    cli/command/formatter/disk_usage.go:324:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *diskUsageContainersContext) Type() string {
          ^
    cli/command/formatter/disk_usage.go:332:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *diskUsageContainersContext) isActive(ctr container.Summary) bool {
          ^
    cli/command/formatter/reflect_test.go:17:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *dummy) func2() string { //nolint:unused
          ^
    cli/command/formatter/reflect_test.go:21:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *dummy) Func3() (string, int) {
          ^
    cli/command/formatter/disk_usage.go:385:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *diskUsageVolumesContext) Type() string {
          ^
    cli/command/formatter/disk_usage.go:446:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *diskUsageBuilderContext) Type() string {
          ^
    cli/command/formatter/reflect_test.go:25:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *dummy) Func4() int {
          ^
    cli/command/formatter/reflect_test.go:31:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *dummy) Func5() dummyType {
          ^
    cli/command/formatter/reflect_test.go:35:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *dummy) FullHeader() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:56 +01:00
Sebastiaan van Stijn 450768c311
cli-plugins/manager: fix "unused-receiver" linting
cli-plugins/manager/manager.go:35:7: unused-receiver: method receiver 'e' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (e errPluginNotFound) NotFound() {}
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:55 +01:00
Sebastiaan van Stijn e5f3cc14c1
internal/test: fix "unused-receiver" linting
internal/test/cli.go:211:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *FakeCli) BuildKitEnabled() (bool, error) {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:55 +01:00
Sebastiaan van Stijn 1b3718f459
cli/command: fix "unused-receiver" linting
cli/command/cli.go💯7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *DockerCli) DefaultVersion() string {
          ^
    cli/command/cli.go:234:7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *DockerCli) ManifestStore() manifeststore.Store {
          ^
    cli/command/telemetry.go:57:7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *DockerCli) TracerProvider() trace.TracerProvider {
          ^
    cli/command/telemetry.go:61:7: unused-receiver: method receiver 'cli' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (cli *DockerCli) MeterProvider() metric.MeterProvider {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:55 +01:00
Sebastiaan van Stijn d27f6a61a2
cli/registry: fix "unused-receiver" linting
cli/registry/client/fetcher.go:307:7: unused-receiver: method receiver 'n' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (n *notFoundError) NotFound() {}
          ^
    cli/registry/client/endpoint.go:126:7: unused-receiver: method receiver 'th' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (th *existingTokenHandler) Scheme() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:55 +01:00
Sebastiaan van Stijn 72b32c69cc
internal/test/notary: fix "unused-receiver" linting
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:55 +01:00
Sebastiaan van Stijn ba3f4fb41c
cli/internal/oauth/manager: fix "unused-receiver" linting
cli/internal/oauth/manager/manager_test.go:349:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f *fakeStore) Save() error {
          ^
    cli/internal/oauth/manager/manager_test.go:357:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f *fakeStore) GetFilename() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:54 +01:00
Sebastiaan van Stijn f0f19c6d4f
cli/trust: fix "unused-receiver" linting
cli/trust/trust.go:92:7: unused-receiver: method receiver 'scs' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (scs simpleCredentialStore) SetRefreshToken(*url.URL, string, string) {}
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:54 +01:00
Sebastiaan van Stijn c8bd0a7e51
cli/manifest: fix "unused-receiver" linting
cli/manifest/store/store.go:47:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s *fsStore) getFromFilename(ref reference.Reference, filename string) (types.ImageManifest, error) {
          ^
    cli/manifest/store/store.go:168:7: unused-receiver: method receiver 'n' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (n *notFoundError) NotFound() {}
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:54 +01:00
Sebastiaan van Stijn 20b4ab366e
cli/compose: fix "unused-receiver" linting
cli/compose/schema/schema.go:25:7: unused-receiver: method receiver 'checker' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (checker portsFormatChecker) IsFormat(input any) bool {
          ^
    cli/compose/schema/schema.go:41:7: unused-receiver: method receiver 'checker' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (checker durationFormatChecker) IsFormat(input any) bool {
          ^
    cli/compose/loader/loader.go:272:7: unused-receiver: method receiver 'e' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (e *ForbiddenPropertiesError) Error() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:54 +01:00
Sebastiaan van Stijn 1e7add9f4b
cli/internal/oauth/api: fix "unused-receiver" linting
cli/internal/oauth/api/api.go:227:7: unused-receiver: method receiver 'a' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (a API) GetAutoPAT(ctx context.Context, audience string, res TokenResponse) (string, error) {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:54 +01:00
Sebastiaan van Stijn 9b62e57402
cli/config/configfile: fix "unused-receiver" linting
cli/config/configfile/file_test.go:189:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *mockNativeStore) Store(_ types.AuthConfig) error {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:54 +01:00
Sebastiaan van Stijn f79193c22c
opts: fix "unused-receiver", line-length-limit linting
opts/port.go:124:7: unused-receiver: method receiver 'p' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (p *PortOpt) Type() string {
          ^
    opts/mount.go:218:7: unused-receiver: method receiver 'm' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (m *MountOpt) Type() string {
          ^
    opts/quotedstring.go:16:7: unused-receiver: method receiver 's' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (s *QuotedString) Type() string {
          ^
    opts/secret.go:82:7: unused-receiver: method receiver 'o' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (o *SecretOpt) Type() string {
          ^
    opts/opts_test.go:235: line-length-limit: line is 283 characters, out of limit 200 (revive)
            `foo.bar.baz.this.should.fail.on.long.name.because.it.is.longer.thanisshouldbethis.should.fail.on.long.name.because.it.is.longer.thanisshouldbethis.should.fail.on.long.name.because.it.is.longer.thanisshouldbethis.should.fail.on.long.name.because.it.is.longer.thanisshouldbe`,
    opts/ulimit.go:61:7: unused-receiver: method receiver 'o' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (o *UlimitOpt) Type() string {
          ^
    opts/weightdevice.go:82:7: unused-receiver: method receiver 'opt' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (opt *WeightdeviceOpt) Type() string {
          ^
    opts/throttledevice.go:103:7: unused-receiver: method receiver 'opt' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (opt *ThrottledeviceOpt) Type() string {
          ^
    opts/duration.go:49:7: unused-receiver: method receiver 'd' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (d *DurationOpt) Type() string {
          ^
    opts/network.go:109:7: unused-receiver: method receiver 'n' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (n *NetworkOpt) Type() string {
          ^
    opts/network.go:119:7: unused-receiver: method receiver 'n' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (n *NetworkOpt) String() string {
          ^
    opts/opts.go:113:7: unused-receiver: method receiver 'opts' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (opts *ListOpts) Type() string {
          ^
    opts/pull_behavior.go:13:7: unused-receiver: method receiver 'p' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (p *PullOpt) Type() string {
          ^
    opts/config.go:83:7: unused-receiver: method receiver 'o' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (o *ConfigOpt) Type() string {
          ^
    opts/gpus.go:95:7: unused-receiver: method receiver 'o' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (o *GpuOpts) Type() string {
          ^
    opts/pull_behavior.go:23:7: unused-receiver: method receiver 'p' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (p *PullOpt) IsBoolFlag() bool {
          ^
    opts/opts.go:183:7: unused-receiver: method receiver 'opts' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (opts *MapOpts) Type() string {
          ^
    opts/opts.go:361:7: unused-receiver: method receiver 'o' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (o *FilterOpt) Type() string {
          ^
    opts/opts.go:389:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *NanoCPUs) Type() string {
          ^
    opts/opts.go:466:7: unused-receiver: method receiver 'm' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (m *MemBytes) Type() string {
          ^
    opts/opts.go:501:7: unused-receiver: method receiver 'm' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (m *MemSwapBytes) Type() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:53 +01:00
Sebastiaan van Stijn d0c3380ce4
cli/connhelper/commandconn: fix "unused-receiver" linting
cli/connhelper/commandconn/commandconn.go:256:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *commandConn) SetDeadline(t time.Time) error {
          ^
    cli/connhelper/commandconn/commandconn.go:261:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *commandConn) SetReadDeadline(t time.Time) error {
          ^
    cli/connhelper/commandconn/commandconn.go:266:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *commandConn) SetWriteDeadline(t time.Time) error {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:53 +01:00
Sebastiaan van Stijn fdc665820c
cli/config/credentials: fix "unused-receiver" linting
cli/config/credentials/file_store_test.go:29:7: unused-receiver: method receiver 'f' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (f *fakeStore) GetFilename() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:53 +01:00
Sebastiaan van Stijn 88b2e78e02
internal/tui: fix "unused-receiver" linting
internal/tui/colors.go:27:7: unused-receiver: method receiver 'a' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (a noColor) Apply(s string) string {
          ^
    internal/tui/colors.go:31:7: unused-receiver: method receiver 'a' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (a noColor) String() string {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:53 +01:00
Sebastiaan van Stijn 20c15cee99
cli/compose/loader: shorten skip-comment to please the linters
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:53 +01:00
Sebastiaan van Stijn cac88ca34c
cli/command: wrap some long lines (revive)
cli/command/cli_options.go:180: line-length-limit: line is 205 characters, out of limit 200 (revive)
      			return errdefs.InvalidParameter(errors.Errorf("failed to parse custom headers from %s environment variable: value must be formatted as comma-separated key=value pairs", envOverrideHTTPHeaders))
      cli/command/cli_options.go:194: line-length-limit: line is 208 characters, out of limit 200 (revive)
      				return errdefs.InvalidParameter(errors.Errorf(`failed to set custom headers from %s environment variable: value contains a key=value pair with an empty key: '%s'`, envOverrideHTTPHeaders, kv))

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:52 +01:00
Sebastiaan van Stijn eef4127de9
cli/internal/oauth/manager: ignore line-length-limit
cli/internal/oauth/manager/manager_test.go:18: line-length-limit: line is 857 characters, out of limit 200 (revive)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:52 +01:00
Sebastiaan van Stijn d8e76bc33f
cli: define const for magic value
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:52 +01:00
Sebastiaan van Stijn 9fda9134a9
cli/command/service/progress: define const for magic value
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:52 +01:00
Sebastiaan van Stijn 3825d37923
cli/command: define some consts for repeated values
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 15:24:44 +01:00
Sebastiaan van Stijn 2f65cf7d1a
cli/command: fix some unused-receiver linting
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 14:53:51 +01:00
Sebastiaan van Stijn a368e3eb58
cmd/docker: fix unused-receiver (revive)
cmd/docker/builder_test.go:130:7: unused-receiver: method receiver 'c' is not referenced in method's body, consider removing or renaming it as _ (revive)
    func (c *fakeClient) Ping(_ context.Context) (types.Ping, error) {
          ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 13:15:50 +01:00
Sebastiaan van Stijn 88a019a9bb
Merge pull request #5833 from vvoland/subpath-swarm-fix
cli/compose: Handle Volume Subpath
2025-02-17 12:54:24 +01:00
Sebastiaan van Stijn b73653ef41
Merge pull request #5832 from vvoland/swarm-fix-image-subpath
cli/compose: Fix Image Subpath
2025-02-17 12:53:34 +01:00
Paweł Gronowski add32e4b51
cli/compose: Handle Volume Subpath
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-17 12:39:23 +01:00
Paweł Gronowski 4cc2dce807
cli/compose: Fix Image Subpath
handleImageToMount was an exact copy of handleBindToMount instead of
populating the ImageOptions.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-17 12:37:24 +01:00
Sebastiaan van Stijn c542ad7443
Merge pull request #5830 from lalyos/fix-entrypoint-option-test
Fix entrypoint parsing logic
2025-02-17 12:18:51 +01:00
Lajos Papp e868f0f580 cli/command/container/opts_test: Fix entrypoint parsing logic
Right now the test passes even if you change the expected value.
It passes if the array has 1 element.

Signed-off-by: Lajos Papp <lalyos@yahoo.com>
2025-02-17 11:10:50 +00:00
Sebastiaan van Stijn ca295779cf
Merge pull request #5831 from thaJeztah/bump_engine
vendor: github.com/docker/docker 57d4d23825f4 (master, v28.0.0-rc.2)
2025-02-17 12:04:40 +01:00
Sebastiaan van Stijn c2ba77de49
vendor: github.com/docker/docker 57d4d23825f4 (master, v28.0.0-rc.2)
no changes in vendored code

full diff: 5cc3f1dab8...57d4d23825

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-17 11:57:23 +01:00
Sebastiaan van Stijn f488a75d6d
Merge pull request #5825 from thaJeztah/bump_engine
vendor: github.com/docker/docker 5cc3f1dab895 (master, v28.0.0-rc.2)
2025-02-14 19:40:38 +01:00
Sebastiaan van Stijn 1d3eb6f95b
vendor: github.com/docker/docker 5cc3f1dab895 (master, v28.0.0-rc.2)
full diff: b570831cc3...5cc3f1dab8

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-14 19:22:53 +01:00
Sebastiaan van Stijn 591fcb273a
vendor: golang.org/x/sys v0.29.0
full diff: https://github.com/golang/sys/compare/v0.28.0...v0.29.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-14 17:29:51 +01:00
Paweł Gronowski c9e7daec81
Merge pull request #5755 from LaurentGoderre/image-mount-subpath
Add image mount options
2025-02-13 13:09:12 +00:00
Sebastiaan van Stijn b2ac898781
Merge pull request #5822 from vvoland/pr-changelog-desc
gha: Mirror PR template and validate PR workflow from moby
2025-02-13 13:55:00 +01:00
Sebastiaan van Stijn 0eda4c51d7
Merge pull request #5818 from mohammedfuta2000/5814-limit-completion
Restrict completion to one suggestion on run, history, push, tag
2025-02-13 13:54:08 +01:00
Paweł Gronowski 1edc4e07d4
gha: Mirror PR template and validate PR workflow from moby
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-12 14:54:10 +01:00
Mohammed Aminu Futa a656dfd409 Restrict completion for some commands with a limit paramter for ImageNames
Previously, multiple suggestions were provided when completing
commands like `run`, `history` and `push`. This change
limits completion to a single suggestion for the above and 2 suggestions for `tag`

Signed-off-by: Mohammed Aminu Futa <mohammedfuta2000@gmail.com>
2025-02-12 12:42:19 +00:00
Paweł Gronowski a3f758fc13
Merge pull request #5820 from thaJeztah/bump_engine
vendor: github.com/docker/docker b570831cc3a3  (master, v28.0.0-rc.2)
2025-02-12 10:53:30 +00:00
Laurent Goderre 04b1b4e08a Add image mount options
Signed-off-by: Laurent Goderre <laurent.goderre@docker.com>
2025-02-11 12:19:12 -05:00
Sebastiaan van Stijn c6a7f9a646
vendor: github.com/docker/docker b570831cc3a3 (master, v28.0.0-rc.2)
full diff: https://github.com/docker/docker/compare/v28.0.0-rc.1...b570831cc3a3fcfe4edc96af4c249199b019c7dd

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-11 18:06:55 +01:00
Sebastiaan van Stijn 1e3e1bd5f4
Merge pull request #5812 from thaJeztah/bump_gofumpt
Dockerfile.dev: bump mvdan.cc/gofumpt to v0.7.0
2025-02-11 16:07:46 +01:00
Sebastiaan van Stijn 235e657b25
Merge pull request #5813 from thaJeztah/bump_goversioninfo
Dockerfile.dev: bump github.com/josephspurrier/goversioninfo to v1.4.1
2025-02-11 16:06:48 +01:00
Sebastiaan van Stijn b7e4fac496
Merge pull request #5819 from thaJeztah/bump_grpc
vendor: google.golang.org/grpc v1.69.4
2025-02-11 16:06:16 +01:00
Sebastiaan van Stijn 018bf1b237
vendor: google.golang.org/grpc v1.69.4
full diff: https://github.com/grpc/grpc-go/compare/v1.68.1...v1.69.4

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-11 15:55:27 +01:00
Sebastiaan van Stijn 516e822d4c
Merge pull request #5817 from thaJeztah/bump_pflag
vendor: github.com/spf13/pflag v1.0.6, remove local IPNetSliceVar fork
2025-02-11 12:50:51 +01:00
Sebastiaan van Stijn 558ebd5922
vendor: github.com/spf13/pflag v1.0.6, remove local IPNetSliceVar fork
- Add exported functions to preserve pkg/flag compatibility
- Add IPNetSlice and unit tests
- Revert the local fork added in 80a2256478,
  which was pending the upstream feature to be shipped in a release.

full diff: https://github.com/spf13/pflag/compare/v1.0.5...v1.0.6

Revert "Swarm init: use local IPNetSliceValue"

This reverts commit 80a2256478.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-11 12:19:51 +01:00
Paweł Gronowski 0af65dc566
Merge pull request #5816 from thaJeztah/connhelper_context
cli/connhelper/commandcon.New: pass context with WithoutCancel
2025-02-11 11:00:40 +00:00
Sebastiaan van Stijn 2c17edf804
cli/connhelper/commandcon.New: pass context with WithoutCancel
Passing the context to the constructor, but explicitly making it
non-cancelable and add a comment describing why context-cancelation
should not be propagated.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-10 21:41:48 +01:00
Sebastiaan van Stijn e6ee7ea94b
Merge pull request #5730 from thelovekesh/update/help-template
Remove preceding white space from cobra help template
2025-02-10 19:02:55 +01:00
Paweł Gronowski f7c3d1c796
Merge pull request #5815 from thaJeztah/bump_buildx
Dockerfile: dev-container: update buildx v0.20.1
2025-02-10 10:36:10 +00:00
Paweł Gronowski 661d079b1e
Merge pull request #5805 from thaJeztah/vendor_28.0.0-rc.1
vendor: github.com/docker/docker/v28.0.0-rc.1
2025-02-10 10:32:17 +00:00
thelovekesh 61a3b4bd50
Remove preceding white space from cobra help template
Signed-off-by: thelovekesh <lovekesh.kumar@rtcamp.com>
Signed-off-by: Lovekesh Kumar <lovekesh.kumar@rtcamp.com>
2025-02-10 10:51:25 +01:00
Sebastiaan van Stijn bca1f17da8
Merge pull request #5808 from thaJeztah/bump_gotest_tools
vendor: gotest.tools/v3 v3.5.2
2025-02-10 10:49:09 +01:00
Sebastiaan van Stijn 3560bdded9
Merge pull request #5809 from thaJeztah/bump_golangci_lint
Dockerfile: update golangci-lint to v1.63.4
2025-02-10 10:47:35 +01:00
Sebastiaan van Stijn 1acf32cdc6
Dockerfile: dev-container: update buildx v0.20.1
Also align versions in the Dockerfile.dev Dockerfile

full diff: https://github.com/docker/buildx/compare/v0.20.0...v0.20.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-10 10:09:42 +01:00
Sebastiaan van Stijn 7a72f38947
Merge pull request #5810 from thaJeztah/bump_gotestsum
Dockerfile: bump gotest.tools/gotestsum v1.12.0
2025-02-10 09:37:21 +01:00
Sebastiaan van Stijn bb74513ef3
Dockerfile.dev: bump github.com/josephspurrier/goversioninfo to v1.4.1
Re-align the version with the main Dockerfile, which was missed when
I updated the version in 93a931920b

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-09 17:07:52 +01:00
Sebastiaan van Stijn 7b3f264a69
Dockerfile.dev: bump mvdan.cc/gofumpt to v0.7.0
- full diff: https://github.com/mvdan/gofumpt/compare/v0.6.0...v0.7.0
- release notes: https://github.com/mvdan/gofumpt/releases/tag/v0.7.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-09 17:04:33 +01:00
Sebastiaan van Stijn aecc31039d
Dockerfile: bump gotest.tools/gotestsum v1.12.0
full diff: https://github.com/gotestyourself/gotestsum/compare/v1.10.0...v1.12.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-09 16:36:17 +01:00
Sebastiaan van Stijn e1a9d1cd37
Dockerfile: update golangci-lint to v1.63.4
full diff: https://github.com/golangci/golangci-lint/compare/v1.62.0...v1.63.4
Changelog: https://golangci-lint.run/product/changelog/#v1634

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-09 16:29:41 +01:00
Sebastiaan van Stijn df8c19d8fd
vendor: gotest.tools/v3 v3.5.2
- un-deprecates `assert.ErrorType`, `cmp.ErrorType`
- assert: ensure message is always displayed and fix under bazel
- poll: Continue(): use format.Message for formatting
- fix TestFromDirSymlink on Windows due to missing drive-letter
- fix various linting issues and minor bugs

full diff: https://github.com/gotestyourself/gotest.tools/compare/v3.5.1...v3.5.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-09 13:39:45 +01:00
Sebastiaan van Stijn 3c0d703acd
vendor: github.com/docker/docker/v28.0.0-rc.1
no diff; same code but tagged

full diff: https://github.com/docker/docker/compare/6c3797923dcb...v28.0.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-07 01:38:33 +01:00
Sebastiaan van Stijn bf65a46c2c
Merge pull request #5803 from thaJeztah/build_tags
add //go:build directives to prevent downgrading to go1.16 language
2025-02-06 19:59:01 +01:00
Sebastiaan van Stijn 2815d2337b
add //go:build directives to prevent downgrading to go1.16 language
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-06 19:52:03 +01:00
Paweł Gronowski c962084462
Merge pull request #5754 from thaJeztah/bump_engine
vendor: github.com/docker/docker 6c3797923dcb (master, v28.0-dev)
2025-02-06 18:26:54 +00:00
Sebastiaan van Stijn 01da8a582f
vendor: github.com/docker/docker 6c3797923dcb (master, v28.0-dev)
full diff: 6968719093...6c3797923d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-06 19:16:50 +01:00
Paweł Gronowski 11999b16e4
Merge pull request #5778 from laurazard/add-cause-statuserr
Don't print "context canceled" if user terminated
2025-02-06 14:20:38 +00:00
Paweł Gronowski eec977bbea
Merge pull request #5800 from thaJeztah/bump_version
bump version to v28.0.0-dev
2025-02-06 13:30:15 +00:00
Laura Brehm 76e0088b5c
minor cleanup
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2025-02-06 14:16:45 +01:00
Laura Brehm 85a77af591
Don't print "context canceled" if user terminated
Without breaking API compatibility, this patch allows us to know whether
a returned `cli/StatusError` was caused by a context cancellation or
not, which we can use to provide a nicer UX and not print the Go
"context canceled" error message if this is the cause.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2025-02-06 14:16:20 +01:00
Sebastiaan van Stijn 7e83ff7735
bump version to v28.0.0-dev
This file is only used as default if no version is specified. We
should probably get rid of this, but let's update it to better
reflect the version that developer builds are building.

d48fb9f9f7/docker.Makefile (L22)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-06 01:41:59 +01:00
Sebastiaan van Stijn d48fb9f9f7
Merge pull request #5795 from vvoland/update-go
update to go1.23.6
2025-02-05 19:23:43 +01:00
Paweł Gronowski eb6546b523
Merge pull request #5774 from Benehiko/improve-login-text
login: improve text on already authenticated and on OAuth login
2025-02-05 12:06:53 +00:00
Alano Terblanche 6d7afd48a4
login: improve text on already authenticated and on OAuth login
Users have trouble understanding the different login paths on the CLI.
The default login is performed through an OAuth flow with the option to
fallback to a username and PAT login using the docker login -u <username>
option.

This patch improves the text around docker login, indicating:
- The username is shown when already authenticated
- Steps the user can take to switch user accounts are printed when
  authenticated in an info.
- When not authenticated, the OAuth login flow explains the fallback
  clearly to the user in an info.
- The password prompt now explicitly states that it accepts a PAT in an
  info.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-02-05 12:32:24 +01:00
Alano Terblanche 9005f36e6e
Merge pull request #5760 from Benehiko/user-terminated-ctx-err
cmd/docker: add cause to user-terminated `context.Context`
2025-02-05 12:16:22 +01:00
Paweł Gronowski 1d9d349c19
update to go1.23.6
- https://github.com/golang/go/issues?q=milestone%3AGo1.23.6+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.23.5...go1.23.6

This minor release include 1 security fix following the security policy:

- crypto/elliptic: timing sidechannel for P-256 on ppc64le

  Due to the usage of a variable time instruction in the assembly implementation
  of an internal function, a small number of bits of secret scalars are leaked on
  the ppc64le architecture. Due to the way this function is used, we do not
  believe this leakage is enough to allow recovery of the private key when P-256
  is used in any well known protocols.

This is CVE-2025-22866 and Go issue https://go.dev/issue/71383.

View the release notes for more information:
https://go.dev/doc/devel/release#go1.23.6

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-04 20:34:35 +01:00
Paweł Gronowski dff0dc8afa
Merge pull request #5790 from thaJeztah/leftover_cleanups
cli/command: some minor cleanups
2025-02-04 12:30:30 +00:00
Sebastiaan van Stijn 7c3fa8172b
Merge pull request #5791 from thaJeztah/multi_errors
cli/command: use errors.Join instead of our own implementation
2025-02-04 12:23:11 +01:00
Paweł Gronowski 5b90e0e4e5
Merge pull request #5744 from vvoland/image-tree-chips
image/tree: Chips to represent "in use"
2025-02-04 09:23:24 +00:00
Sebastiaan van Stijn 81da375c4d
cli/command/service: runScale: use errors.Join, and cleanup
- Use stdlib multi-errors instead of creating our own
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- rewrite runServiceScale to return warnings, instead of printing them

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 20:35:48 +01:00
Sebastiaan van Stijn 09b513ecfd
cli/command/service: runRollback: remove intermediate vars
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 20:31:52 +01:00
Sebastiaan van Stijn aa96cb7aa0
cli/command/volume: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 20:31:52 +01:00
Sebastiaan van Stijn be985bd28e
cli/command/stack/swarm: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 20:31:45 +01:00
Sebastiaan van Stijn f1193effc0
cli/command/service: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:36:59 +01:00
Sebastiaan van Stijn f9e4335564
cli/command/secret: use errors.Join
- Use stdlib multi-errors instead of creating our own
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- rename runSecretRemove to runRemove to align with other commands

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:33:58 +01:00
Sebastiaan van Stijn 2a9fd4a939
cli/command/node: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:30:56 +01:00
Sebastiaan van Stijn f8729c6da2
cli/command/manifest: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:30:25 +01:00
Sebastiaan van Stijn 1fd9d0dd34
cli/command/manifest: pass manifest-store and handle context
- pass through the manifest-store, instead of the CLI as a whole
- handle context cancellation
- rename `runRm` to `runRemove` to align with other commands

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:27:59 +01:00
Sebastiaan van Stijn f431f61568
cli/command/inspect: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:21:27 +01:00
Sebastiaan van Stijn 7147e85f63
cli/command/image: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:20:34 +01:00
Sebastiaan van Stijn 2b9a4d5f4c
cli/command/context: use errors.Join
Use stdlib multi-errors instead of creating our own; also
touch-up one error and some minor cleanups.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:19:18 +01:00
Sebastiaan van Stijn 150f27b68c
cli/command/container: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:17:50 +01:00
Sebastiaan van Stijn 791e06b435
cli/command/config: RunConfigRemove: use errors.Join
Use stdlib multi-errors instead of creating our own

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:16:28 +01:00
Sebastiaan van Stijn 632f179e8f
cli/command/image: minor cleanups
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:08:08 +01:00
Sebastiaan van Stijn e81d76ffe1
cli/command/container: minor cleanups
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:08:08 +01:00
Sebastiaan van Stijn deaa601189
cli/command/config: minor cleanups
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 19:08:08 +01:00
Sebastiaan van Stijn ce30966636
Merge pull request #5785 from thaJeztah/checkpoint_test_keeprunning
TestCheckpointCreateWithOptions check both "keep-running=true/false"
2025-02-03 18:25:31 +01:00
Sebastiaan van Stijn 795b7d5f0a
Merge pull request #5788 from thaJeztah/progress_clean
service/progress: ServiceProgress: avoid fuzzy matching service ID in loop
2025-02-03 18:24:52 +01:00
Paweł Gronowski c950d48f72
image/tree: Chips to represent "in use"
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-02-03 18:24:32 +01:00
Sebastiaan van Stijn 919bd6aff3
Merge pull request #5779 from thaJeztah/fix_plugin_multierr
cli/command/plugins: runRemove: fix incorrect use of errors.Join
2025-02-03 18:24:27 +01:00
Sebastiaan van Stijn ac13f502c6
Merge pull request #5787 from thaJeztah/jsonstream_noshadow
jsonstream: Display: rename var that shadowed type
2025-02-03 17:45:07 +01:00
Alano Terblanche c51be77767
cmd/docker: add cause to user-terminated `context.Context`
This patch adds a "cause" to the `context.Context`
error when the user terminates the process through
SIGINT/SIGTERM.

This allows us to distinguish the cause of the
`context.Context` cancellation. In future we would
also be able to improve the UX of printed errors
based on the underlying cause.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>

cmd/docker: fix possible race between ctx channel and signal channel

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>

test: notifyContext

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>

cmd/docker: print status on SIGTERM and not SIGINT

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-02-03 16:29:09 +01:00
Sebastiaan van Stijn 8169a5142b
jsonstream: Display: rename var that shadowed type
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 16:17:11 +01:00
Sebastiaan van Stijn a4288003bd
service/progress: ServiceProgress: avoid fuzzy matching service ID in loop
Tasks with a service filter will result in the daemon performing a lookup
of the full service ID, then updating the provided filter with the actual
ID: 96ded2a1ba/daemon/cluster/tasks.go (L15-L30)

The `getService()` helper has a fast-path for situations where the given
filter is a full ID, before falling back to fuzzy-logic to search filters
by service name or prefix, which would return an error if the result is
ambiguous;
96ded2a1ba/daemon/cluster/helpers.go (L62-L81)

The loop executed here calls `client.ServiceInspectWithRaw()` to get info
of the service, and that method is ultimately calling the exact same
`getService()` helper on the daemon side, which means that we don't need
to repeat the work; we can use the `Service.ID` resolved from that call,
and use it to apply as filter for listing the tasks.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 16:16:19 +01:00
Sebastiaan van Stijn e88b1939f7
service/progress: newReplicatedJobProgressUpdater: slight cleanup
Use intermediate vars, so that the replicatedJobProgressUpdater can
be created in one go intead of setting some fields after the fact.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 16:16:16 +01:00
Paweł Gronowski 4771abac9e
Merge pull request #5780 from thaJeztah/multierr_simplify
cli/command/stack/swarm: waitOnServices remove redundant check for multi-error
2025-02-03 15:09:27 +00:00
Sebastiaan van Stijn dea59eabba
cli/command/stack/swarm: waitOnServices remove redundant check for multi-error
This check was redundant, because `errors.Join` already checks if the
list of errors is either empty, or only contains `nil` errors, as can
be seen in [this example][1];

    package main

    import (
        "errors"
        "testing"
    )

    func TestMultiErr(t *testing.T) {
        var errs []error
        if err := errors.Join(errs...); err != nil {
            t.Fatal(err)
        }

        errs = append(errs, nil, nil, nil)
        t.Logf("errs contains %d elements", len(errs))
        if err := errors.Join(errs...); err != nil {
            t.Fatal(err)
        }

        errs = append(errs, errors.New("with an error"))
        if err := errors.Join(errs...); err == nil {
            t.Fatal("expected an error")
        }
    }

[1]: https://go.dev/play/p/iSuGP81eght

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:26:43 +01:00
Sebastiaan van Stijn d68c4d8217
Merge pull request #5782 from thaJeztah/volume_tests_clean
cli/command/volume: various fixes and improvements in tests
2025-02-03 13:24:53 +01:00
Sebastiaan van Stijn 37b25f2265
cli/command/plugins: runRemove: fix incorrect use of errors.Join
commit 71ebbb81ae replaced the use of the
custom "cli.Errors" type for stdlib's errors.Join, however it made a
mistake by calling errors.Join for each error occurred, which "nests"
each error instead of putting each error at the same level.

Thanks to Paweł Gronowski for spotting this on the [pull request][1]

[1]: 71ebbb81ae (r1810257735)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:08:05 +01:00
Sebastiaan van Stijn 007e88ec3d
TestCheckpointCreateWithOptions check both "keep-running=true/false"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:05:23 +01:00
Sebastiaan van Stijn 31b8198286
cli/command/volume: TestVolumeCreateClusterOpts: minor fixes and refactor
- assert unhandled error
- discard stdout/stderr output

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:04:52 +01:00
Sebastiaan van Stijn 5b8c08d19e
cli/command/volume: TestVolumeCreateCluster: minor fixes and refactor
- assert unhandled error
- use sub-tests
- use slightly more unique volume-names
- discard stdout/stderr output

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:04:52 +01:00
Sebastiaan van Stijn a8265e72bf
cli/command/volume: TestVolumeCreateWithFlags: minor fixes
- assert unhandled error
- reset command-args to prevent test failing when running from pre-compiled test-binary
- use a const and a slightly more unique name for the volume-name
- discard stdout/stderr output

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:04:52 +01:00
Sebastiaan van Stijn 8b5e5539e1
cli/command/volume: TestVolumeCreateWithName: minor fixes and improvements
- assert unhandled error
- use sub-tests
- add test-case for conflicting options (both flag and name)
- reset command-args to prevent test failing when running from pre-compiled test-binary
- use a const and a slightly more unique name for the volume-name
- discard stdout/stderr output

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:04:52 +01:00
Sebastiaan van Stijn 2e266001c6
cli/command/volume: TestVolumeCreateErrors: assert unhandled errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 13:04:48 +01:00
Sebastiaan van Stijn 4808d1bcd2
Merge pull request #5783 from thaJeztah/newline_galore
assorted cleanups: use Println, rename vars for consistency
2025-02-03 13:04:00 +01:00
Sebastiaan van Stijn 987da09578
cli/command/volume: remove example and var for long description
This was the only command for which we set the "example" field; while
we could consider doing this for other commands, we need to look what's
best w.r.t. duplicating the information maintained in markdown.

Also remove the intermediate variable used for the long description,
as this was also the only location where we used one.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:21:00 +01:00
Sebastiaan van Stijn 13ef82974d
cli/flags: suppress some errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:21:00 +01:00
Sebastiaan van Stijn dc5a4501a4
cli/command: minor cleanups: use Println, suppress errors
- use Println to print newline instead of custom format
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:21:00 +01:00
Sebastiaan van Stijn cd6d902dff
cli/command/inspect: remove additional newline from log
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:21:00 +01:00
Sebastiaan van Stijn 10f5b3f73a
cli/command/volumes: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:20:59 +01:00
Sebastiaan van Stijn 299aae0419
cli/command/trust: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:20:59 +01:00
Sebastiaan van Stijn 5cfc89c1c2
cli/command/system: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:20:59 +01:00
Sebastiaan van Stijn 8c5e85d4cf
cli/command/swarm: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier
- fix some tests to work with "go test -update"
- rewrite TestSwarmInit to use sub-tests

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:20:56 +01:00
Sebastiaan van Stijn 925b8fe34c
cli/command/stack: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:12 +01:00
Sebastiaan van Stijn aa74f931d3
cli/command/service: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:12 +01:00
Sebastiaan van Stijn 016dbef449
cli/command/registry: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:11 +01:00
Sebastiaan van Stijn 53aed6119b
cli/command/plugin: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:11 +01:00
Sebastiaan van Stijn 35e74d58e3
cli/command/node: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:11 +01:00
Sebastiaan van Stijn 886f2295cf
cli/command/network: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:11 +01:00
Sebastiaan van Stijn 5d3bdf8ac2
cli/command/manifest: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:11 +01:00
Sebastiaan van Stijn c8f27b027f
cli/command/image: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:11 +01:00
Sebastiaan van Stijn a0ca41e6f6
cli/command/formatter: suppress some errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:10 +01:00
Sebastiaan van Stijn 82e2efbbf7
cli/command/context: minor cleanups
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:10 +01:00
Sebastiaan van Stijn c462eaee11
cli/command/container: minor cleanups: use Println
- use Println to print newline instead of custom format
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:10 +01:00
Sebastiaan van Stijn 8650ffef38
cli/command/checkpoint: minor cleanups: use Println, rename vars
- use Println to print newline instead of custom format
- use dockerCLI with Go's standard camelCase casing.
- suppress some errors to make my IDE and linters happier

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:10 +01:00
Sebastiaan van Stijn b10b79e6fd
cli-plugins: minor cleanups: use Println
- use Println to print newline instead of custom format
- suppress some errors to make my IDE and linters happier
- use res.Assert() with icmd.Expected{} where possible to make
  assertions not depend on newline / whitespace randomness
- use apiClient instead of client for the API client to
  prevent shadowing imports.
- use dockerCLI with Go's standard camelCase casing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-03 12:18:07 +01:00
Sebastiaan van Stijn 4d7fe01d4b
Merge pull request #5781 from thaJeztah/less_pkg_errors
remove uses of pkg/errors in tests
2025-02-03 10:56:31 +01:00
Sebastiaan van Stijn 2e26ce145b
e2e/testutils: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 19:48:46 +01:00
Sebastiaan van Stijn 4de5e92124
internal/test: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 19:48:22 +01:00
Sebastiaan van Stijn c55b39a2e0
cli/config/credentials: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 16:00:02 +01:00
Sebastiaan van Stijn 832f5fa2c8
cli/compose/convert: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 16:00:01 +01:00
Sebastiaan van Stijn 45d81f849e
cli/command: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 16:00:01 +01:00
Sebastiaan van Stijn a85a94f46b
cli/command/system: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 16:00:00 +01:00
Sebastiaan van Stijn 694d248001
cli/command/swarm: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 16:00:00 +01:00
Sebastiaan van Stijn 8b09ee1e12
cli/command/stack: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:59 +01:00
Sebastiaan van Stijn ec5ae0c2d0
cli/command/secret: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:59 +01:00
Sebastiaan van Stijn c50068f7e1
cli/command/plugin: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:58 +01:00
Sebastiaan van Stijn 2b02e05f9a
cli/command/node: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:58 +01:00
Sebastiaan van Stijn 38f61539e5
cli/command/network: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:58 +01:00
Sebastiaan van Stijn d6c26471d1
cli/command/manifest: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:58 +01:00
Sebastiaan van Stijn f29fdd3091
cli/command/image: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:57 +01:00
Sebastiaan van Stijn d30c894af1
cli/command/idresolver: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:57 +01:00
Sebastiaan van Stijn 5a99ea9ad4
cli/command/container: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:57 +01:00
Sebastiaan van Stijn 0d913efe8a
cli/command/config: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:59:52 +01:00
Sebastiaan van Stijn 957be84a3c
cli/command/checkpoint: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:52:47 +01:00
Sebastiaan van Stijn 10aca7dd50
cli/command/volume: remove uses of pkg/errors in tests
While there may be reasons to keep pkg/errors in production code,
we don't need them for these tests.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-02-01 15:52:44 +01:00
Albin Kerouanton bdd70c1c61
Merge pull request #5739 from robmry/fix_links_check
Allow '--link' with '--network bridge'
2025-01-28 12:15:15 +01:00
Sebastiaan van Stijn cc224b8ae9
Merge pull request #5773 from thaJeztah/remove_dockerd_manpage
remove dockerd man-page (moved back to moby repository)
2025-01-27 15:20:29 +01:00
Sebastiaan van Stijn a87cb974fc
remove dockerd man-page (moved back to moby repository)
When splitting the docker CLI from the moby/moby repository, the dockerd
documentation and man-pages were moved to the CLI repository. This was a
bit of a bad choice, as now the documentation and code lived in separate
repositories, but when the CLI and dockerd packages were split, the man
page for dockerd ended up in the CLI package.

Starting with [moby@d6e9b5f], the dockerd man-page has been reintegrated
into the moby repository, so we cab  remove it from the CLI repository.

[moby@d6e9b5f]: d6e9b5fe30

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-25 01:11:22 +01:00
Sebastiaan van Stijn b8879a4eb5
Merge pull request #5770 from thaJeztah/build_completion
Makefile: add "shell-completion" target
2025-01-24 14:41:41 +01:00
Sebastiaan van Stijn 6ab9b92aa5
Makefile: add "shell-completion" target
Add a target to build the (cobra) generated completion and store
them inside build/completions.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-24 14:18:30 +01:00
Paweł Gronowski 17c5fe601b
Merge pull request #5767 from thaJeztah/bump_alpine
Dockerfile: update to alpine 3.21
2025-01-22 13:49:24 +01:00
Sebastiaan van Stijn 0760e85132
Dockerfile: update to alpine 3.21
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-21 18:17:45 +01:00
Rob Murray 2c35778a63 Allow '--link' with '--network bridge'
The '--link' option should only be migrated to an endpoint
option if the network is user-defined ... there was already
an exception for network "default", but not for "bridge".

Signed-off-by: Rob Murray <rob.murray@docker.com>
2025-01-21 16:58:42 +00:00
Paweł Gronowski ad54f757d3
Merge pull request #5761 from thaJeztah/bump_golang_1.23.5
update to go1.23.5 (fix CVE-2024-45341, CVE-2024-45336)
2025-01-21 11:31:58 +01:00
Alano Terblanche 41c2786716
Merge pull request #5663 from Benehiko/ctx-jsonmessage
pkg/command: wrap `jsonmessage.DisplayJSONMessagesStream` with go context
2025-01-21 11:22:40 +01:00
Paweł Gronowski fdb75d2f6b
Merge pull request #5765 from thaJeztah/bump_dev_tools
Dockerfile: dev-container: update buildx v0.20.0, compose v2.32.4
2025-01-21 10:34:32 +01:00
Sebastiaan van Stijn 1546f023fb
Dockerfile: update compose to v2.32.4
Update the compose cli plugin used in the dev-container

full diff: https://github.com/docker/compose/compare/v2.30.3...v2.32.4

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-21 09:52:10 +01:00
Sebastiaan van Stijn 7b07242708
Dockerfile: update buildx to v0.20.0
Update the buildx cli plugin used in the dev-container

full diff: https://github.com/docker/buildx/compare/v0.18.0..v0.20.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-21 09:51:39 +01:00
Sebastiaan van Stijn 55e6db580c
Merge pull request #5763 from vvoland/gha-relbranches
gha: Adjust release branches
2025-01-20 18:21:18 +01:00
Alano Terblanche 91adb70d6b
pkg/command: wrap `jsonmessage.DisplayJSONMessagesStream` with go context
Allows for the `jsonmessage.DisplayJSONMessagesStream` function
to correctly return when the context is cancelled with the appropriate
reason (`ctx.Error()`) instead of just a nil error.

Follow-up to 30a73ff19c

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
Co-authored-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-01-20 16:36:11 +01:00
Paweł Gronowski 81b0bb58ba
gha: Adjust release branches
Adjust all workflows to also run on branches like `27.x`

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-01-20 16:35:39 +01:00
Sebastiaan van Stijn 3c0691146d
update to go1.23.5 (fix CVE-2024-45341, CVE-2024-45336)
go1.23.5 (released 2025-01-16) includes security fixes to the crypto/x509 and
net/http packages, as well as bug fixes to the compiler, the runtime, and the
net package. See the Go 1.23.5 milestone on our issue tracker for details;

- https://github.com/golang/go/issues?q=milestone%3AGo1.23.5+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.23.4...go1.23.5

Hello gophers,

We have just released Go versions 1.23.5 and 1.22.11, minor point releases.

These minor releases include 2 security fixes following the security policy:

- crypto/x509: usage of IPv6 zone IDs can bypass URI name constraints

  A certificate with a URI which has a IPv6 address with a zone ID may
  incorrectly satisfy a URI name constraint that applies to the certificate
  chain.

  Certificates containing URIs are not permitted in the web PKI, so this
  only affects users of private PKIs which make use of URIs.

  Thanks to Juho Forsén of Mattermost for reporting this issue.

  This is CVE-2024-45341 and Go issue https://go.dev/issue/71156.

- net/http: sensitive headers incorrectly sent after cross-domain redirect

  The HTTP client drops sensitive headers after following a cross-domain redirect.
  For example, a request to a.com/ containing an Authorization header which is
  redirected to b.com/ will not send that header to b.com.

  In the event that the client received a subsequent same-domain redirect, however,
  the sensitive headers would be restored. For example, a chain of redirects from
  a.com/, to b.com/1, and finally to b.com/2 would incorrectly send the Authorization
  header to b.com/2.

  Thanks to Kyle Seely for reporting this issue.

  This is CVE-2024-45336 and Go issue https://go.dev/issue/70530.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-20 16:04:17 +01:00
Paweł Gronowski 66a584a66d
Merge pull request #5757 from vvoland/images-tree-name
image/tree: Print longest names first and use full width
2025-01-20 14:16:19 +01:00
Alano Terblanche 1f3615e756
Merge pull request #5756 from Benehiko/completion-descriptions
cmd/docker: enable cobra completion descriptions
2025-01-20 12:00:12 +01:00
Paweł Gronowski 26010e4c3c
image/tree: Print longest names first and use full width
When printing image names, sort them by length and print the longest
first. This also allows them to use a full terminal width because they
are not printed alongside other columns.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-01-20 11:25:57 +01:00
Paweł Gronowski f97ec69122
Merge pull request #5758 from vvoland/images-tree-elips-dot
cli/tree: Use single character triple dot
2025-01-20 10:24:00 +01:00
Paweł Gronowski f906139fc8
cli/tree: Use single character triple dot
Using 3 characters instead of 1 to ellipsize a long string is wasteful.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-01-17 14:34:45 +01:00
Alano Terblanche 4c2fece0cb
cmd/docker: enable cobra completion descriptions
This patch enables descriptions on the CLI completion script.
It used to be disabled due to the CLI historically not supporting
cobra v2 completions, as seen by this patch
cbec75e2f3.

As an escape hatch, the user can set the `DOCKER_CLI_DISABLE_COMPLETION_DESCRIPTION`
environment variable to disable the completion description when
generating the completion file with `docker completion <fish|bash|zsh>`.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2025-01-17 14:30:11 +01:00
Mert Şişmanoğlu 48dbdc6f2d
fix(dockerfiles): Update CMD instruction in 'Dockerfile.dev' to use exec form instead of shell form
* https://docs.docker.com/reference/build-checks/json-args-recommended/

Signed-off-by: Mert Şişmanoğlu <mert190737fb@gmail.com>
2025-01-15 18:32:54 +03:00
Sebastiaan van Stijn f4a68da195
Merge pull request #5752 from thaJeztah/bump_yamlv3
switch to gopkg.in/yaml.v3
2025-01-15 15:24:01 +01:00
Sebastiaan van Stijn 58bf0f1846
switch to gopkg.in/yaml.v3
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 23:54:33 +01:00
Sebastiaan van Stijn ce293bdb81
Merge pull request #5751 from thaJeztah/update_semconv
cli/command: update semconv to 1.26.0
2025-01-14 20:41:41 +01:00
Sebastiaan van Stijn 9abd0ebdf4
cli/command: update semconv to 1.26.0
Align the version with what's used by buildkit.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 19:37:57 +01:00
Sebastiaan van Stijn 88755df233
Merge pull request #5741 from thaJeztah/vendor_cli_docs_tool
update cli-docs-tool to v0.9.0, go-md2man v2.0.6
2025-01-14 19:36:26 +01:00
Sebastiaan van Stijn 5e970091d3
Merge pull request #5750 from thaJeztah/vendor_otel
vendor: otel v0.56.0 / v1.31.0
2025-01-14 19:35:53 +01:00
Sebastiaan van Stijn 2f42b32722
vendor: otel v0.56.0 / v1.31.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 19:09:03 +01:00
Sebastiaan van Stijn 15e4848a0e
Merge pull request #5748 from thaJeztah/vendor_runewidth
vendor: github.com/mattn/go-runewidth v0.0.16
2025-01-14 16:24:58 +01:00
Sebastiaan van Stijn 3d9b861165
vendor: github.com/mattn/go-runewidth v0.0.16
adds support for Unicode 15.1.0

full diff: https://github.com/mattn/go-runewidth/compare/v0.0.15...v0.0.16

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 15:18:35 +01:00
Sebastiaan van Stijn 25bdd5ced6
Merge pull request #5747 from thaJeztah/vendor_containerd_platforms
vendor: github.com/containerd/platforms v1.0.0-rc.1
2025-01-14 15:13:42 +01:00
Sebastiaan van Stijn 5896278838
Merge pull request #5745 from thaJeztah/vendor_grpc_v1.68.1
vendor: google.golang.org/grpc v1.68.1, google.golang.org/genproto 324edc3d5d38
2025-01-14 15:07:58 +01:00
Sebastiaan van Stijn aa540679e4
vendor: github.com/containerd/platforms v1.0.0-rc.1
full diff: https://github.com/containerd/platforms/compare/v0.2.1...v1.0.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 14:28:53 +01:00
Sebastiaan van Stijn 1b9bf398bf
Merge pull request #5746 from thaJeztah/vendor_pty_v1.1.24
vendor: github.com/creack/pty v1.1.24
2025-01-14 14:17:12 +01:00
Sebastiaan van Stijn d3ca995857
vendor: github.com/creack/pty v1.1.24
full diff: https://github.com/creack/pty/compare/v1.1.21...v1.1.24

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 13:41:12 +01:00
Sebastiaan van Stijn b412f7199a
vendor: google.golang.org/grpc v1.68.1, google.golang.org/genproto 324edc3d5d38
full diff: https://github.com/grpc/grpc-go/compare/v1.66.3...v1.68.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 13:31:06 +01:00
Sebastiaan van Stijn dbc5cf67eb
Merge pull request #5740 from akerouanton/fluentd-async-connect-removal
Drop support for fluentd-async-connect
2025-01-13 19:28:06 +01:00
Sebastiaan van Stijn 7244f7d42f
update cli-docs-tool to v0.9.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-13 18:59:22 +01:00
Sebastiaan van Stijn 6f3ba987b1
vendor: github.com/docker/cli-docs-tool v0.9.0
full diff: https://github.com/docker/cli-docs-tool/compare/v0.8.0...v0.9.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-13 18:58:31 +01:00
Sebastiaan van Stijn 97a14c4561
update go-md2man to v2.0.5
full diff: https://github.com/cpuguy83/go-md2man/compare/v2.0.5...v2.0.6

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-13 18:58:07 +01:00
Albin Kerouanton acbdad9551 completion: replace fluentd-async-connect with fluentd-async
Signed-off-by: Albin Kerouanton <albinker@gmail.com>
2025-01-13 18:38:24 +01:00
Albin Kerouanton 3da5f5893c docs: mark logger opt 'fluentd-async-connect' as removed
Signed-off-by: Albin Kerouanton <albinker@gmail.com>
2025-01-13 18:38:09 +01:00
Sebastiaan van Stijn b462778491
Merge pull request #5708 from thaJeztah/bump_engine
vendor: github.com/docker/docker 69687190936d (master, v28.0-dev)
2025-01-13 13:47:16 +01:00
Sebastiaan van Stijn 0df55307c8
vendor: github.com/docker/docker 69687190936d (master, v28.0-dev)
full diff: 50212d215b...6968719093

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-11 01:17:36 +01:00
Sebastiaan van Stijn 4e217ae9c1
Merge pull request #5737 from crazy-max/bake-v6
ci: update bake-action to v6
2025-01-10 20:26:52 +01:00
CrazyMax cc571902bc
ci: update bake-action to v6
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
2025-01-10 16:45:54 +01:00
Sebastiaan van Stijn 8e365dd3d8
Merge pull request #5734 from vvoland/gha-build-xbranches
gha/build: Publish bin image for release branches
2025-01-10 14:51:49 +01:00
Paweł Gronowski 987befaeac
gha/build: Publish bin image for release branches
We moved to the major release branches with a `.x` suffix and forgot to
adjust this workflow to run on branches like `27.x`.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-01-10 14:32:54 +01:00
Sebastiaan van Stijn ff4697d820
Merge pull request #5729 from thaJeztah/cleanup_plugin_install
cli/command/plugin: runCreate: minor cleanup
2025-01-08 18:57:11 +01:00
Sebastiaan van Stijn 557afb66d0
Merge pull request #5728 from thaJeztah/vendor_engine
vendor: github.com/docker/docker 50212d215ba7 (master, v28.0-dev)
2025-01-08 18:56:53 +01:00
Sebastiaan van Stijn 216674c3e3
vendor: github.com/docker/docker 50212d215ba7 (master, v28.0-dev)
full diff: 6f6c3b9211...50212d215b

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-08 18:11:19 +01:00
Sebastiaan van Stijn bf2dae22de
cli/command/plugin: runCreate: minor cleanup
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-08 12:53:20 +01:00
Sebastiaan van Stijn a289f11ac8
vendor: github.com/moby/swarmkit/v2 v2.0.0-20250103191802-8c1959736554
no changes in vendored code

full diff: e8ecf83ee0...8c19597365

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-06 10:28:35 +01:00
Sebastiaan van Stijn 667ece32cf
Merge pull request #5724 from thaJeztah/deprecate_nondistributable_artifacts
Deprecate configuration for pushing non-distributable artifacts
2025-01-05 14:39:35 +01:00
Sebastiaan van Stijn 7e8f94903d
docs, man: remove --allow-nondistributable-artifacts flag
This flag is deprecated and no longer functional.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-04 15:18:03 +01:00
Sebastiaan van Stijn 760326694d
contrib/completion: remove --allow-nondistributable-artifacts flag
This flag is deprecated and no longer functional.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-04 15:18:00 +01:00
Sebastiaan van Stijn 2334df1108
Deprecate configuration for pushing non-distributable artifacts
Non-distributable artifacts (also called foreign layers) were introduced in
docker v1.12 to accommodate Windows images for which the EULA did not allow
layers to be distributed through registries other than those hosted by Microsoft.
The concept of foreign / non-distributable layers was adopted by the OCI distribution
spec in [oci#233]. These restrictions were relaxed later to allow distributing
these images through non-public registries, for which a configuration was added
in Docker v17.0.6.0.

In 2022, Microsoft updated the EULA and [removed these restrictions][msft-3645201],
followed by the OCI distribution specification deprecating foreign layers in [oci#965].
In 2023, Microsoft [removed the use of foreign data layers][msft-3846833] for their images,
making this functionality obsolete.

Docker v28.0 deprecates the `--allow-nondistributable-artifacts` daemon flag and
corresponding `allow-nondistributable-artifacts` field in `daemon.json`. Setting
either option no longer takes an effect, but a deprecation warning log is added
to raise awareness about the deprecation. This warning is planned to become an
error in the Docker v29.0.

Users currently using these options are therefore recommended to remove this
option from their configuration to prevent the daemon from starting when
upgrading to Docker v29.0.

The `AllowNondistributableArtifactsCIDRs` and `AllowNondistributableArtifactsHostnames`
fields in the `RegistryConfig` of the `GET /info` API response are also deprecated.
For API version v1.48 and lower, the fields are still included in the response
but always `null`. In API version v1.49 and higher, the field will be omitted
entirely.

[oci#233]: https://github.com/opencontainers/image-spec/pull/233
[oci#965]: https://github.com/opencontainers/image-spec/pull/965
[msft-3645201]: https://techcommunity.microsoft.com/blog/containers/announcing-windows-container-base-image-redistribution-rights-change/3645201
[msft-3846833]: https://techcommunity.microsoft.com/blog/containers/announcing-removal-of-foreign-layers-from-windows-container-images/3846833

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-04 15:16:36 +01:00
Sebastiaan van Stijn 8be29ef534
Merge pull request #5725 from thaJeztah/remove_cors_headers_completion
contrib/completion: remove deprecated --api-cors-header
2025-01-04 14:01:51 +01:00
Sebastiaan van Stijn cfa3a0ca27
Merge pull request #5727 from thaJeztah/bump_moby_term
vendor: github.com/moby/term v0.5.2
2025-01-04 02:22:39 +01:00
Sebastiaan van Stijn a139bb293b
Merge pull request #5722 from thaJeztah/rm_oom_score_adj
remove remnants of --oom-score-adj daemon config (docs, completion)
2025-01-03 22:42:03 +01:00
Sebastiaan van Stijn 2fc32c707b
vendor: github.com/moby/term v0.5.2
- update github.com/Azure/go-ansiterm to v0.0.0-20250102033503-faa5f7b0171c
  to fix OSC string terminator parsing.
- add security policy
- update github actions and test against go1.22, go1.23

full diff: https://github.com/moby/term/compare/v0.5.0...v0.5.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-03 22:33:30 +01:00
Sebastiaan van Stijn e1a0c377b7
vendor: github.com/Azure/go-ansiterm faa5f7b0171c
- fix OSC string terminator parsing

diff: d185dfc1b5...faa5f7b017

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-03 22:32:37 +01:00
Sebastiaan van Stijn f42c0ccd09
contrib/completion: remove deprecated --api-cors-header
This flag was deprecated in docker v27.0, and removed in v28.0 (producing
and error).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-03 21:26:00 +01:00
Sebastiaan van Stijn 2db88599fd
contrib/completion: remove --oom-score-adj daemon flag
This flag was deprecated in docker v24.0, and no longer functional
since v25.0; fully removed in v26.0, so we can remove the docs
for this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-03 20:21:30 +01:00
Sebastiaan van Stijn eb5c507cd1
docs: dockerd: --oom-score-adj flag
This flag was deprecated in docker v24.0, and no longer functional
since v25.0; fully removed in v26.0, so we can remove the docs
for this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-03 20:20:47 +01:00
Sebastiaan van Stijn 5be685e647
Merge pull request #5718 from thaJeztah/remove_isolation_hint
docs, man: remove confusing example for "--isolation"
2025-01-03 14:48:51 +01:00
Sebastiaan van Stijn d1c76538e9
Merge pull request #5719 from dmcgowan/build-context-io-copy
Use io.copy for build context compression
2025-01-03 13:51:50 +01:00
Derek McGowan 7b37f30da2
Use io.copy for build context compression
The use of pools here is unnecessary and creates a code dependency on
moby library which will move to internal.

The pool does not provide any value here since it is only done for a
single operation and unlikely performed in alongside other operations
which are re-using the buffers many times between garbage collections.

Signed-off-by: Derek McGowan <derek@mcg.dev>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-03 13:45:38 +01:00
Sebastiaan van Stijn 75f791d904 builder: use lazyregexp to compile regexes on first use
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-02 21:37:32 +01:00
Sebastiaan van Stijn 7138107e87
Merge pull request #5716 from thaJeztah/vendor_moby_master
vendor: github.com/docker/docker 6f6c3b921180 (master, v28.0.0-dev)
2025-01-02 12:32:32 +01:00
Sebastiaan van Stijn 7b7a4c020e
docs, man: remove confusing example for "--isolation"
This snippet was added in [docker@38ec5d8][1]. The intent was to indicate
that an empty value is equivalent to passing "default" as value. However,
passing the `--isolation` flag _without a value_ (i.e., no `=` specified)
will fail in many cases, as any string after it will be parsed as value
(e.g. `docker run --isolation busybox` would consider `busybox` as value).

This patch removes these lines as they add more confusion than addressing.

[1]: 38ec5d86a3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-02 12:15:08 +01:00
Sebastiaan van Stijn 25f02bc044
vendor: github.com/docker/docker 6f6c3b921180 (master, v28.0.0-dev)
full diff: a72026acbb...6f6c3b9211

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-01 16:24:28 +01:00
Sebastiaan van Stijn 07aca45f5e
Merge pull request #5715 from dmcgowan/fix-container-cp-test
Fix container cp test to separate source and destination
2024-12-27 15:33:39 +01:00
Derek McGowan 8c0cb30515 Fix cp test to separate source and destination
Currently the cp will tar from the same directory it will untar into
simultaneously. There is a race between reading the file and truncating
the file for write, however, the race will not show up with a large
enough buffer on the tar side if buffered before the copy begins.

Also removes the unnecessary deferred removal, the removal is handled by
cleanup and respects the no cleanup env.

Signed-off-by: Derek McGowan <derek@mcg.dev>
2024-12-26 16:30:45 -08:00
Sebastiaan van Stijn 3b49deb8fc
Merge pull request #5711 from thaJeztah/bump_engine_step1
vendor: github.com/docker/docker a72026acbbdf (master, v28.0.0-dev)
2024-12-23 14:05:49 +01:00
Sebastiaan van Stijn c8c47b1dd5
golangci-lint: depguard: prevent uses of pkg/system
We no longer use this package; add a linter rule to prevent
accidentally importing it again.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-23 13:51:16 +01:00
Sebastiaan van Stijn 76ec0ea2eb
vendor: github.com/docker/docker a72026acbbdf (master, v28.0.0-dev)
removes uses of pkg/system

full diff: ad6929339a...a72026acbb

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-23 13:50:59 +01:00
Paweł Gronowski 1a9d19131d
Merge pull request #5710 from thaJeztah/TestRunCopyFromContainerToFilesystem_simplify
TestRunCopyFromContainerToFilesystem: use Tar without options
2024-12-23 12:30:37 +00:00
Sebastiaan van Stijn a8f83d5d99
TestRunCopyFromContainerToFilesystem: use Tar without options
Just a minor cleanup; use archive.Tar as we're not using other
options here.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-23 13:23:39 +01:00
Paweł Gronowski 7e73609bb6
Merge pull request #5709 from thaJeztah/sync_depguard
golangci-lint: sync some depguard settings with moby/moby
2024-12-23 12:07:29 +00:00
Sebastiaan van Stijn 0c04dc05ba
golangci-lint: sync some depguard settings with moby/moby
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-21 15:08:23 +01:00
Sebastiaan van Stijn 45648e8e0e
Merge pull request #5703 from thaJeztah/bump_engine
vendor: github.com/docker/docker ad6929339acd (master, v28.0.0-dev)
2024-12-20 18:48:35 +01:00
Sebastiaan van Stijn cc65127cb0
vendor: github.com/docker/docker ad6929339acd (master, v28.0.0-dev)
full diff: b249c5ebd2...ad6929339a

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-20 17:58:34 +01:00
Sebastiaan van Stijn 46cf6661c9
Merge pull request #5705 from thaJeztah/bump_x_net
vendor: golang.org/x/net v0.33.0
2024-12-20 17:58:02 +01:00
Sebastiaan van Stijn 6f47bce41c
vendor: golang.org/x/net v0.33.0
contains a fix for CVE-2024-45338 / https://go.dev/issue/70906,
but it doesn't affect our codebase:

    govulncheck -show=verbose ./...
    Scanning your code and 1260 packages across 211 dependent modules for known vulnerabilities...
    ...
    Vulnerability #1: GO-2024-3333
        Non-linear parsing of case-insensitive content in golang.org/x/net/html
      More info: https://pkg.go.dev/vuln/GO-2024-3333
      Module: golang.org/x/net
        Found in: golang.org/x/net@v0.32.0
        Fixed in: golang.org/x/net@v0.33.0

    Your code is affected by 0 vulnerabilities.
    This scan also found 0 vulnerabilities in packages you import and 1
    vulnerability in modules you require, but your code doesn't appear to call these
    vulnerabilities.

full diff: https://github.com/golang/net/compare/v0.32.0...v0.33.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-20 17:12:38 +01:00
Sebastiaan van Stijn 2f67b2f3ff
Merge pull request #5684 from thaJeztah/gofumpt_go_version
Makefile: use go1.22 semantics for gofumpt
2024-12-18 13:41:08 +01:00
Paweł Gronowski 3723f0bde7
Merge pull request #5682 from thaJeztah/bump_golangci_lint
update golangci-lint to v1.62.2
2024-12-18 10:23:34 +00:00
Sebastiaan van Stijn ecd162228f
Merge pull request #5695 from thaJeztah/fix_TestEventsFormat
cli/command/system: TestEventsFormat: set cmd.Args to prevent test-failures
2024-12-17 13:02:53 +01:00
Sebastiaan van Stijn 0dd6aa8cc3
Merge pull request #5702 from thaJeztah/bump_x_deps
vendor: update golang.org/x/ dependencies for docker/docker
2024-12-17 13:02:23 +01:00
Sebastiaan van Stijn 83156e6627
vendor: golang.org/x/net v0.32.0
go maintainers annnounced a security release for this module; this patch
already brings it up to the current version in case the security issue
affects us.

full diff: https://github.com/golang/net/compare/v0.31.0...v0.32.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 23:01:20 +01:00
Sebastiaan van Stijn 450f6b9955
vendor: golang.org/x/crypto v0.31.0
update to the latest version of this dependency, which has a fix for a
authorization bypass in the ssh package. We don't use this functionality,
so there's no need to backport this change (other than de-noising false positives).

This is CVE-2024-45337 and Go issue https://go.dev/issue/70779.

full diff: https://github.com/golang/crypto/compare/v0.29.0...v0.31.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 22:59:33 +01:00
Sebastiaan van Stijn b74302eb50
vendor: golang.org/x/text v0.21.0
no changes in vendored code

full diff: https://github.com/golang/text/compare/v0.20.0...v0.21.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 22:58:24 +01:00
Sebastiaan van Stijn cb2e35286c
vendor: golang.org/x/sync v0.10.0
no changes in vendored code

full diff: https://github.com/golang/sync/compare/v0.9.0...v0.10.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 22:57:35 +01:00
Sebastiaan van Stijn e56b665d81
vendor: golang.org/x/sys v0.28.0
full diff: https://github.com/golang/sys/compare/v0.27.0...v0.28.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 22:56:51 +01:00
Sebastiaan van Stijn 8454e012ca
Merge pull request #5697 from thaJeztah/remove_system_isabs
cli/command/container: use local copy of pkg/system.IsAbs
2024-12-16 17:46:27 +01:00
Albin Kerouanton 7dd31686e9
Merge pull request #5696 from thaJeztah/remove_use_of_netfilter_fields
cli/command/system: remove BridgeNfIptables, BridgeNfIp6tables in tests
2024-12-16 16:25:01 +01:00
Sebastiaan van Stijn 1eda498786
cli/command/container: use local copy of pkg/system.IsAbs
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-16 10:22:35 +01:00
Sebastiaan van Stijn ffe0354c2c
cli/command/system: remove BridgeNfIptables, BridgeNfIp6tables in tests
This is a follow-up to 55e404e7a8, which
removed some warnings related to these fields.

These fields in the /info response were used to warn users if netfiltering
was not enabled on the host when the daemon started.  Starting with
[moby@db25b0d], detecting whether netfiltering  is enabled now
[happens when needed][1], making the state that's detected at startup
irrelevant.

These fields will therefore be deprecated in future, but we can start
removing their use in tests.

[moby@db25b0d]: db25b0dcd0
[1]: 944e403502/libnetwork/drivers/bridge/setup_bridgenetfiltering.go (L16-L77)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-14 15:29:33 +01:00
Sebastiaan van Stijn 73ff81b651
cli/command/system: TestEventsFormat: set cmd.Args to prevent test-failures
When running the tests with options set, such as `-update` for updating
"golden" files, this test would pick up test arguments because no arguments
were set to invoke the command;

    go test . -update
    Error: unknown shorthand flag: 'u' in -update
    Usage:
      events [OPTIONS] [flags]

    Flags:
      -f, --filter filter   Filter output based on conditions provided
          --format string   Format output using a custom template:
                            'json':             Print in JSON format
                            'TEMPLATE':         Print output using the given Go template.
                            Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates
      -h, --help            help for events
          --since string    Show all events created since timestamp
          --until string    Stream events until this timestamp

    --- FAIL: TestEventsFormat (0.00s)
        --- FAIL: TestEventsFormat/default (0.00s)
            events_test.go:75: assertion failed: error is not nil: unknown shorthand flag: 'u' in -update
        --- FAIL: TestEventsFormat/json (0.00s)
            events_test.go:75: assertion failed: error is not nil: unknown shorthand flag: 'u' in -update
        --- FAIL: TestEventsFormat/json_template (0.00s)
            events_test.go:75: assertion failed: error is not nil: unknown shorthand flag: 'u' in -update
        --- FAIL: TestEventsFormat/json_action (0.00s)
            events_test.go:75: assertion failed: error is not nil: unknown shorthand flag: 'u' in -update

This patch:

- changes the test to use command-arguments instead of manually setting the
  flag options; this also adds test-coverage for parsing actual command arguments.
- discards stdout/stderr of the command to prevent noise in test output

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-14 13:46:53 +01:00
Sebastiaan van Stijn 91d097e70b
Merge pull request #5683 from thaJeztah/bump_xx
update xx to v1.6.1 for compatibility with alpine 3.21
2024-12-13 14:38:36 +01:00
Sebastiaan van Stijn 5b36e1b34a
Merge pull request #5691 from thaJeztah/remove_netfilter_warnings
cli/command/system: remove netfilter warnings from tests
2024-12-13 13:11:14 +01:00
Sebastiaan van Stijn 55e404e7a8
cli/command/system: remove netfilter warnings from tests
These warnings will no longer be returned by the daemon, so remove
them from the tests as well to make them more representative of
reality.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-13 10:29:01 +01:00
Sebastiaan van Stijn 4c2a184aaf
Merge pull request #5689 from thaJeztah/bump_gomd2man
update go-md2man to v2.0.5
2024-12-13 02:01:07 +01:00
Sebastiaan van Stijn eaa8b5716d
update go-md2man to v2.0.5
full diff: https://github.com/cpuguy83/go-md2man/compare/v2.0.4...v2.0.5

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-13 01:21:51 +01:00
Rob Murray 2080e09905
Merge pull request #5599 from robmry/option_ipv4
Add option --ipv4
2024-12-12 15:10:48 +00:00
Sebastiaan van Stijn b8fd205178
Makefile: use go1.22 semantics for gofumpt
gofumpt defaults to using the go version from go.mod, but as we don't
have one, we need to set it explicitly.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-11 12:16:56 +01:00
Rob Murray 6a2cde6c75 Add option '--ipv4'
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-12-10 15:51:21 +00:00
Rob Murray 5c896c95d0 Docs: emphasise that some options that are for docker0
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-12-10 15:51:21 +00:00
Sebastiaan van Stijn 26526f9970
Merge pull request #5674 from thaJeztah/registry_trimname
registry/client: remove uses of APIEndpoint.TrimHostName
2024-12-10 12:28:12 +01:00
Rob Murray a5353e55da Docs: include --fixed-cidr-v6 and --bip6 docker0 options
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-12-10 09:44:59 +00:00
Sebastiaan van Stijn 1e51ae7af2
update xx to v1.6.1 for compatibility with alpine 3.21
This fixes compatibility with alpine 3.21

- Fix additional possible `xx-cc`/`xx-cargo` compatibility issue with Alpine 3.21
- Support for Alpine 3.21
- Fix `xx-verify` with `file` 5.46+
- Fix possible error taking lock in `xx-apk` in latest Alpine without `coreutils`

full diff: https://github.com/tonistiigi/xx/compare/v1.5.0...v1.6.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-10 10:12:58 +01:00
Sebastiaan van Stijn b39f482874
update golangci-lint to v1.62.2
full diff: https://github.com/golangci/golangci-lint/compare/v1.62.0...v1.62.2
changelog: https://golangci-lint.run/product/changelog/#v1622

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-09 22:36:45 +01:00
Sebastiaan van Stijn 2a5ac8f5ab
vendor: github.com/docker/docker b249c5ebd214 (master, v28.0.0-dev)
full diff: 5d72419486...b249c5ebd2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-09 21:56:05 +01:00
Sebastiaan van Stijn afab765014
registry/client: remove uses of APIEndpoint.TrimHostName
This field was added in 19515a7ad8,
but looks to be always set for endpoints used, so we can trim remote names
unconditionally.

This option was added for possible future expansion, allowing registry-
mirrors to get the full reference of the image (including domain-name),
for them to host a mirror for multiple upstreams on the same registry.

That approach will unlikely be implemented, and containerd has a different
approach for this, where the reference to the original registry is passed
through a query parameter instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-09 21:51:02 +01:00
Sebastiaan van Stijn e554bfef6c
Merge pull request #5662 from laurazard/consistent-attach-check
run: correctly handle only STDIN attached
2024-12-09 18:01:45 +01:00
Sebastiaan van Stijn 619ea8e134
Merge pull request #5673 from thaJeztah/bump_engine
vendor: github.com/docker/docker 5d72419486fe (master, v28.0.0-dev)
2024-12-09 17:43:27 +01:00
Laura Brehm 7dab597e6d
tests: cleanup comment
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-12-09 15:49:21 +00:00
Laura Brehm 30c4637f03
run: don't hang if only attaching STDIN
If STDOUT or STDERR are attached and the container exits, the streams
will be closed by the daemon while the container is exiting, causing
the streamer to return an error
61b02e636d/cli/command/container/hijack.go (L53)
that gets sent
61b02e636d/cli/command/container/run.go (L278)
and received
61b02e636d/cli/command/container/run.go (L225)
on `errCh`.

However, if only STDIN is attached, it's not closed (since this is
attached to the user's TTY) when the container exits, so the streamer
doesn't exit and nothing gets sent on `errCh`, meaning the CLI execution
hangs receiving on `errCh` on L231.

Change the logic to receive on both `errCh` and `statusChan` – this way,
if the container exits, we get notified on `statusChan` (even if only
STDIN is attached), and can cancel the streamer and exit.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-12-09 15:49:20 +00:00
Sebastiaan van Stijn 2eb77f4ede
vendor: github.com/docker/docker 5d72419486fe (master, v28.0.0-dev)
full diff: 87fbd9cd3b...5d72419486

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-09 12:41:45 +01:00
Sebastiaan van Stijn 9dfdffa015
Merge pull request #5672 from thaJeztah/bump_protobuf
vendor: google.golang.org/protobuf v1.35.2
2024-12-09 12:11:31 +01:00
Sebastiaan van Stijn 395716be3f
Merge pull request #5679 from thaJeztah/remove_use_of_nondistributable_artifacts
cli/command/system: don't use "non-distributable-artifacts" fields in tests
2024-12-09 12:05:53 +01:00
Laura Brehm be6ddae56d
Merge pull request #5671 from thaJeztah/bump_x_deps 2024-12-09 11:49:04 +01:00
Sebastiaan van Stijn b51a71148f
cli/command/system: don't use "non-distributable-artifacts" fields in tests
Nondistributable artifacts are deprecated, and no longer used; we'll be
deprecating these fields, so let's already skip their use.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-07 12:24:59 +01:00
Sebastiaan van Stijn f50dea6c40
vendor: google.golang.org/protobuf v1.35.2
full diff: https://github.com/protocolbuffers/protobuf-go/compare/v1.35.1...v1.35.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:45:30 +01:00
Sebastiaan van Stijn 9399483f7a
vendor: golang.org/x/net v0.31.0
full diff: https://github.com/golang/net/compare/v0.30.0...v0.31.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:40:39 +01:00
Sebastiaan van Stijn 6751bcc972
vendor: golang.org/x/crypto v0.29.0
no changes in vendored code

full diff: https://github.com/golang/crypto/compare/v0.28.0...v0.29.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:39:54 +01:00
Sebastiaan van Stijn d41ab7703a
vendor: golang.org/x/term v0.26.0
full diff: https://github.com/golang/term/compare/v0.25.0...v0.26.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:38:55 +01:00
Sebastiaan van Stijn 5972025fae
vendor: golang.org/x/text v0.20.0
no changes in vendored code

full diff: https://github.com/golang/text/compare/v0.19.0...v0.20.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:35:41 +01:00
Sebastiaan van Stijn feb1e2a34c
vendor: golang.org/x/sync v0.9.0
no changes in vendored code

full diff: https://github.com/golang/sync/compare/v0.8.0...v0.9.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:34:43 +01:00
Sebastiaan van Stijn 4c27c895f2
vendor: golang.org/x/sys v0.27.0
full diff: https://github.com/golang/sys/compare/v0.26.0...v0.27.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-06 22:33:47 +01:00
Sebastiaan van Stijn 66dfe6d428
Merge pull request #5664 from akerouanton/gw-priority
run, create, connect: add support for gw-priority
2024-12-06 22:20:57 +01:00
Sebastiaan van Stijn 97010d13f3
Merge pull request #5667 from thaJeztah/login_clean
cli/command/registry: assorted refactor and test changes
2024-12-06 14:42:22 +01:00
Sebastiaan van Stijn e7078bf20c
Merge pull request #5668 from thaJeztah/update_go_1.23.4
update to go1.23.4
2024-12-04 13:14:52 +01:00
Sebastiaan van Stijn a1e57ac72d
update to go1.23.4
go1.23.4 (released 2024-12-03) includes fixes to the compiler, the runtime,
the trace command, and the syscall package. See the Go 1.23.4 milestone on
our issue tracker for details:

- https://github.com/golang/go/issues?q=milestone%3AGo1.23.4+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.23.3...go1.23.4

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-04 10:33:14 +01:00
Sebastiaan van Stijn e398d16c04
cli/command/registry: return status only instead of whole response
Various functions were passing through the API response as a whole, but
effectively only needed it for a status message (if any). Reduce what's
returned to only the message.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-03 19:04:24 +01:00
Sebastiaan van Stijn 297afb2a2b
cli/command/registry: TestLoginWithCredStoreCreds slight refactor
- also check errors that were previously not handled
- use the fakeCLI's buffer instead of creating one manually

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-03 18:42:40 +01:00
Sebastiaan van Stijn 575e373669
cli/command/registry: rename some vars that collided with imports
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-03 18:37:35 +01:00
Albin Kerouanton d4db289eb5 run, create, connect: add support for gw-priority
Signed-off-by: Albin Kerouanton <albinker@gmail.com>
2024-12-03 15:13:08 +01:00
Sebastiaan van Stijn cf89afb32b
cli/command/registry: storeCredentials: accept configfile as arg
This function only needs access to the configfile

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-03 13:00:59 +01:00
Sebastiaan van Stijn b5a00d0b0f
cli/command/registry: loginWithRegistry: use shallower interface
This function only needs the API client, not all of the CLI.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-03 12:50:12 +01:00
Sebastiaan van Stijn 13f0d46411
cli/command/registry: don't return creds on error
Be more explicit on not returning a response if there was an error;
change some non-exported functions to return a pointer, and return
nil instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-12-03 12:48:12 +01:00
Laura Brehm a3d9fc4941
run: cleanup – remove `errCh` nil check
Now, if running in "detached" mode, we early exit at L222.

Similarly, if `attachContainer` errors out, it returns an error that
gets handled on L190.

As such, `errCh` can never be nil on L231. Remove the nil check.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-12-02 14:35:30 +00:00
Laura Brehm 446f36ce58
run: cleanup – move "detached" early exit earlier
Since everything else after the `apiClient.ContainerStart` block is
under an `if attach` conditional, we can move the "detached" early exit
up.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-12-02 14:35:29 +00:00
Laura Brehm 8431298824
run: cleanup – use `attached` where applicable
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-12-02 14:34:28 +00:00
Laura Brehm aee9eebf34
run: return error code when only STDIN attached
During a `docker run`, the CLI has some different behavior/output
depending on whether the run is "detached" or not.

In some cases, the CLI is checking whether either `stdin`, `stdout` or
`stderr` are attached, but in other cases we're only checking `stdout`
and `stderr`, which leads to some inconsistencies:

```
$ docker run -a stdout --rm --name test alpine top
[docker kill test]
exit status 137

$ docker run -a stderr --rm --name test alpine top
[docker kill test]
exit status 137

$ docker run -a stdin --rm --name test alpine top
56820d94a89b96889478241ae68920323332c6d4cf9b51ba9340cba01e9e0565
[docker kill test]
[no exit code]
```

Since we're not checking for whether `stdin` is attached when deciding
whether to early exit without receiving on `statusChan`, the `docker run
-a stdin` is falling into the "detached mode" logic, which simply prints
the container ID and doesn't print/return the exit code.

This patch makes the "attached" checks consistent.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-12-02 14:31:26 +00:00
Laura Brehm 5afa739692
Merge pull request #5660 from thaJeztah/remove_repoinfo_class 2024-12-02 13:51:47 +01:00
Sebastiaan van Stijn ed9fcf31e6
cli/trust: GetNotaryRepository: remove uses of RepositoryInfo.Class
The Class field was added because  Docker Hub registry required a special
scope to be set for pulling plugins;

    HTTP/1.1 401 Unauthorized
    ...
    Www-Authenticate: Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository(plugin):vieux/sshfs:pull",error="insufficient_scope"

This is no longer a requirement, and the field is no longer set.

updates 0ba820ed0b

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-30 14:44:34 +01:00
Sebastiaan van Stijn 61b02e636d
Merge pull request #5607 from robmry/v6only/host_gateway_ip
Docs: host-gateway-ip daemon option IPv4+IPv6
2024-11-29 23:03:48 +01:00
Rob Murray c629eca890 Put --help before --host in the dockerd manpage
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-11-29 17:10:09 +00:00
Rob Murray ea84e8f94b Add --host-gateway to the dockerd manpage
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-11-29 17:10:09 +00:00
Rob Murray cf88ab074a Docs: host-gateway-ip daemon option IPv4+IPv6
The host-gateway-ip daemon option now accepts two addresses, one
IPv4 and one IPv6.

Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-11-29 17:10:09 +00:00
Sebastiaan van Stijn 3be8b8c151
Merge pull request #5651 from vvoland/fix-plugin-paths
cli-plugins: Fix searching inaccessible directories
2024-11-29 15:24:54 +01:00
Sebastiaan van Stijn 083495c847
Merge pull request #5598 from robmry/dockerd-cmd-ref-ipffd
Add --ip-forward-no-drop to dockerd cmdline ref
2024-11-29 13:40:24 +01:00
Sebastiaan van Stijn c0a5c68dc7
Merge pull request #5655 from robmry/dockerd-manpage-bip6
Add --bip6 to the dockerd manpage
2024-11-29 13:39:02 +01:00
Rob Murray ae54c9d97f Add --bip6 to the dockerd manpage
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-11-29 12:23:45 +00:00
Rob Murray 1911dedcf2 Add --ip-filter-forward-drop
Added to the dockerd cmdline ref and its manpage.

Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-11-29 12:17:18 +00:00
Laura Brehm 2369935bdb
Merge pull request #5645 from Benehiko/fix-run-ctx 2024-11-29 12:08:51 +01:00
Sebastiaan van Stijn 41fba28661
Merge pull request #5653 from dvdksn/docs-fix-screwy-dockerd-rendering
docs: fix janky rendering of toc on docs.docker.com
2024-11-28 17:16:10 +01:00
David Karlsson 0f058041c4 docs: fix janky rendering of toc on docs.docker.com
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-11-28 15:01:09 +01:00
Paweł Gronowski fcd94feefb
cli-plugins: Simplify addPluginCandidatesFromDir
The returned error is always nil now, so just remove it.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-11-28 14:33:49 +01:00
Paweł Gronowski 6de3d71ab6
cli-plugins: Fix searching inaccessible directories
Fix a case where one inaccessible plugin search path stops the whole
search and prevents latter paths from being scanned.

Remove a preliminary `Stat` call that verifies whether path is an actual
directory and is accessible.
It's unneeded and doesn't actually check whether the directory can be
listed or not.
`os.ReadDir` will fail in such case anyway, so just attempt to do that
and ignore any encountered error, instead of erroring out the whole
plugin candidate listing.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-11-28 14:17:11 +01:00
Alano Terblanche 30a73ff19c
fix: ctx should cancel image pull on run
This patch fixes the context cancellation
behaviour for the `runContainer` function,
specifically the `createContainer` function
introduced in this commit 991b1303da.

It delays stripping the `cancel` from the context
passed into the `runContainer` function so that
the `createContainer` function can be cancelled
gracefully by a SIGTERM/SIGINT.

This is especially true when the requested image
does not exist and `docker run` needs to `pull`
the image before creating the container.

Although this patch does gracefully cancel
the `runContainer` function it does not address
the root cause. Some functions in the call path
are not context aware, such as `pullImage`.

Future work would still be necessary to ensure
a consistent behaviour in the CLI.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-11-28 09:53:04 +01:00
Sebastiaan van Stijn 682cf57d73
Merge pull request #5597 from robmry/dockerd-cmd-ref-bip6
Add --bip6 to dockerd cmdline ref
2024-11-28 00:08:52 +01:00
Sebastiaan van Stijn bc908a655f
Merge pull request #5650 from laurazard/cleanup-tests-1
tests: cleanup table test names
2024-11-27 18:35:15 +01:00
Laura Brehm 1d4a7ae082
tests: cleanup table test names
There's no need for `case=[xxx]` in table tests, Go does a good job of
formatting the test output and we're just adding the same information
for every test output line.

Previously:
```console
$ go test -count=1 -v -run=TestPromptForConfirmation ./cli/command
=== RUN   TestPromptForConfirmation
=== RUN   TestPromptForConfirmation/case=SIGINT
=== RUN   TestPromptForConfirmation/case=no
=== RUN   TestPromptForConfirmation/case=yes
=== RUN   TestPromptForConfirmation/case=any
=== RUN   TestPromptForConfirmation/case=with_space
=== RUN   TestPromptForConfirmation/case=reader_closed
--- PASS: TestPromptForConfirmation (0.00s)
    --- PASS: TestPromptForConfirmation/case=SIGINT (0.00s)
    --- PASS: TestPromptForConfirmation/case=no (0.00s)
    --- PASS: TestPromptForConfirmation/case=yes (0.00s)
    --- PASS: TestPromptForConfirmation/case=any (0.00s)
    --- PASS: TestPromptForConfirmation/case=with_space (0.00s)
    --- PASS: TestPromptForConfirmation/case=reader_closed (0.00s)
PASS
ok      github.com/docker/cli/cli/command       0.013s
```

After:
```console
go test -count=1 -v -run=TestPromptForConfirmation ./cli/command
=== RUN   TestPromptForConfirmation
=== RUN   TestPromptForConfirmation/SIGINT
=== RUN   TestPromptForConfirmation/no
=== RUN   TestPromptForConfirmation/yes
=== RUN   TestPromptForConfirmation/any
=== RUN   TestPromptForConfirmation/with_space
=== RUN   TestPromptForConfirmation/reader_closed
--- PASS: TestPromptForConfirmation (0.00s)
    --- PASS: TestPromptForConfirmation/SIGINT (0.00s)
    --- PASS: TestPromptForConfirmation/no (0.00s)
    --- PASS: TestPromptForConfirmation/yes (0.00s)
    --- PASS: TestPromptForConfirmation/any (0.00s)
    --- PASS: TestPromptForConfirmation/with_space (0.00s)
    --- PASS: TestPromptForConfirmation/reader_closed (0.00s)
PASS
ok      github.com/docker/cli/cli/command       0.009s
```

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-11-27 16:46:34 +00:00
Alano Terblanche ba1a15433b
Merge pull request #5648 from Benehiko/improve-contribution
chore: update commit guidelines in CONTRIBUTING.md
2024-11-26 13:09:48 +01:00
Alano Terblanche 4a219b1a41
chore: update commit guidelines in CONTRIBUTING.md
The commit guidelines are too vague and offer little guidance on
acceptable commit styles. This patch expands on what is acceptable
with some examples of what a commit is supposed to look like.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
Co-authored-by: Christopher Petito <47751006+krissetto@users.noreply.github.com>
2024-11-26 12:38:28 +01:00
Aleksa Sarai 8d3c0fb6dc tests: migrate to assert.ErrorContains when possible
If we have an error type that we're checking a substring against, we
should really be checking using ErrorContains to indicate the right
semantics to assert.

Mostly done using these transforms:

  find . -type f -name "*_test.go" | \
    xargs gofmt -w -r 'assert.Assert(t, is.ErrorContains(e, s)) -> assert.ErrorContains(t, e, s)'
  find . -type f -name "*_test.go" | \
    xargs gofmt -w -r 'assert.Assert(t, is.Contains(err.Error(), s)) -> assert.ErrorContains(t, err, s)'
  find . -type f -name "*_test.go" | \
    xargs gofmt -w -r 'assert.Check(t, is.Contains(err.Error(), s)) -> assert.Check(t, is.ErrorContains(err, s))'

As well as some small fixups to helpers that were doing
strings.Contains explicitly.

Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
2024-11-22 23:59:21 +11:00
Sebastiaan van Stijn 6c76914532
Merge pull request #5637 from thaJeztah/bump_rosetta
vendor: github.com/tonistiigi/go-rosetta v0.0.0-20220804170347-3f4430f2d346
2024-11-21 17:53:16 +01:00
Sebastiaan van Stijn 7b67057c32
Merge pull request #5636 from thaJeztah/bump_codecov_action
build(deps): bump codecov/codecov-action from 4 to 5
2024-11-21 17:52:41 +01:00
Sebastiaan van Stijn 9ccc462005
Merge pull request #5634 from thaJeztah/bump_mapstructure
vendor: github.com/go-viper/mapstructure/v2 v2.2.1
2024-11-21 17:52:21 +01:00
Sebastiaan van Stijn 35bf069da2
Merge pull request #5633 from thaJeztah/bump_capability
vendor: github.com/moby/sys/capability v0.4.0
2024-11-21 17:51:57 +01:00
Sebastiaan van Stijn 9b72a58d35
Merge pull request #5632 from thaJeztah/bump_golangci_lint
update golangci-lint to v1.62.0
2024-11-21 17:51:22 +01:00
Sebastiaan van Stijn 6aeba15e55
Merge pull request #5630 from thaJeztah/bump_goversioninfo
Dockerfile: bump github.com/josephspurrier/goversioninfo to v1.4.1
2024-11-21 17:50:45 +01:00
Sebastiaan van Stijn a93fb1678a
Merge pull request #5638 from thaJeztah/bump_engine
vendor: github.com/docker/docker e5c2b5e10d68 (master, v28.0.0-dev)
2024-11-21 09:54:53 +01:00
Sebastiaan van Stijn d41b80fafc
vendor: github.com/docker/docker e5c2b5e10d68 (master, v28.0.0-dev)
full diff: 6ac445c42b...e5c2b5e10d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-20 15:54:27 +01:00
Sebastiaan van Stijn 11fbc99939
vendor: github.com/tonistiigi/go-rosetta v0.0.0-20220804170347-3f4430f2d346
full diff: f79598599c...3f4430f2d3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-19 21:51:51 +01:00
dependabot[bot] b0c0cd5e32
build(deps): bump codecov/codecov-action from 4 to 5
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 4 to 5.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codecov/codecov-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-19 13:53:08 +01:00
Sebastiaan van Stijn 81401f37f2
Merge pull request #5625 from Giedriusj1/master
Optimise `docker stats` to not require clearing the whole screen
2024-11-19 12:48:26 +01:00
Sebastiaan van Stijn f6599300ff
vendor: github.com/go-viper/mapstructure/v2 v2.2.1
full diff: https://github.com/go-viper/mapstructure/compare/v2.0.0...v2.2.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-19 11:49:17 +01:00
Sebastiaan van Stijn 446d4138ed
vendor: github.com/moby/sys/capability v0.4.0
full diff: https://github.com/moby/sys/compare/capability/v0.3.0...capability/v0.4.0

Added

* New separate API for ambient ([GetAmbient], [SetAmbient], [ResetAmbient])
  and bound ([GetBound], [DropBound]) capabilities, modelled after libcap.

Fixed

* [Apply] now returns an error if called for non-zero `pid`. Before this change,
  it could silently change some capabilities of the current process, instead of
  the one identified by the `pid`.
* Fixed tests that change capabilities to be run in a separate process.
* Other improvements in tests.

Changed

* Use raw syscalls (which are slightly faster).
* Most tests are now limited to testing the public API of the package.
* Simplify parsing /proc/*pid*/status, add a test case.
* Optimize the number of syscall to set ambient capabilities in Apply
  by clearing them first; add a test case.
* Better documentation for [Apply], [NewFile], [NewFile2], [NewPid], [NewPid2].

Removed

* `.golangci.yml` and `.codespellrc` are no longer part of the package.

<!-- Doc links (please keep sorted). -->
[Apply]: https://pkg.go.dev/github.com/moby/sys/capability#Capabilities.Apply
[DropBound]: https://pkg.go.dev/github.com/moby/sys/capability#DropBound
[GetAmbient]: https://pkg.go.dev/github.com/moby/sys/capability#GetAmbient
[GetBound]: https://pkg.go.dev/github.com/moby/sys/capability#GetBound
[LastCap]: https://pkg.go.dev/github.com/moby/sys/capability#LastCap
[ListKnown]: https://pkg.go.dev/github.com/moby/sys/capability#ListKnown
[ListSupported]: https://pkg.go.dev/github.com/moby/sys/capability#ListSupported
[List]: https://pkg.go.dev/github.com/moby/sys/capability#List
[NewFile2]: https://pkg.go.dev/github.com/moby/sys/capability#NewFile2
[NewFile]: https://pkg.go.dev/github.com/moby/sys/capability#NewFile
[NewPid2]: https://pkg.go.dev/github.com/moby/sys/capability#NewPid2
[NewPid]: https://pkg.go.dev/github.com/moby/sys/capability#NewPid
[ResetAmbient]: https://pkg.go.dev/github.com/moby/sys/capability#ResetAmbient
[SetAmbient]: https://pkg.go.dev/github.com/moby/sys/capability#SetAmbient

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-19 11:37:18 +01:00
Sebastiaan van Stijn 07e5ddd054
update golangci-lint to v1.62.0
full diff: https://github.com/golangci/golangci-lint/compare/v1.61.0...v1.62.0
Changelog: https://golangci-lint.run/product/changelog/#v1620

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-19 11:05:27 +01:00
Sebastiaan van Stijn 93a931920b
Dockerfile: bump github.com/josephspurrier/goversioninfo to v1.4.1
full diff: https://github.com/josephspurrier/goversioninfo/compare/v1.3.0...v1.4.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-19 00:36:15 +01:00
Giedrius Jonikas cb2f95ceee Optimise `docker stats` to not require clearing the whole screen
Instead of clearing the whole screen and then writing the new stats,
we now write the new stats on top of the old text, and then clear
the remaining text.

This is a more efficient way to update the stats, as it avoids the
flickering that happens when the screen is cleared and rewritten.

Signed-off-by: Giedrius Jonikas <giedriusj1@gmail.com>
2024-11-16 15:29:57 +00:00
Sebastiaan van Stijn 9861ce90fd
Merge pull request #5621 from thaJeztah/more_go_build_tags
cli/command/container: fix missing go:build tag
2024-11-15 11:24:51 +01:00
Sebastiaan van Stijn d1d5353269
cli/command/container: fix missing go:build tag
make shell
    make -C ./internal/gocompat/

    GO111MODULE=on go test -v
    # github.com/docker/cli/cli/command/container
    ../../cli/command/container/completion.go:37:28: implicit function instantiation requires go1.18 or later (-lang was set to go1.16; check go.mod)
    ../../cli/command/container/completion.go:82:25: implicit function instantiation requires go1.18 or later (-lang was set to go1.16; check go.mod)
    ../../cli/command/container/completion.go:92:27: implicit function instantiation requires go1.18 or later (-lang was set to go1.16; check go.mod)
    FAIL	gocompat [build failed]

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-15 11:06:20 +01:00
Sebastiaan van Stijn 4adbb18f1c
Merge pull request #5580 from albers/container-completions
Improve Cobra completions for `run` and `create`
2024-11-14 16:58:54 +01:00
Sebastiaan van Stijn e00ed82399
Merge pull request #5615 from thaJeztah/bump_compose_buildx
Dockerfile: update buildx to v0.18.0, compose to v2.30.3
2024-11-14 14:42:05 +01:00
Sebastiaan van Stijn 3dd7621240
Dockerfile: update compose to v2.30.3
Update the compose cli plugin used in the dev-container

full diff: https://github.com/docker/compose/compare/v2.29.7...v2.30.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-14 10:35:52 +01:00
Sebastiaan van Stijn 4242cda826
Dockerfile: update buildx to v0.18.0
Update the buildx cli plugin used in the dev-container

full diff: https://github.com/docker/buildx/compare/0.17.1..0.18.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-14 10:35:25 +01:00
Sebastiaan van Stijn a4228409d2
Merge pull request #5608 from thaJeztah/go1.22_buildtags
update go:build tags to use go1.22
2024-11-12 14:12:00 +01:00
Sebastiaan van Stijn 45f09a1504 builder/remotecontext/git: remove redundant capturing of loop vars (copyloopvar)
builder/remotecontext/git/gitutils_test.go:116:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-12 14:02:11 +01:00
Sebastiaan van Stijn 7c80e4f938
update go:build tags to use go1.22
commit 4a7b04d412 configured golangci-lint
to use go1.23 semantics, which enabled the copyloopvar linter.

go1.22 now creates a copy of variables when assigned in a loop; make sure we
don't have files that may downgrade semantics to go1.21 in case that also means
disabling that feature; https://go.dev/ref/spec#Go_1.22

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-12 12:38:18 +01:00
Harald Albers 06260e68f3 Handle null completions with a default callback
Credits to thaJeztah

Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 4525fe37b4 Add completion for `--volume-driver`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers db0ed1e216 Add completion for `--cgroupns`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 2915749279 Add completion for `--uts`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 3a2503fa43 Add completion for --log-driver` and --log-opt`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 9a9ae231a9 Add completion for `--security-opt`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 5f7c43e5e6 Add completion for `--detach-keys`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 3292afe6e6 Add completion for `--userns`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 5d709a8d9f Add completion for `--ulimit`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers 2d89339b34 Add completion for `--storage-opt`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers ac7bde6f64 Add completion for `--pid`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:55:59 +00:00
Harald Albers e513454244 Add completion for `--link`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:35:34 +00:00
Harald Albers c555327f0b Add completion for `--ipc`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:35:34 +00:00
Harald Albers b598ec8cdb Add completion for `--attach`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:35:34 +00:00
Harald Albers 761d76750c Share the container completions
Signed-off-by: Harald Albers <github@albersweb.de>
2024-11-08 15:35:34 +00:00
Sebastiaan van Stijn 917d2dc837
Merge pull request #5601 from vvoland/update-go
update to go1.23.3
2024-11-07 14:42:18 +01:00
Sebastiaan van Stijn f9497b8a46
Merge pull request #5600 from aevesdocker/desktop-link-fix
docs: change link to desktop docs
2024-11-07 13:56:47 +01:00
Paweł Gronowski 382d4c34a9
update to go1.23.3
- https://github.com/golang/go/issues?q=milestone%3AGo1.23.3+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.23.2...go1.23.3

go1.23.3 (released 2024-11-06) includes fixes to the linker, the
runtime, and the net/http, os, and syscall packages. See the
[Go 1.23.3 milestone](https://github.com/golang/go/issues?q=milestone%3AGo1.23.3+label%3ACherryPickApproved)
for details.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-11-07 13:24:16 +01:00
aevesdocker 1440f9f8cf docs: change link to desktop docs
Signed-off-by: aevesdocker <allie.sadler@docker.com>
2024-11-07 09:38:19 +00:00
Sebastiaan van Stijn 9c01d924fb
Merge pull request #5595 from dvdksn/docs-redis-example-tags
docs: update example redis tags from 3.0.x to 7.4.x
2024-11-06 15:52:12 +01:00
Rob Murray fafaac59fd Add --bip6 to dockerd cmdline ref
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-11-06 14:39:08 +00:00
Sebastiaan van Stijn 8c22315e31
Merge pull request #5596 from laurazard/update-jwt-dep-v4
deps: update `go-jose/go-jose` to `v4`
2024-11-05 15:29:00 +01:00
Laura Brehm 13754f6776
deps: update `go-jose/go-jose` to `v4`
See: https://github.com/go-jose/go-jose

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-11-05 14:12:16 +00:00
Sebastiaan van Stijn 9eb7b52189
Merge pull request #5594 from thaJeztah/fix_golangci_go_version
golangci-lint: set go version to prevent fallback to go1.17, and fix copyloopvar linting issues
2024-11-05 11:24:44 +01:00
David Karlsson 172f340112 docs: update example redis tags from 3.0.x to 7.4.x
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-11-05 11:20:17 +01:00
Sebastiaan van Stijn 750b8ebcdc
Merge pull request #5590 from thaJeztah/bump_engine_28
vendor: github.com/docker/docker 6ac445c42bad (master, v28.0-dev)
2024-11-05 10:21:26 +01:00
Sebastiaan van Stijn 4a7b04d412
golangci-lint: set go version to prevent fallback to go1.17
GolangCI-lint attempts to deduct the Go version to lint for through the
go version specified in go.mod, which we don't have, and therefore it
falls back to go1.17 semantics:

    level=warning msg="[linters_context] copyloopvar: this linter is disabled because the Go version (1.17) of your project is lower than Go 1.22

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:15:36 +01:00
Sebastiaan van Stijn d77760fe53
cli-plugins/manager: remove redundant capturing of loop vars (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    cli-plugins/manager/cobra.go:55:4: The copy of the 'for' variable "p" can be deleted (Go 1.22+) (copyloopvar)
                p := p
                ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:32 +01:00
Sebastiaan van Stijn 32b40deb46
cli/command/service: remove redundant capturing of loop vars (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    cli/command/service/update.go:1061:3: The copy of the 'for' variable "entry" can be deleted (Go 1.22+) (copyloopvar)
            entry := entry
            ^
    cli/command/service/update.go:1089:4: The copy of the 'for' variable "port" can be deleted (Go 1.22+) (copyloopvar)
                port := port
                ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:32 +01:00
Sebastiaan van Stijn 40833fd296
cli/compose/loader: remove redundant capturing of loop vars (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    cli/compose/loader/merge.go:71:3: The copy of the 'for' variable "overrideService" can be deleted (Go 1.22+) (copyloopvar)
            overrideService := overrideService
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:32 +01:00
Sebastiaan van Stijn 78a7e15032
cli/command/container: remove redundant capturing of loop vars (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    cli/command/container/opts.go:765:3: The copy of the 'for' variable "n" can be deleted (Go 1.22+) (copyloopvar)
            n := n
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:32 +01:00
Sebastiaan van Stijn 4a71ce02e6
cli/command/image: remove redundant capturing of loop vars (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    cli/command/image/tree.go:59:4: The copy of the 'for' variable "im" can be deleted (Go 1.22+) (copyloopvar)
                im := im
                ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:31 +01:00
Sebastiaan van Stijn 7d9ea25564
templates: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:31 +01:00
Sebastiaan van Stijn 046ac9714c
service: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:31 +01:00
Sebastiaan van Stijn 762b5a8df3
opts: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:31 +01:00
Sebastiaan van Stijn 417974cdc3
cmd/docker: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:31 +01:00
Sebastiaan van Stijn bf37e26b33
cli/manifest: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:30 +01:00
Sebastiaan van Stijn 6489a777e5
e2e: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:30 +01:00
Sebastiaan van Stijn 20de861134
cli/config: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:30 +01:00
Sebastiaan van Stijn 1448cecba1
cli/compose: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:30 +01:00
Sebastiaan van Stijn 67458f710d
cli/command: remove redundant capturing of loop vars in tests (copyloopvar)
go1.22 and up now produce a unique variable in loops, tehrefore no longer
requiring to capture the variable manually;

    service/logs/parse_logs_test.go:50:3: The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
            tc := tc
            ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-05 10:14:30 +01:00
Sebastiaan van Stijn b45477bffa
Merge pull request #5591 from noahsilas/docs-run-exit-code
docs: Correct `run` exit code 126 description
2024-11-04 17:27:25 +01:00
Noah Silas 0c999fe95b docs: Correct `run` exit code 126 description
The command to run inside the container is `/etc`. The semicolon is a
statement terminator, which ends the command `docker run busybox /etc`,
while `echo $?` prints the exit code of that full docker command.

Having this mistake could confuse someone who thinks that `/etc; echo
$?` is all run inside the container, which wouldn't help the reader
understand the exit code of the `docker run` command itself.

Signed-off-by: Noah Silas <noah@hustle.com>
2024-11-04 00:21:33 +00:00
Sebastiaan van Stijn 5f1311ae8d
vendor: github.com/docker/docker 6ac445c42bad (master, v28.0-dev)
full diff: 36a3bd0904...6ac445c42b

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 14:10:15 +01:00
Sebastiaan van Stijn 10c5a57927
vendor: go.opentelemetry.io/contrib/instrumentation/xxx v0.53.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 14:10:09 +01:00
Sebastiaan van Stijn 5e40d288c7
vendor: go.opentelemetry.io/otel v1.28.0
aligning all related packages to v1.28.0 as well

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 14:08:45 +01:00
Sebastiaan van Stijn 9ba73a1a05
vendor: github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0
full diff: https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.16.0...v2.20.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 14:04:41 +01:00
Sebastiaan van Stijn f3cf1b4213
vendor: go.etcd.io/etcd/raft/v3 v3.5.16
no changes in vendored code

full diff: https://github.com/etcd-io/etcd/compare/v3.5.6...v3.5.16

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:54:25 +01:00
Sebastiaan van Stijn cae19e3928
vendor: github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6
no changes in vendored code

full diff: ced1acdcaa...e8a1dd7889

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:46:38 +01:00
Sebastiaan van Stijn 074d1028b5
vendor: update prometheus dependencies
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:44:05 +01:00
Sebastiaan van Stijn 1dbcce2057
vendor: google.golang.org/grpc v1.67.1
full diff:

- https://github.com/grpc/grpc-go/compare/v1.66.2...v1.67.1
- ef581f9131...5fefd90f89

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:39:15 +01:00
Sebastiaan van Stijn 1bba009944
vendor: google.golang.org/protobuf v1.35.1
full diff: https://github.com/protocolbuffers/protobuf-go/compare/v1.34.1...v1.35.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:31:29 +01:00
Sebastiaan van Stijn e3942d46a0
vendor: github.com/klauspost/compress v1.17.11
full diff: https://github.com/klauspost/compress/compare/v1.17.9...v1.17.11

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:28:47 +01:00
Sebastiaan van Stijn 97ff1b7c0a
vendor: github.com/go-logr/logr v1.4.2
full diff: https://github.com/go-logr/logr/compare/v1.4.1...v1.4.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:25:17 +01:00
Sebastiaan van Stijn 4c85feb4dd
vendor: github.com/cenkalti/backoff/v4 v4.3.0
full diff: https://github.com/cenkalti/backoff/compare/v4.2.1...v4.3.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:23:39 +01:00
Sebastiaan van Stijn 3b48a57b04
vendor: github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161
documentation changes only, no changes in vendored code

full diff: d185dfc1b5...306776ec81

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:20:48 +01:00
Sebastiaan van Stijn 36e6c42977
vendor: golang.org/x/net v0.30.0
full diff: https://github.com/golang/net/compare/v0.29.0...v0.30.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:17:57 +01:00
Sebastiaan van Stijn 84bfa52a6c
vendor: golang.org/x/crypto v0.28.0
no changes in vendored code

full diff: https://github.com/golang/crypto/compare/v0.27.0...v0.28.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:16:26 +01:00
Sebastiaan van Stijn 7a94f592ed
vendor: golang.org/x/text v0.19.0
no changes in vendored code

full diff: https://github.com/golang/text/compare/v0.18.0...v0.19.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:14:25 +01:00
Sebastiaan van Stijn ef197f7314
vendor: golang.org/x/term v0.25.0
no changes in vendored code

full diff: https://github.com/golang/term/compare/v0.24.0...v0.25.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:12:59 +01:00
Sebastiaan van Stijn 02b92c699d
vendor: golang.org/x/sys v0.26.0
full diff: https://github.com/golang/sys/compare/v0.25.0...v0.26.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-11-01 13:11:15 +01:00
Laura Brehm 2995631498
Merge pull request #5586 from Giedriusj1/master 2024-10-31 13:29:09 +00:00
Paweł Gronowski fb103cb982
Merge pull request #5583 from thaJeztah/bump_golang_1.23.2
update to go1.23.2
2024-10-31 13:10:28 +00:00
Sebastiaan van Stijn 42cda38840
update to go1.23.2
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-31 13:04:02 +01:00
Sebastiaan van Stijn 5e51513a8b
Merge pull request #5585 from thaJeztah/bump_golangci_lint
bump golangci-lint to v1.61.0 and cleanup config
2024-10-31 13:03:00 +01:00
Giedrius Jonikas 0b16070ae6 Buffer 'docker stats' text to avoid terminal flickering
This change reduces the flickering of the terminal when
running `docker stats` by buffering the formatted stats
text and printing it in one write.

Should also consume less CPU as we now only have to issue
a single syscall to write the stats text to the terminal.

Signed-off-by: Giedrius Jonikas <giedriusj1@gmail.com>
2024-10-31 11:23:57 +00:00
Sebastiaan van Stijn 9af049c618
bump golangci-lint to v1.61.0
Also updating a linter that was deprecated;

    The linter 'exportloopref' is deprecated (since v1.60.2) due to: Since Go1.22 (loopvar) this linter is no longer relevant. Replaced by copyloopvar.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-30 15:54:47 +01:00
Sebastiaan van Stijn 745629bd55
golangci-lint: update comment, and disable "exclude-dirs-use-default"
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-30 15:52:18 +01:00
Sebastiaan van Stijn 7451339ab0
golangci-lint: move gosec excludes to linters-settings
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-30 15:52:18 +01:00
Sebastiaan van Stijn 020f3a7ad9
golangci-lint: enable G204, add #nosec comments instead
There's only 3 locations where it's hit, so putting #gosec ignore comments
in those locations.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-30 15:52:18 +01:00
Sebastiaan van Stijn aa331e94cc
Merge pull request #5579 from thaJeztah/remove_warning
cli/command/container: parse: remove client-side warning
2024-10-30 10:50:34 +01:00
Sebastiaan van Stijn 1875d9fdcb
Merge pull request #5538 from albers/completion-events--filter
Completion for `events --filter`
2024-10-29 17:58:16 +01:00
Harald Albers e1c5180dba Add tests for completions that call the API
Signed-off-by: Harald Albers <github@albersweb.de>
2024-10-29 15:58:17 +00:00
Harald Albers d4f4cf1418 Add completion for `events --filter`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-10-29 15:58:17 +00:00
Sebastiaan van Stijn 59b90305f7
cli/command/container: parse: remove client-side warning
remove a client-side warning about volume drivers combined with "mounts"
in favor of producing the warning on the daemon side.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-28 23:13:31 +01:00
Sebastiaan van Stijn 32ff200fe6
Merge pull request #5573 from thaJeztah/inspect_add_configs
docker inspect: add support for swarm configs
2024-10-25 17:38:47 +02:00
Sebastiaan van Stijn e9ae9f788b
docker inspect: add support for swarm configs
The docker inspect command did not inspect configs. This patch adds support for
it, and while at it, also sorts the list of objects in runInspect.

Before this patch:

    docker config create myconfig ./codecov.yml
    danpeyh8qzb30vgdj9fr665l1

    docker inspect --format='{{.ID}}' myconfig
    []
    Error: No such object: myconfig

    docker inspect --format='{{.ID}}' --type=config myconfig
    "config" is not a valid value for --type

With this patch:

    docker inspect --format='{{.ID}}' myconfig
    danpeyh8qzb30vgdj9fr665l1

    docker inspect --format='{{.ID}}' --type=config myconfig
    danpeyh8qzb30vgdj9fr665l1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-24 18:32:32 +02:00
Sebastiaan van Stijn 61baf2a3d9
Merge pull request #5570 from thaJeztah/credentials_coverage
cli/config/credentials: add test for save being idempotent
2024-10-22 16:36:58 +02:00
Sebastiaan van Stijn c34b80bc65
Merge pull request #5567 from thaJeztah/config_fix_err
cli/config: improve error when failing to parse config file
2024-10-22 14:05:45 +02:00
Sebastiaan van Stijn ea511f0de2
Merge pull request #5549 from thaJeztah/remove_cli_errors
cli: remove deprecated Errors type
2024-10-22 12:35:42 +02:00
Sebastiaan van Stijn 3c78069240
cli/config/credentials: add test for save being idempotent
Test case for d3f6867e4d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-22 12:22:54 +02:00
Sebastiaan van Stijn 0dd6f7f1b3
cil/config/credentials: remove newStore() test-utility
This function was names slightly confusing, as it returns a fakeStore,
and it didn't do any constructing, so didn't provide value above just
constructing the type.

I'm planning to add more functionality to the fakeStore, but don't want
to maintain a full-fledged constructor for all of that, so let's remove
this utility.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-22 10:58:29 +02:00
Sebastiaan van Stijn 5f4b14950e
cli: remove deprecated Errors type
The Errors type was deprecated in d3bafa5f3e,
which has been included in the 27.4.0 release.

This patch removes the type, as there are no external consumers.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-22 10:43:24 +02:00
Sebastiaan van Stijn 1aab64dd90
Merge pull request #5547 from thaJeztah/plugin_better_error
cli/command/plugins: use errors.Join instead of custom cli.Errors, and deprecate cli.Errors
2024-10-22 10:42:26 +02:00
Sebastiaan van Stijn 0ab0eca8bd
Merge pull request #5550 from thaJeztah/login_minor_refactor
cli/command: PromptUserForCredentials: assorted minor improvements and (linting) fixes
2024-10-21 23:23:06 +02:00
Sebastiaan van Stijn d96f8b7f91
cli/config: improve error when failing to parse config file
The format had a stray colon and space included. While fixing that, also
updating the error message to clarify the error happened while parsing
the file (not so much "loading" it).

Before:

    WARNING: Error loading config file: /root/.docker/config.json: : json: cannot unmarshal bool into Go struct field ConfigFile.features of type string

After:

    WARNING: Error parsing config file (/root/.docker/config.json): json: cannot unmarshal bool into Go struct field ConfigFile.features of type string

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-21 18:26:02 +02:00
Sebastiaan van Stijn abb8e9b78a
Merge pull request #5546 from thaJeztah/hints_coverage
cli/hints: add tests
2024-10-21 18:08:28 +02:00
Laura Brehm 7029147458
Merge pull request #5557 from thaJeztah/minor_linting_issues 2024-10-21 17:00:40 +01:00
Paweł Gronowski d2b87a0a3b
Merge pull request #5553 from thaJeztah/login_idempotent
cli/config/credentials: skip saving config-file if credentials didn't change
2024-10-21 15:23:26 +02:00
Sebastiaan van Stijn 24ee5f228a
Merge pull request #5551 from thaJeztah/fix_ConfigureAuth_deprecation
cli/command: ConfigureAuth: fix deprecation comment
2024-10-21 14:28:43 +02:00
Sebastiaan van Stijn 8b6133a2b7
Merge pull request #5544 from thaJeztah/bump_engine_28
vendor: github.com/docker/docker 36a3bd090489 (master, v28.0-dev)
2024-10-21 13:28:35 +02:00
Sebastiaan van Stijn d3f6867e4d
cli/config/credentials: skip saving config-file if credentials didn't change
Before this change, the config-file was always updated, even if there
were no changes to save. This could cause issues when the config-file
already had credentials set and was read-only for the current user.

For example, on NixOS, this poses a problem because `config.json` is a
symlink to a write-protected file;

    $ readlink ~/.docker/config.json
    /home/username/.config/sops-nix/secrets/ghcr_auth

    $ readlink -f ~/.docker/config.json
    /run/user/1000/secrets.d/28/ghcr_auth

Which causes `docker login` to fail, even if no changes were to be made;

    Error saving credentials: rename /home/derek/.docker/config.json2180380217 /home/username/.config/sops-nix/secrets/ghcr_auth: invalid cross-device link

This patch updates the code to only update the config file if changes
were detected. It there's nothing to save, it skips updating the file,
as well as skips printing the warning about credentials being stored
insecurely.

With this patch applied:

    $ docker login -u yourname
    Password:

    WARNING! Your credentials are stored unencrypted in '/root/.docker/config.json'.
    Configure a credential helper to remove this warning. See
    https://docs.docker.com/go/credential-store/

    Login Succeeded

    $ docker login -u yourname
    Password:
    Login Succeeded

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-21 00:19:52 +02:00
Sebastiaan van Stijn 6b9083776f
cli/command: AddPlatformFlag: suppress unhandled error
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-20 17:51:36 +02:00
Sebastiaan van Stijn fb61156b05
cli/command/registry: fix minor linting issues
- fix camelCase naming of verifyLoginOptions
- suppress unhandled errors that can be ignored

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-20 17:51:12 +02:00
Sebastiaan van Stijn 062eecf14a
Merge pull request #5554 from albers/fix-completion-events-filter-daemon
Fix bash completion for `events --filter daemon=`
2024-10-19 17:55:12 +02:00
Harald Albers 3f7b156c85 Fix bash completion for `events --filter daemon=`
Signed-off-by: Harald Albers <github@albersweb.de>
2024-10-19 15:40:07 +00:00
Sebastiaan van Stijn 4b7a1e4613
cli/command: PromptUserForCredentials: suppress unhandled errors
Keep the linters (and my IDE) happy; these errors should be safe to ignore.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 13:24:19 +02:00
Sebastiaan van Stijn 378a3d7d36
cli/command: PromptUserForCredentials: use consts for all hints
This message resulted in code-lines that were too long; move it to a
const together with the other hint. While at it, also suppress unhandled
error, and touch-up the code-comment.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 13:23:29 +02:00
Sebastiaan van Stijn 54e3685bcd
cli/command: ConfigureAuth: fix deprecation comment
Deprecation comments must have an empty line before them, otherwise tools
and linters may not recognise them. While fixing this, also updated the
reference to PromptUserForCredentials to be a docs-link to make it clickable.

Updates 6e4818e7d6.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 13:05:31 +02:00
Sebastiaan van Stijn 3d8b49523d
cli/command: PromptUserForCredentials: print error on terminal restore fail
If restoring the terminal state fails, "echo" no longer works, which means
that anything the user types is no longer shown. The login itself may already
have succeeded, so we should not fail the command, but it's good to inform
the user that this happened, which may give them a clue why things no longer
work as they expect them to work.

With this patch:

    docker login -u yourname
    Password:
    Error: failed to restore terminal state to echo input: something bad happened

    Login Succeeded

We should consider printing instructions how  to restore this manually (other
than restarting the shell). e.g., 'run stty echo' when in a Linux or macOS shell,
but PowerShell and CMD.exe may need different instructions.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 12:49:44 +02:00
Sebastiaan van Stijn a21a5f4243
cli/command: PromptUserForCredentials: always trim password
we don't support empty passwords; when prompting the user for a password,
we already trim the result, but we didn't do the same for a password that's
passed through stdin or through the `-p` / `--password` flag.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 12:10:46 +02:00
Sebastiaan van Stijn eda78e9cdc
cli/command: PromptUserForCredentials: move trimming where it's used
- move trimming defaultUsername inside the if-branch, as it's the only
  location where the result of the trimmed username is use.
- do the reverse for trimming argUser, because the result of trimming
  argUser is used outside of the if-branch (not just for the condition).
  putting it inside the condition makes it easy to assume the result is
  only used locally.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 12:07:51 +02:00
Sebastiaan van Stijn 581cf36bd4
cli/command: PromptUserForCredentials: move "post" check for empty name
move the "post" check for username being empty inside the branch
that's handling the username, as it's the only branch where username
is mutated after checking if it's empty.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 12:06:49 +02:00
Sebastiaan van Stijn a55cfe5f82
cli/command: PromptUserForCredentials: inline isDefaultRegistry
remove isDefaultRegistry and inline it where it's used; the code-comment
already outlines what we're looking for, so the intermediate var didn't
add much currently.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 11:58:42 +02:00
Sebastiaan van Stijn 3a8485085d
cli/command: PromptUserForCredentials: remove named output variables
This function has multiple conditional branches, which makes it harder
to see at a glance whether authConfig may be partially populated. This
patch instead returns a fresh instance for error returns to prevent any
confusion.

It also removes the named output variables, as they're now no longer used,
and the returned types should already be descriptive enough to understand
what's returned.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 11:46:21 +02:00
Sebastiaan van Stijn d3bafa5f3e
cli: deprecate Errors type
The Errors type is no longer used by the CLI itself, and this custom
"multi-error" implementation had both limitations (empty list not being
`nil`), as well as formatting not being great. All of this making it not
something to recommend, and better handled with Go's stdlib.

As far as I could find, there's no external consumers of this, but let's
deprecate first, and remove in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 10:32:55 +02:00
Sebastiaan van Stijn 71ebbb81ae
cli/command/plugins: use errors.Join instead of custom cli.Errors
This command was using a custom "multi-error" implementation, but it
had some limitations, and the formatting wasn't great.

This patch replaces it with Go's errors.Join.

Before:

    docker plugin remove one two three
    Error response from daemon: plugin "one" not found, Error response from daemon: plugin "two" not found, Error response from daemon: plugin "three" not found

After:

    docker plugin remove one two three
    Error response from daemon: plugin "one" not found
    Error response from daemon: plugin "two" not found
    Error response from daemon: plugin "three" not found

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 10:32:54 +02:00
Sebastiaan van Stijn 87acf77aef
cli/hints: add tests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-19 00:48:16 +02:00
Sebastiaan van Stijn 9b525bc9d1
vendor: github.com/docker/docker 36a3bd090489 (master, v28.0-dev)
full diff: 164cae56ed...36a3bd0904

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-18 17:48:05 +02:00
Sebastiaan van Stijn 8a7c5ae68f
Merge pull request #5542 from thaJeztah/base_completion_tests
cmd/docker: add tests for flag-completions, and refactor
2024-10-18 12:07:02 +02:00
Sebastiaan van Stijn da9e984231
Merge pull request #5541 from thaJeztah/template_coverage
templates: add test for HeaderFunctions
2024-10-18 11:42:00 +02:00
Sebastiaan van Stijn 670f81803f
cmd/docker: add tests for flag-completions, and refactor
Remove the registerCompletionFuncForGlobalFlags for now, as
the error it returned was ignored, so it didn't add much
benefit, other than abstracting things.

Split the underlying completion-functions to separate
functions, and add some basic tests for them.

Remove the completions helper, as it now didn't add much,
and it saved having the dependency on the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-18 11:23:55 +02:00
Paweł Gronowski 38653277af
Merge pull request #5539 from thaJeztah/bump_swarmkit
vendor: github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e
2024-10-18 10:44:41 +02:00
Sebastiaan van Stijn 12dcc6e25c
templates: add test for HeaderFunctions
Before:

    go test -test.coverprofile -
    PASS
    coverage: 65.2% of statements
    ok  	github.com/docker/cli/templates	0.607s

After:

    go test -test.coverprofile -
    PASS
    coverage: 95.7% of statements
    ok  	github.com/docker/cli/templates	0.259s

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-18 10:07:33 +02:00
Sebastiaan van Stijn cbbb917323
vendor: github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e
- add Unwrap error to custom error types
- removes dependency on github.com/rexray/gocsi
- fix CSI plugin load issue

full diff: ea1a7cec35...e8ecf83ee0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-17 23:01:19 +02:00
Paweł Gronowski 3590f946a3
Merge pull request #5535 from dvdksn/fix-image-tag-spec
docs: update prose about image tag/name format
2024-10-17 12:46:46 +02:00
David Karlsson 2c6b80491b docs: update prose about image tag/name format
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-10-17 12:36:32 +02:00
Paweł Gronowski 09e16fc9c6
Merge pull request #5537 from dvdksn/correct_events_limit
docs: corrected the max events returned
2024-10-17 11:26:09 +02:00
Laura Brehm dba4b15d6b
Merge pull request #5534 from thaJeztah/container_testfixes 2024-10-16 22:08:22 +01:00
David Karlsson 50ef0c58c2 docs: corrected the max events returned
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-10-16 12:21:51 +02:00
Sebastiaan van Stijn 35d7b1a7a6
cli/command/container: TestWaitExitOrRemoved use subtests
=== RUN   TestWaitExitOrRemoved
    === RUN   TestWaitExitOrRemoved/normal-container
    === RUN   TestWaitExitOrRemoved/give-me-exit-code-42
    === RUN   TestWaitExitOrRemoved/i-want-a-wait-error
    time="2024-10-13T18:48:14+02:00" level=error msg="Error waiting for container: removal failed"
    === RUN   TestWaitExitOrRemoved/non-existent-container-id
    time="2024-10-13T18:48:14+02:00" level=error msg="error waiting for container: no such container: non-existent-container-id"
    --- PASS: TestWaitExitOrRemoved (0.00s)
        --- PASS: TestWaitExitOrRemoved/normal-container (0.00s)
        --- PASS: TestWaitExitOrRemoved/give-me-exit-code-42 (0.00s)
        --- PASS: TestWaitExitOrRemoved/i-want-a-wait-error (0.00s)
        --- PASS: TestWaitExitOrRemoved/non-existent-container-id (0.00s)
    PASS

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-16 12:03:17 +02:00
Sebastiaan van Stijn 3b38dc67be
cli/command/container: set empty args in tests and discard output
Prevent some tests from failing when running from a pre-compiled
testbinary, and discard output to make the output less noisy.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-16 12:01:25 +02:00
Sebastiaan van Stijn 31eeed7ca4
Merge pull request #5533 from thaJeztah/completions_coverage
cli/command/completion: add more unit-tests
2024-10-14 17:38:02 +02:00
Sebastiaan van Stijn 089448ba6d
Merge pull request #5532 from thaJeztah/update_badges
README: update pkg.go.dev badge, add OpenSSF scorecard
2024-10-14 17:18:23 +02:00
Sebastiaan van Stijn 6ed137f7dd
Merge pull request #5529 from thaJeztah/bump_deps
vendor assorted dependencies in preparation of engine update
2024-10-14 13:29:16 +02:00
Sebastiaan van Stijn e1c472a436
completion: add test for VolumeNames
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 19:08:56 +02:00
Sebastiaan van Stijn 302d73f990
completion: add test for NetworkNames
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 19:08:52 +02:00
Sebastiaan van Stijn ab418a38d8
completion: add test for ImageNames
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 19:08:26 +02:00
Sebastiaan van Stijn f3b4094eb0
completion: add test for ContainerNames
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 19:07:52 +02:00
Sebastiaan van Stijn be197da6b8
completion: add test for NoComplete
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 17:54:40 +02:00
Sebastiaan van Stijn 51713196c9
completion: add test for FromList
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 17:53:19 +02:00
Sebastiaan van Stijn a5ca5b33f1
completion: add test for FileNames
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 17:52:50 +02:00
Sebastiaan van Stijn 8f2e5662e7
completion: add test for EnvVarNames
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 17:48:49 +02:00
Sebastiaan van Stijn b8cddc63ad
completion: ContainerNames: don't panic on nil filter
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-13 17:47:07 +02:00
Sebastiaan van Stijn a58faf7971
README: update pkg.go.dev badge, add OpenSSF scorecard
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 22:12:38 +02:00
Sebastiaan van Stijn b6d27ff60e
vendor: google.golang.org/grpc v1.66.2
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:52:41 +02:00
Sebastiaan van Stijn 200225f530
vendor: google.golang.org/protobuf v1.34.1
full diff: https://github.com/protocolbuffers/protobuf-go/compare/v1.33.0...v1.34.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:49:59 +02:00
Sebastiaan van Stijn 9599251d07
vendor: github.com/cespare/xxhash/v2 v2.3.0
full diff: https://github.com/cespare/xxhash/compare/v2.2.0...v2.3.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:48:45 +02:00
Sebastiaan van Stijn ea8aa2a419
vendor: golang.org/x/net v0.29.0
no changes in vendored code

full diff: https://github.com/golang/net/compare/v0.28.0...v0.29.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:47:34 +02:00
Sebastiaan van Stijn 61867feecf
vendor: golang.org/x/crypto v0.27.0
no changes in vendored code

full diff: https://github.com/golang/crypto/compare/v0.26.0...v0.27.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:46:59 +02:00
Sebastiaan van Stijn 843ae6d7e2
vendor: golang.org/x/term v0.24.0
full diff: https://github.com/golang/term/compare/v0.23.0...v0.24.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:46:04 +02:00
Sebastiaan van Stijn bea4ee6588
vendor: golang.org/x/text v0.18.0
no changes in vendored code

full diff: https://github.com/golang/text/compare/v0.17.0...v0.18.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:43:36 +02:00
Sebastiaan van Stijn a88ee33f71
vendor: golang.org/x/sys v0.25.0
full diff: https://github.com/golang/sys/compare/v0.24.0...v0.25.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-12 21:42:42 +02:00
Sebastiaan van Stijn 21eea1e003
Merge pull request #5527 from albers/completion-container-rm
Improve completion of containers for `docker rm`
2024-10-11 22:35:25 +02:00
Harald Albers 147630a309 Only complete removable containers if --force is not given
Signed-off-by: Harald Albers <github@albersweb.de>
2024-10-10 21:34:38 +00:00
Sebastiaan van Stijn 88f1e99e8e
Merge pull request #5507 from p-rogalski/link-supported-go-duration-strings
docs: Link supported Go duration strings
2024-10-10 18:04:19 +02:00
Sebastiaan van Stijn f483aacd6b
Merge pull request #5331 from vvoland/c8d-saveload-platform
c8d: Add `--platform` flag to history, save and load
2024-10-10 17:33:08 +02:00
Paweł Gronowski d085e2445c
image/history: Add `--platform` flag
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-10 17:00:43 +02:00
Paweł Gronowski b0bb4ba7f2
image/load: Add `--platform`
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-10 16:35:07 +02:00
Paweł Gronowski a20eb45b26
image/save: Add `--platform`
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-10 16:35:03 +02:00
Sebastiaan van Stijn 6a78e9231a
Merge pull request #5524 from Stavrospanakakis/compose-ports-validation
cli/compose: implement the ports validation method
2024-10-10 14:34:09 +02:00
Stavros Panakakis 0319795d4f cli/compose: implement the ports validation method
This commit implements a validation
method for the port mappings.

Also, it removes the ports validation
method from the expose property
since they do not accept the
same type of values.

Signed-off-by: Stavros Panakakis <stavrospanakakis@gmail.com>
2024-10-10 11:50:11 +03:00
Sebastiaan van Stijn 305985c1b1
Merge pull request #5417 from DilepDev/5416-brokenLinks
Update broken links in CONTRIBUTING.md
2024-10-09 00:34:17 +02:00
Sebastiaan van Stijn 2d47c9b222
Merge pull request #5521 from thaJeztah/fix_test_args
cli/command/images: set cmd.Args to prevent test-failures
2024-10-08 20:49:28 +02:00
Sebastiaan van Stijn 839dbbcf27
cli/command/images: set cmd.Args to prevent test-failures
When running tests from my IDE, it compiles the tests before running,
then executes the compiled binary to run the tests. Cobra doesn't like that,
because in that situation os.Args is taken as argument for the command that's
executed. The command that's tested now sees the `test-` flags as arguments
(`-test.v -test.run ..`), which causes various tests to fail ("Command XYZ
does not accept arguments").

    # compile the tests:
    go test -c -o foo.test

    # execute the test:
    ./foo.test -test.v -test.run TestFoo
    === RUN   TestFoo
    Error: "foo" accepts no arguments.

Set arguments to an empty slice to make sure it doesn't inherit arguments
from the test-binary.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-08 20:26:15 +02:00
Sebastiaan van Stijn b64f265d0f
Merge pull request #5520 from thaJeztah/fix_TestNewSaveCommandSuccess
cli/command/image: fix TestNewSaveCommandSuccess to actually test
2024-10-08 19:57:11 +02:00
Sebastiaan van Stijn 19eeb10155
cli/command/image: fix TestNewSaveCommandSuccess to actually test
This test was added in [moby@b2551c6] as part of a larger PR that implemented
unit tests in various packages. In this specific test, it looks like the
`imageSaveFunc` that's defined in the test-table was forgotten to be wired
up, causing all tests to effectively be skipped.

This patch wires up the function so that it's used in the test.

[moby@b2551c6]: b2551c619d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-08 19:41:05 +02:00
Sebastiaan van Stijn 185622986e
Merge pull request #5506 from Stavrospanakakis/cli-container-testing
command: add tests for container kill, commit, and pause
2024-10-08 16:15:26 +02:00
Sebastiaan van Stijn eb53046ad2
Merge pull request #5516 from thaJeztah/complete_platforms
add shell-completion for --platform flags
2024-10-08 15:26:49 +02:00
Sebastiaan van Stijn d42cf96e15
cli/command/image: add shell completion for --platform flags
With this patch, completion is provided for `--platform` flags:

    docker pull --platform<TAB>
    linux           linux/amd64     linux/arm/v5    linux/arm/v7    linux/arm64/v8  linux/riscv64   wasip1          windows
    linux/386       linux/arm       linux/arm/v6    linux/arm64     linux/ppc64le   linux/s390x     wasip1/wasm     windows/amd64

Note that `docker buildx build` (with BuildKit) does not yet provide completion;
it's provided through buildx, and uses a different format (accepting multiple
comma-separated platforms). Interestingly, tab-completion for `docker build`
currently uses completion for non-buildkit, and has some other issues that may
have to be looked into.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-08 13:15:28 +02:00
Sebastiaan van Stijn 8c7f713db6
cli/command/container: add shell completion for --platform flags
With this patch, completion is provided for `--platform` flags:

    docker run --platform<TAB>
    linux           linux/amd64     linux/arm/v5    linux/arm/v7    linux/arm64/v8  linux/riscv64   wasip1          windows
    linux/386       linux/arm       linux/arm/v6    linux/arm64     linux/ppc64le   linux/s390x     wasip1/wasm     windows/amd64

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-08 13:14:45 +02:00
Sebastiaan van Stijn ce1aebcc30
cli/command/completion: add Platforms
Add a utility for completing platform strings.

Platforms offers completion for platform-strings. It provides a non-exhaustive
list of platforms to be used for completion. Platform-strings are based on
[runtime.GOOS] and [runtime.GOARCH], but with (optional) variants added. A
list of recognised os/arch combinations from the Go runtime can be obtained
through "go tool dist list".

Some noteworthy exclusions from this list:

  - arm64 images ("windows/arm64", "windows/arm64/v8") do not yet exist for windows.
  - we don't (yet) include `os-variant` for completion (as can be used for Windows images)
  - we don't (yet) include platforms for which we don't build binaries, such as
    BSD platforms (freebsd, netbsd, openbsd), android, macOS (darwin).
  - we currently exclude architectures that may have unofficial builds,
    but don't have wide adoption (and no support), such as loong64, mipsXXX,
    ppc64 (non-le) to prevent confusion.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-08 13:12:31 +02:00
Sebastiaan van Stijn 55ae7d7113
Merge pull request #5504 from austinvazquez/update-golang-1.22.8
ci: update to go1.22.8
2024-10-07 20:27:44 +02:00
Sebastiaan van Stijn fc7e779c57
Merge pull request #5508 from dvdksn/fix-unless-stopped-desc
docs: fix inaccurate description of --restart=unless-stopped
2024-10-07 16:34:22 +02:00
David Karlsson 2f2b16a966 docs: fix inaccurate description of --restart=unless-stopped
`unless-stopped` containers are not restart after a daemon restart

Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-10-07 13:07:33 +02:00
Paul Rogalski c70b2165a9 docs: Link supported Go duration strings
Signed-off-by: Paul Rogalski <mail@paul-rogalski.de>
2024-10-07 10:37:00 +02:00
Stavros Panakakis 442c38636f command: add tests for container kill, commit, and pause
This commit adds tests for the commands
docker kill, docker commit, and docker
pause. Also, it creates the mock methods
of the docker client ContainerCommit and
ContainerPause so they can
be used in the tests.

For docker kill, it covers the
cases that:
 - the command runs successfully
 - the client returns an error

For docker commit, it covers
the cases that:
 - the command runs successfully
 - the client returns an error

For docker pause, it covers
the cases that:
 - the command runs successfully
 - the client returns an error

Signed-off-by: Stavros Panakakis <stavrospanakakis@gmail.com>
2024-10-06 20:00:49 +03:00
Austin Vazquez a6ab65948e
ci: update to go1.22.8
Signed-off-by: Austin Vazquez <macedonv@amazon.com>
2024-10-04 20:20:16 +00:00
Sebastiaan van Stijn 7908982543
Merge pull request #5467 from Stavrospanakakis/cli-container-tests
command: add tests for container diff and rename
2024-10-04 13:49:32 +02:00
Sebastiaan van Stijn ff3f94a542
Merge pull request #5502 from thaJeztah/separate_kvfile
move parsing key-value files to a separate package
2024-10-04 13:46:08 +02:00
Sebastiaan van Stijn 9025c932b9
Merge pull request #5469 from dvdksn/docs-use-important-callout-legacy-build
docs: use important callout for buildkit vs legacy builder
2024-10-04 13:05:52 +02:00
Nicolas De Loof 9ecfe4f5a7
move parsing key-value files to a separate package
Move the code for parsing key-value files, such as used for
env-files and label-files to a separate package. This allows
other projects (such as compose) to use the same parsing
logic, but provide custom lookup functions for their situation
(which is slightly different).

The new package provides utilities for parsing key-value files
for either a file or an io.Reader. Most tests for EnvFile were
now testing functionality that's already tested in the new package,
so were (re)moved.

Co-authored-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-04 12:27:10 +02:00
Sebastiaan van Stijn 9dee12ff69
Merge pull request #5496 from thaJeztah/parseKeyValueFile_refactor
opts: parseKeyValueFile: cleanup and remove redundant trimming
2024-10-04 12:12:09 +02:00
Sebastiaan van Stijn 76196dbb01
opts: parseKeyValueFile: cleanup and remove redundant trimming
- the function already trimmed leading whitespace from each line before
  parsing. keys with trailing whitespace would be invalidated, and values
  have whitespace preserved, so there's no need to trim whitespace for the
  key.
- if a line is validated (key is valid), we don't need to reconstruct the
  key=value by concatenating, and we can add the line as-is.
- check if the key is empty before checking if it contains whitespace
- touch-up comments
- rename some variables for readability
- slight cleanup to use early returns / early continues to reduce nesting

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-04 11:56:15 +02:00
Sebastiaan van Stijn dac7319f10
Merge pull request #5495 from thaJeztah/opts_remove_ErrBadKey
opts: remove ErrBadKey as it's not used as a sentinel error
2024-10-03 17:52:56 +02:00
Sebastiaan van Stijn 95e221ef4d
opts: remove ErrBadKey as it's not used as a sentinel error
This error was originally introduced `ErrBadEnvVariable` in [moby/moby@500c8ba],
but merely for convenience, and not used as a sentinel error. After the code
was moved from the daemon to the cli repository, it was renamed to be more
generic `ErrBadKey` in commit 2b17f4c8a8.

A search on GitHub shows that there's no consumers using this error as
sentinel error, and it's not used in our own code as such, so it should
be safe to remove this error.

This patch removes the `ErrBadKey` error-type; it also removes the prefix
(`poorly formatted environment:`) to make the error more generic, because
the same function was used both for env-files and label-files.

[moby/moby@500c8ba]: 500c8ba4b6

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-03 17:22:22 +02:00
Sebastiaan van Stijn 7c85db6e1a
Merge pull request #5494 from thaJeztah/opts_test_cleanup
opts: cleanup ParseEnvFile tests
2024-10-03 15:36:50 +02:00
Sebastiaan van Stijn b129660dd3
opts: cleanup ParseEnvFile tests
- Use gotest.tools for assertions
- Check for expected error messages
- Don't check for ErrBadKey errors, as it's not used
  as a sentinel error anywhere.
- Use t.SetEnv() instead of depending on `HOME` being set
- Use t.TempDir() for writing temporary files

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-03 14:08:22 +02:00
Laura Brehm 30e9abbd3f
Merge pull request #5492 from thaJeztah/completion_unit_tests
cli/command/container: add unit tests for completion helpers
2024-10-02 15:52:14 +01:00
Sebastiaan van Stijn d49e72c0ac
cli/command/container: add unit tests for completion helpers
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-02 10:38:25 +02:00
Sebastiaan van Stijn ccb3b44fe3
Merge pull request #5480 from thaJeztah/moby_sys_capability
cli/container: use github.com/moby/sys/capability for completions
2024-10-01 15:08:46 +02:00
Sebastiaan van Stijn 462e08219d
cli/container: use github.com/moby/sys/capability for completions
We used a hard-coded list of capabilities that we copied from containerd,
but the new "capability" package allows use to have a maintained list
of capabilities.

There's likely still some improvements to be made;

First of all, the capability package could provide a function to get the list
of strings.

On the completion-side, we need to consider what format is most convenient;
currently we use the canonical name (uppercase and "CAP_" prefix), however,
tab-completion is case-sensitive by default, so requires the user to type
uppercase letters to filter the list of options.

Bash completion provides a `completion-ignore-case on` option to make completion
case-insensitive (https://askubuntu.com/a/87066), but it looks to be a global
option; the current cobra.CompletionOptions also don't provide this as an option
to be used in the generated completion-script.

Fish completion has `smartcase` (by default?) which matches any case if
all of the input is lowercase.

Zsh does not have a dedicated option, but allows setting matching-rules
(see https://superuser.com/a/1092328).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-01 14:01:02 +02:00
Sebastiaan van Stijn f4fab2c7f3
Merge pull request #5488 from thaJeztah/align_errs
align "conflicting options" errors for consistency
2024-10-01 13:05:55 +02:00
Sebastiaan van Stijn bd96bdaf1b
align "conflicting options" errors for consistency
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-01 12:08:56 +02:00
Sebastiaan van Stijn 3907414549
Merge pull request #5485 from thaJeztah/time_or_timeout
cli/command/container: stop, restart: rename "--time" to "--timeout"
2024-09-30 13:06:29 +02:00
Sebastiaan van Stijn df8b34595b
cli/command/container: stop, restart: rename "--time" to "--timeout"
This renames the `--time` flag as used on `docker stop` and `docker restart`
to `--timeout`,  bringing it in line with other uses for this property,
such as `--stop-timeout` on `docker run`.

The `--time` option is deprecated and hidden, but will be kept for
backward compatibility, as these options existed for a long time.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-30 09:43:54 +02:00
Sebastiaan van Stijn b1ae218f60
Merge pull request #5484 from thaJeztah/stop_restart_flag_descriptions
docs/reference: stop, restart: add flag descriptions
2024-09-27 12:24:24 +02:00
Sebastiaan van Stijn 6075303483
docs/reference: stop, restart: add flag descriptions
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-27 10:18:55 +02:00
Sebastiaan van Stijn c767b9b2da
Merge pull request #5483 from robmry/ip-range-validation
Check that --ip-range is a CIDR address
2024-09-26 22:49:12 +02:00
Rob Murray 8fca0a1f28 Check that --ip-range is a CIDR address
Signed-off-by: Rob Murray <rob.murray@docker.com>
2024-09-26 20:38:33 +01:00
Sebastiaan van Stijn daabb1533e
Merge pull request #5482 from thaJeztah/restart_stop_unit_tests
cli/command/container: add unit tests for container restart and container stop
2024-09-26 20:06:48 +02:00
Sebastiaan van Stijn ac502b5909
cli/command/container: add unit tests for container stop
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-26 18:58:40 +02:00
Sebastiaan van Stijn 16aa994255
cli/command/container: add unit tests for container restart
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-26 18:57:27 +02:00
Sebastiaan van Stijn bae4b67c24
Merge pull request #5481 from dvdksn/fix-container-run-typo
docs: fix a typo in run.md
2024-09-26 15:39:20 +02:00
David Karlsson 54a20ce54c docs: fix a typo in run.md
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-26 15:33:09 +02:00
Laura Brehm 3a3fe840ed
Merge pull request #5428 from thaJeztah/bump_docker_28
vendor: github.com/docker/docker 164cae56ed95 (master, v-next)
2024-09-24 15:53:30 +01:00
Sebastiaan van Stijn b12ac897fb
vendor: github.com/docker/docker 164cae56ed95 (master, v-next)
full diff: 2269acc7a3...164cae56ed

Co-authored-by: Paweł Gronowski <pawel.gronowski@docker.com>
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-24 16:30:30 +02:00
Laura Brehm ff853c42a5
Merge pull request #5454 from thaJeztah/touchup_codeql
gha: codeql: minor touch-ups and fixes
2024-09-24 12:03:11 +01:00
Sebastiaan van Stijn 56d0af783c
Merge pull request #5474 from docker/change_to_inuse
Images Tree: Change 'Used' to 'In Use'
2024-09-24 10:37:17 +02:00
Sebastiaan van Stijn 97a6bf3580
Merge pull request #5473 from rumpl/no-underline
Do not underline image name
2024-09-23 21:02:51 +02:00
Brian Goff df52ddcfcc Images Tree: Change 'Used' to 'In Use'
Signed-off-by: Brian Goff <cpuguy83@gmail.com>
2024-09-23 11:26:42 -07:00
Djordje Lukic 17040890e4
Do not underline image name
Blue text with underline looks too much as a hyperlink I can click on

Signed-off-by: Djordje Lukic <djordje.lukic@docker.com>
2024-09-23 15:36:18 +02:00
Sebastiaan van Stijn 9d478be4a8
Merge pull request #5468 from akerouanton/fix-ps-ipv6
cli/formatter: fix unbracketed IPv6 addrs
2024-09-23 15:31:02 +02:00
Stavros Panakakis 46b360b059 command: add tests for container diff and rename
This commit adds tests for the commands
docker diff and docker rename. Also,
it creates the mock methods of the
docker client ContainerDiff and
ContainerRename so they can
be used in the tests.

For docker diff, it covers the
cases that:
 - the command runs successfully
 - the client returns an error
 - the container id is empty

For docker rename, it covers
the cases that:
 - the command runs successfully
 - the container old name is empty
 - the container new name is empty
 - the client returns an error

Co-authored-by: Laura Brehm <laurabrehm@hey.com>
Signed-off-by: Stavros Panakakis <stavrospanakakis@gmail.com>
2024-09-23 16:17:36 +03:00
Laura Brehm 66977d48e9
Merge pull request #5471 from dvdksn/fix-docker-login-anchorlink
docs: fix anchor link to web-based login section
2024-09-23 14:16:42 +01:00
David Karlsson 465e87afc7 docs: fix anchor link to web-based login section
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-23 13:48:33 +02:00
David Karlsson 8a3d838a19 docs: use important callout for buildkit vs legacy builder
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-23 13:38:33 +02:00
Albin Kerouanton 3e271461e6 cli/formatter: fix unbracketed IPv6 addrs
Commit 964155cd tried to enclose all IPv6 addresses within brackets but
missed some cases. This commit fixes that, and adds a few test cases.

Signed-off-by: Albin Kerouanton <albinker@gmail.com>
2024-09-23 12:17:24 +02:00
Laura Brehm baa7a9f7ad
Merge pull request #5460 from laurazard/master-update-VERSION 2024-09-20 11:48:05 +01:00
Laura Brehm 91c90a9797
Update `VERSION` file to `v27.3.1-dev`
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-09-20 11:41:30 +01:00
Sebastiaan van Stijn 9b4daca9f2
Merge pull request #5459 from thaJeztah/bump_compose
Dockerfile: update compose to v2.29.7
2024-09-20 12:38:14 +02:00
Sebastiaan van Stijn ce26ebc0e9
Dockerfile: update compose to v2.29.7
Update the compose cli plugin used in the dev-container

full diff: https://github.com/docker/compose/compare/v2.29.4...v2.29.7

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-20 12:22:39 +02:00
Sebastiaan van Stijn 48cfe2137c
Merge pull request #5456 from laurazard/fix-defer-mp-shutdown
telemetry: fix early meterprovider shutdown
2024-09-20 02:41:45 +02:00
Laura Brehm 1355d7e9f8
telemetry: fix early meterprovider shutdown
In 4b5a196fee, we changed the CLI global
meter provider shutdown in order to handle any error returned by the
metric export.

Unfortunately, we dropped a `defer` during the fix, which
causes the meter provider to be immediately shutdown after being created
and metrics to not be collected/exporter.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-09-20 01:29:19 +01:00
Sebastiaan van Stijn f468606163
gha: codeql: minor touch-ups and fixes
- remove trailing whitespace
- pin to a versioned ubuntu version
- adjust timeout to be more within expected duration
- remove redundant git checkout, which is no longer needed

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-19 11:09:51 +02:00
Sebastiaan van Stijn a5fb752ecf
Merge pull request #5445 from jsternberg/lowercase-windows-drive
command: change drive to lowercase for wsl path
2024-09-18 12:15:45 +02:00
Laura Brehm 4e64c59d64
Merge pull request #5446 from thaJeztah/codeql_updates
gha: update codeql workflow to go1.22.7
2024-09-18 11:04:32 +01:00
Jonathan A. Sternberg 3472bbc28a
command: change drive to lowercase for wsl path
On Windows, the drive casing doesn't matter outside of WSL. For WSL, the
drives are lowercase. When we're producing a WSL path, lowercase the
drive letter.

Co-authored-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
Co-authored-by: Laura Brehm <laurabrehm@hey.com>

Signed-off-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-09-18 10:59:08 +01:00
Laura Brehm 649e564ee0
Merge pull request #5444 from jsternberg/handle-otel-errors
telemetry: pass otel errors to the otel handler for shutdown and force flush
2024-09-18 10:39:55 +01:00
Sebastiaan van Stijn e1213edcc6
gha: update codeql workflow to go1.22.7
commit d7d56599ca updated this
repository to go1.22, but the codeql action didn't specify a
patch version, and was missed.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-17 21:39:56 +02:00
Jonathan A. Sternberg b1956f5073
telemetry: pass otel errors to the otel handler for shutdown and force flush
Signed-off-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
2024-09-17 10:47:04 -05:00
Sebastiaan van Stijn a4619f3676
Merge pull request #5435 from juliogarciape/docs-fix-container-run
Docs: Fix --rm=false flag in container_run.md
2024-09-16 15:17:06 +02:00
Sebastiaan van Stijn 539a92baca
Merge pull request #5441 from thaJeztah/bump_buildx_compose
Dockerfile: update buildx to v0.17.1, compose to v2.29.4
2024-09-16 15:15:09 +02:00
Sebastiaan van Stijn f7a513cff0
Dockerfile: update compose to v2.29.4
Update the compose cli plugin used in the dev-container

full diff: https://github.com/docker/compose/compare/v2.29.0...v2.29.4

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 15:03:15 +02:00
Sebastiaan van Stijn 42ce06aa5b
Dockerfile: update buildx to v0.17.1
Update the buildx cli plugin used in the dev-container

full diff: https://github.com/docker/buildx/compare/0.16.1...0.17.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 15:01:56 +02:00
Laura Brehm 7b630458bd
Merge pull request #5437 from thaJeztah/remove_deprecated_cors_headers
docs, man: dockerd: remove --api-cors-header (deprecated)
2024-09-16 13:42:01 +01:00
Sebastiaan van Stijn ccc87eb6ab
Merge pull request #5438 from thaJeztah/dockerd_logformat
docs, man: dockerd: add documentation for "--log-format" option
2024-09-16 13:44:19 +02:00
Sebastiaan van Stijn 4f78ffaa03
Merge pull request #5436 from thaJeztah/update_dockerd_docs
docs: add documentation for dockerd --feature flag
2024-09-16 13:43:57 +02:00
Sebastiaan van Stijn baceb4b158
docs: dockerd: add documentation for --log-format option
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 13:23:13 +02:00
Sebastiaan van Stijn a42ca1148d
docs/reference: dockerd: add docs for --feature option
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 13:20:48 +02:00
Sebastiaan van Stijn 9ae514fdc7
man: dockerd: add description for --log-format option
This option was added in a08abec9f8d59eaa44c375900e254384a68c5a31,
as part of Docker v25.0, but did not update the docs and manpage.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 12:46:30 +02:00
Sebastiaan van Stijn 1a0e32099a
docs: dockerd: remove --api-cors-header (deprecated)
Updates 9d9bb19f01

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 12:20:54 +02:00
Sebastiaan van Stijn 9bfd0e1a40
man: remove docs for deprecated --api-cors-header
It was deprecated in 27.0x through 7ea9acc97f4c884ecdaebd06ed0353b28263d118,
and removed in ae96ce866f4b3dc09dc4eab019d7725a63623d94.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 12:15:24 +02:00
Sebastiaan van Stijn a357db0aba
man: dockerd: value is optional for --feature flag
The --feature flag allows the boolean value to be omitted.
If only a name is provided, the default is "true".

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 11:22:21 +02:00
Sebastiaan van Stijn fb056d2ceb
man: fix duplicate word in --feature flag description
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 11:22:15 +02:00
Sebastiaan van Stijn 610f9157f5
man: update dockerd man-page to include --feature flag
commit f13c08246d93dd5aae200d5881a3a374e6cac876 introduced
this flag, but did not yet update the manpage.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-16 11:22:08 +02:00
Julio Cesar Garcia 605c9bf160 docs: Fix --rm=false flag in container_run.md
Signed-off-by: Julio Cesar Garcia <juliogarciamelgarejo@gmail.com>
2024-09-13 18:45:26 -05:00
Sebastiaan van Stijn a18c896928
Merge pull request #5424 from jsternberg/wsl-socket-path
command: check for wsl mount path on windows
2024-09-13 00:33:13 +02:00
Sebastiaan van Stijn b0333da63c
Merge pull request #5427 from thaJeztah/bump_docker_deps
vendor: update various dependencies
2024-09-12 19:07:02 +02:00
Sebastiaan van Stijn dccb8bfa5d
vendor: google.golang.org/grpc v1.62.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:38:40 +02:00
Sebastiaan van Stijn 8cdf90cd93
vendor: tags.cncf.io/container-device-interface v0.8.0
Breaking change: The .ToOCI() functions in the specs-go package have been
removed. This removes the dependency on the OCI runtime specification from
the CDI specification definition itself.

What's Changed

- Add workflow to mark prs and issues as stale
- Remove the ToOCI functions from the specs-go package
- docs: add a pointer to community meetings in our docs.
- Bump spec version to v0.8.0
- Update spec version in README

Full diff: https://github.com/cncf-tags/container-device-interface/compare/v0.7.2...v0.8.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:36:26 +02:00
Sebastiaan van Stijn a5f15bee7a
vendor: golang.org/x/net v0.28.0
full diff: https://github.com/golang/net/compare/v0.25.0...v0.28.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:33:40 +02:00
Sebastiaan van Stijn b93fc39639
vendor: golang.org/x/crypto v0.26.0
full diff: https://github.com/golang/crypto/compare/v0.23.0...v0.26.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:32:05 +02:00
Sebastiaan van Stijn 3a63df265f
vendor: golang.org/x/text v0.17.0
full diff: https://github.com/golang/text/compare/v0.15.0...v0.17.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:31:04 +02:00
Sebastiaan van Stijn c6e5341934
vendor: golang.org/x/term v0.23.0
full diff: https://github.com/golang/term/compare/v0.20.0...v0.23.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:29:52 +02:00
Sebastiaan van Stijn 5f9fe33b6b
vendor: golang.org/x/time v0.6.0
full diff: https://github.com/golang/time/compare/v0.3.0...v0.6.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:26:45 +02:00
Sebastiaan van Stijn 7074e5011f
vendor: golang.org/x/sync v0.8.0
full diff: https://github.com/golang/sync/compare/v0.7.0...v0.8.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:24:38 +02:00
Sebastiaan van Stijn 958fff82f1
vendor: golang.org/x/sys v0.24.0
full diff: https://github.com/golang/sys/compare/v0.22.0...v0.24.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:24:02 +02:00
Sebastiaan van Stijn fb264ffc08
vendor: dario.cat/mergo v1.0.1
- fix: overwriteWithEmptyValue is forced to true when merging an object
  involving maps
- fix: WithoutDereference should respect non-nil struct pointers

full diff: https://github.com/darccio/mergo/compare/v1.0.0...v1.0.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-12 18:18:47 +02:00
Jonathan A. Sternberg 38c3fef1a8
command: check for wsl mount path on windows
This checks for the equivalent WSL mount path on windows. WSL will mount
the windows drives at `/mnt/c` (or whichever drive is being used).

This is done by parsing a UNC path with forward slashes from the unix
socket URL.

Signed-off-by: Jonathan A. Sternberg <jonathan.sternberg@docker.com>
2024-09-12 11:14:43 -05:00
Laura Brehm 986baf22c7
Merge pull request #5425 from zeghong/remove-dup-linter
chore: remove duplicated `govet` linter config
2024-09-11 11:35:50 +01:00
Li Zeghong 5b81f0dcb0 chore: remove duplicated `govet` linter config
Signed-off-by: Li Zeghong <zeghong@hotmail.com>
2024-09-11 17:55:43 +08:00
Sebastiaan van Stijn 6965f40090
Merge pull request #5422 from thaJeztah/info_no_expected_version
info: stop printing "Expected" commits
2024-09-10 19:43:51 +02:00
Sebastiaan van Stijn 88ca4e958f
info: stop printing "Expected" commits
The `Commit` type was introduced in 2790ac68b3,
to assist triaging issues that were reported with an incorrect version of
runc or containerd. At the time, both `runc` and `containerd` were not yet
stable, and had to be built from a specific commit to guarantee compatibility.

We encountered various situations where unexpected (and incompatible) versions
of those binaries were packaged, resulting in hard to trace bug-reports.
For those situations, a "expected" version was set at compile time, to
indicate if the version installed was different from the expected version;

    docker info
    ...
    runc version: a592beb5bc4c4092b1b1bac971afed27687340c5 (expected: 69663f0bd4b60df09991c08812a60108003fa340)

Both `runc` and `containerd` are stable now, and docker 19.03 and up set the
expected version to the actual version since c65f0bd13c
and 23.0 did the same for the `init` binary b585c64e2b,
to prevent the CLI from reporting "unexpected version".

In short; the `Expected` fields no longer serves a real purpose, so we should
no longer print it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-10 13:49:12 +02:00
Sebastiaan van Stijn a464a63d33
Merge pull request #5420 from laurazard/fix-panic-volume-update
volume/update: require 1 argument/fix panic
2024-09-09 20:46:30 +02:00
Laura Brehm daea277ee8
volume/update: require 1 argument/fix panic
This command was declaring that it requires at least 1 argument, when it
needs exactly 1 argument. This was causing the CLI to panic when the
command was invoked with no argument:

`docker volume update`

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-09-09 13:40:03 +01:00
Alano Terblanche 6372ec9c75
Merge pull request #5415 from lentil32/master
fix: docstring for cli/command: `ContainerFormat.CreatedAt`
2024-09-09 12:19:53 +02:00
Sebastiaan van Stijn 21ee2685e3
Merge pull request #5403 from dvdksn/docs-update-titles
docs: rename plugins index file and add linkTitle
2024-09-09 11:04:09 +02:00
David Karlsson 0fcaffb7e4 chore: fix style/lint issues in deprecated.md
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-09 10:53:38 +02:00
Alano Terblanche 2230089371
Merge pull request #5381 from Benehiko/lf-exclude-binary
fix: gitattributes enforcing line endings
2024-09-09 08:51:54 +02:00
Dilep Dev 45d55961d0
Fix broken links in CONTRIBUTING.md
Signed-off-by: Dilep Dev <34891655+DilepDev@users.noreply.github.com>
2024-09-08 23:08:14 +05:30
lentil32 0b9d58245a
cli/command: fix docstring for ContainerFormat.CreatedAt
Signed-off-by: lentil32 <lentil32@icloud.com>
2024-09-08 15:47:21 +09:00
Sebastiaan van Stijn 6b741602c8
Merge pull request #5410 from vvoland/update-go
update to go1.22.7
2024-09-06 10:27:26 +02:00
Alano Terblanche 4a6ab2b37d
fix: binary file line endings
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-09-06 10:23:23 +02:00
Paweł Gronowski 3bf39d25a0
update to go1.22.7
- https://github.com/golang/go/issues?q=milestone%3AGo1.22.7+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.22.6...go1.22.7

These minor releases include 3 security fixes following the security policy:

- go/parser: stack exhaustion in all Parse* functions

    Calling any of the Parse functions on Go source code which contains deeply nested literals can cause a panic due to stack exhaustion.

    This is CVE-2024-34155 and Go issue https://go.dev/issue/69138.

- encoding/gob: stack exhaustion in Decoder.Decode

    Calling Decoder.Decode on a message which contains deeply nested structures can cause a panic due to stack exhaustion.

    This is a follow-up to CVE-2022-30635.

    Thanks to Md Sakib Anwar of The Ohio State University (anwar.40@osu.edu) for reporting this issue.

    This is CVE-2024-34156 and Go issue https://go.dev/issue/69139.

- go/build/constraint: stack exhaustion in Parse

    Calling Parse on a "// +build" build tag line with deeply nested expressions can cause a panic due to stack exhaustion.

    This is CVE-2024-34158 and Go issue https://go.dev/issue/69141.

View the release notes for more information:
https://go.dev/doc/devel/release#go1.23.1

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-09-05 17:51:27 +02:00
Laura Brehm 2b6d2d98d8
Merge pull request #5407 from thaJeztah/mod_tidy
vendor.mod: put github.com/pkg/browser in the right group
2024-09-05 13:47:37 +01:00
Sebastiaan van Stijn 1b8180a405
vendor.mod: put github.com/pkg/browser in the right group
commit fcfdd7b91f introduced github.com/pkg/browser
as a direct dependency, but it ended up in the group for indirect dependencies.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-05 14:36:51 +02:00
David Karlsson 5ca40e0a35 docs: add front matter title to deprecated.md
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-04 13:48:37 +02:00
David Karlsson 071f6f9391 docs: rename plugins index file and add linkTitle
We publish this page on docs.docker.com, and hugo expects index pages
for sections to be named _index.md. We currently rename the page when we
mount it to the docs repo but might as well change the filename in the
source.

Also adds a linkTitle to the page, which is a shorter title that will be
used in the sidebar navigation and breadcrumbs.

Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-04 13:48:37 +02:00
Sebastiaan van Stijn f75abad8a1
Merge pull request #5401 from laurazard/login-non-tty-standardize
login: handle non-tty scenario consistently
2024-09-03 16:36:14 +02:00
Laura Brehm bbb6e7643d
login: handle non-tty scenario consistently
Running `docker login` in a non-interactive environment sometimes errors
out if no username/pwd is provided. This handling is somewhat
inconsistent – this commit addresses that.

Before:
| `--username` | `--password` | Result                                                             |
|:------------:|:------------:| ------------------------------------------------------------------ |
|            |            |                                                                  |
|            |            | `Error: Cannot perform an interactive login from a non TTY device` |
|            |            | `Error: Cannot perform an interactive login from a non TTY device` |
|            |            | hangs                                                              |

After:
| `--username` | `--password` | Result                                                             |
|:------------:|:------------:| ------------------------------------------------------------------ |
|            |            |                                                                  |
|            |            | `Error: Cannot perform an interactive login from a non TTY device` |
|            |            | `Error: Cannot perform an interactive login from a non TTY device` |
|            |            | `Error: Cannot perform an interactive login from a non TTY device` |

It's worth calling out a separate scenario – if there are previous,
valid credentials, then running `docker login` with no username or
password provided will use the previously stored credentials, and not
error out.

```console
cat ~/.docker/config.json
{
        "auths": {
                "https://index.docker.io/v1/": {
                        "auth": "xxxxxxxxxxx"
                }
        }
}
⭑ docker login 0>/dev/null
Authenticating with existing credentials...

Login Succeeded
```

This commit also applies the same non-interactive handling logic to the
new web-based login flow, which means that now, if there are no prior
credentials stored and a user runs `docker login`, instead of initiating
the new web-based login flow, an error is returned.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-09-03 14:26:11 +01:00
Sebastiaan van Stijn 2dd127a1ff
Merge pull request #5387 from thaJeztah/update_go_1.22
update to go1.22.6
2024-09-03 13:25:16 +02:00
Sebastiaan van Stijn 51f320ff62
Merge pull request #5376 from laurazard/fix-oauth-login-timer
oauth/api: drain timer channel on each iteration
2024-09-03 13:14:54 +02:00
Laura Brehm 60d0450287
oauth/api: drain timer channel on each iteration
Previously, if while polling for oauth device-code login results a user
suspended the process (such as with CTRL-Z) and then restored it with
`fg`, an error might occur in the form of:

```
failed waiting for authentication: You are polling faster than the specified interval of 5 seconds.
```

This is due to our use of a `time.Ticker` here - if no receiver drains
the ticker channel (and timers/tickers use a buffered channel behind the
scenes), more than one tick will pile up, causing the program to "tick"
twice, in fast succession, after it is resumed.

The new implementation replaces the `time.Ticker` with a `time.Timer`
(`time.Ticker` is just a nice wrapper) and introduces a helper function
`resetTimer` to ensure that before every `select`, the timer is stopped
and it's channel is drained.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-09-03 11:31:03 +01:00
Sebastiaan van Stijn d7d56599ca
update to go1.22.6
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-03 12:29:03 +02:00
Sebastiaan van Stijn 623af469bb
Merge pull request #5393 from thaJeztah/fix_plugins_CGO_ENABLED
scripts/build/plugins: don't override CGO_ENABLED set by .variables
2024-09-03 12:28:21 +02:00
Sebastiaan van Stijn e3676d233e
Merge pull request #5386 from dvdksn/docker-login-docs-touchup
docs: update docker login reference
2024-09-03 12:15:08 +02:00
Sebastiaan van Stijn 9e29967960
scripts/build/plugins: don't override CGO_ENABLED set by .variables
The `.variables` sets `CGO_ENABLED=1` on arm; b0c41b78d8/scripts/build/.variables (L57-L68)
And if enabled, it sets `-buildmode=pie`; b0c41b78d8/scripts/build/.variables (L79-L88)

But that looks to be conflicting with the hardcoded `CGO_ENABLED=0` in
this script, which causes the build to fail on go1.22;

    > [build-plugins 1/1] RUN --mount=ro --mount=type=cache,target=/root/.cache     xx-go --wrap &&     TARGET=/out ./scripts/build/plugins e2e/cli-plugins/plugins/*:
    0.127 Building static docker-helloworld
    0.127 + CGO_ENABLED=0
    0.127 + GO111MODULE=auto
    0.127 + go build -o /out/plugins-linux-arm/docker-helloworld -tags ' osusergo' -ldflags ' -X "github.com/docker/cli/cli/version.GitCommit=5c123b1" -X "github.com/docker/cli/cli/version.BuildTime=2024-09-02T13:52:17Z" -X "github.com/docker/cli/cli/version.Version=pr-5387" -extldflags -static' -buildmode=pie github.com/docker/cli/cli-plugins/examples/helloworld
    0.135 -buildmode=pie requires external (cgo) linking, but cgo is not enabled

This patch sets the CGO_ENABLED variable before sourcing `.variables`,
so that other variables which are conditionally set are handled correctly.

Before this PR:

    #18 [build-plugins 1/1] RUN --mount=ro --mount=type=cache,target=/root/.cache     xx-go --wrap &&     TARGET=/out ./scripts/build/plugins e2e/cli-plugins/plugins/*
    #18 0.123 Building static docker-helloworld
    #18 0.124 + CGO_ENABLED=0
    #18 0.124 + GO111MODULE=auto
    #18 0.124 + go build -o /out/plugins-linux-arm/docker-helloworld -tags ' osusergo' -ldflags ' -X "github.com/docker/cli/cli/version.GitCommit=c8c402e" -X "github.com/docker/cli/cli/version.BuildTime=2024-09-03T08:28:25Z" -X "github.com/docker/cli/cli/version.Version=pr-5381" -extldflags -static' -buildmode=pie github.com/docker/cli/cli-plugins/examples/helloworld
    ....

With this PR:

    #18 [build-plugins 1/1] RUN --mount=ro --mount=type=cache,target=/root/.cache     xx-go --wrap &&     TARGET=/out ./scripts/build/plugins e2e/cli-plugins/plugins/*
    #18 0.110 Building static docker-helloworld
    #18 0.110 + GO111MODULE=auto
    #18 0.110 + go build -o /out/plugins-linux-arm/docker-helloworld -tags '' -ldflags ' -X "github.com/docker/cli/cli/version.GitCommit=050d9d6" -X "github.com/docker/cli/cli/version.BuildTime=2024-09-03T09:19:05Z" -X "github.com/docker/cli/cli/version.Version=pr-5387"' github.com/docker/cli/cli-plugins/examples/helloworld
    ....

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-03 11:49:43 +02:00
David Karlsson 81744d7aa8 copynit: s/WEB BASED/WEB-BASED/
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-03 11:39:43 +02:00
David Karlsson 2f206fff3c docs: update docker login reference
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-09-03 11:38:05 +02:00
Paweł Gronowski 092b5f0fcb
Merge pull request #5389 from thaJeztah/bump_xx
Dockerfile: update xx to v1.5.0
2024-09-02 18:55:05 +00:00
Sebastiaan van Stijn 1e6cbbc3f1
Dockerfile: update xx to v1.5.0
full diff: https://github.com/tonistiigi/xx/compare/v1.4.0...v1.5.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-09-02 16:48:29 +02:00
Sebastiaan van Stijn b0c41b78d8
Merge pull request #5383 from laurazard/convert-registry-to-hostname
login: use normalized hostname when storing
2024-09-02 11:43:07 +02:00
Laura Brehm e532eead91
login: use normalized hostname when storing
Normalization/converting the registry address to just a hostname happens
inside of `command.GetDefaultAuthConfig`. Use this value for the rest of
the login flow/storage.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-30 15:43:20 +01:00
Sebastiaan van Stijn 6273e65cee
Merge pull request #5379 from laurazard/dont-normalize-registry-1
Revert "login: normalize `registry-1.docker.io`"
2024-08-29 13:33:12 +02:00
Laura Brehm dab9674db9
Revert "login: normalize `registry-1.docker.io`"
This reverts commit e6624676e0.

Since e6624676e0, during login, we started
normalizing `registry-1.docker.io` to `index.docker.io`. This means that
if a user logs in with `docker login -u [username]
registry-1.docker.io`, the user's credentials get stored in
credhelpers/config.json under `https://index.docker.io/v1/`.

However, while the registry code normalizes an image reference without
registry (`docker pull alpine:latest`) and image references explicitly for
`index.docker.io` (`docker pull index.docker.io/library/alpine:latest`)
to the official index server (`https://index.docker.io/v1/`), and
fetches credentials for that auth key, it does not normalize
`registry-1.docker.io`, which means pulling explicitly from there
(`docker pull registry-1.docker.io/alpine:latest`) will not use
credentials stored under `https://index.docker.io/v1/`.

As such, until changes are made to the registry/pull/push code to
normalize `registry-1.docker.io` to `https://index.docker.io/v1/`, we
should not normalize this during login.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-29 12:16:05 +01:00
Paweł Gronowski 3826f5ad73
Merge pull request #5370 from thaJeztah/fix_linting_issues
Fix linting issues in preparation of Go and GolangCI-lint update
2024-08-26 14:38:07 +02:00
Sebastiaan van Stijn c4a55df7c0
cli: rename args that collided with builtins (predeclard)
cli/required.go:33:22: param min has same name as predeclared identifier (predeclared)
    func RequiresMinArgs(min int) cobra.PositionalArgs {
                         ^
    cli/required.go:50:22: param max has same name as predeclared identifier (predeclared)
    func RequiresMaxArgs(max int) cobra.PositionalArgs {
                         ^
    cli/required.go:67:24: param min has same name as predeclared identifier (predeclared)
    func RequiresRangeArgs(min int, max int) cobra.PositionalArgs {
                           ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-26 13:55:28 +02:00
Sebastiaan van Stijn 9c87891278
e2e/global: fix n-constant format string in call (govet)
e2e/global/cli_test.go:217:28: printf: non-constant format string in call to gotest.tools/v3/poll.Continue (govet)
                            return poll.Continue(err.Error())
                                                 ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-26 13:54:05 +02:00
Sebastiaan van Stijn f101f07a7b
cli/command: fix n-constant format string in call (govet)
cli/command/utils.go:225:29: printf: non-constant format string in call to github.com/pkg/errors.Wrapf (govet)
                return errors.Wrapf(err, fmt.Sprintf("invalid output path: %q must be a directory or a regular file", path))
                                         ^
    cli/command/manifest/cmd.go:21:33: printf: non-constant format string in call to fmt.Fprintf (govet)
                fmt.Fprintf(dockerCli.Err(), "\n"+cmd.UsageString())
                                             ^
    cli/command/service/remove.go:45:24: printf: non-constant format string in call to github.com/pkg/errors.Errorf (govet)
            return errors.Errorf(strings.Join(errs, "\n"))
                                 ^
    cli/command/service/scale.go:93:23: printf: non-constant format string in call to github.com/pkg/errors.Errorf (govet)
        return errors.Errorf(strings.Join(errs, "\n"))
                             ^
    cli/command/stack/swarm/remove.go:74:24: printf: non-constant format string in call to github.com/pkg/errors.Errorf (govet)
            return errors.Errorf(strings.Join(errs, "\n"))
                                 ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-26 13:52:49 +02:00
Sebastiaan van Stijn cc1d7b7ac9
cli/command/system: remove redundant nil-check (gosimple)
cli/command/system/info.go:375:5: S1009: should omit nil check; len() for []github.com/docker/docker/api/types/system.NetworkAddressPool is defined as zero (gosimple)
        if info.DefaultAddressPools != nil && len(info.DefaultAddressPools) > 0 {
           ^

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-26 13:44:42 +02:00
David Karlsson 436080b887
Merge pull request #5360 from dvdksn/update-apireference-link
chore: update link to docker engine api reference
2024-08-22 15:17:45 +02:00
David Karlsson 35626bae8a
Merge pull request #5350 from dvdksn/docs-alerts-syntax
docs: use gh alert syntax for callouts
2024-08-21 11:39:45 +02:00
Sebastiaan van Stijn d47c36debb
Merge pull request #5363 from akerouanton/fix-ps-pbs
cli/formatter: bracket IPv6 addrs prepended to ports
2024-08-20 17:51:14 +02:00
Albin Kerouanton 964155cd27 cli/formatter: bracket IPv6 addrs prepended to ports
On `docker ps`, port bindings with an IPv6 HostIP should have their
addresses put into brackets when joining them to their ports.

RFC 3986 (Section 3.2.2) stipulates that IPv6 addresses should be
enclosed within square brackets. This RFC is only about URIs. However,
doing so here helps user identifier what's part of the IP address and
what's the port. It also makes it easier to copy/paste that
'[addr]:port' into other software (including browsers).

Signed-off-by: Albin Kerouanton <albinker@gmail.com>
2024-08-20 17:32:27 +02:00
Laura Brehm 986b077a53
Merge pull request #5361 from laurazard/add-oauth-login-escape-hatch
login: add oauth escape hatch
2024-08-20 12:31:07 +01:00
Laura Brehm a327476f7f
login: add e2e tests for oauth + escape hatch
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-20 11:49:04 +01:00
David Karlsson c974a83391 chore: update link to docker engine api reference
Engine API reference page is moving to /reference/api/engine

Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-08-20 12:35:04 +02:00
Laura Brehm 846ecf59ff
login: add oauth escape hatch
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-20 11:16:55 +01:00
David Karlsson 0be9e2faaa
Merge pull request #5347 from dvdksn/update-build-context-link
docs: update link to moved build context doc
2024-08-19 13:13:31 +02:00
Laura Brehm b06db58d8d
Merge pull request #5356 from vvoland/list-tree-gd-spacing
list/tree: No extra spacing for graphdriver
2024-08-19 11:46:07 +01:00
Paweł Gronowski 7b91647943
list/tree: No extra spacing for graphdriver
Don't output the extra spacing around the images when none of the
top-level image entries has any children.

This makes the list look better when ran against the graphdrivers image
store.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-19 12:09:37 +02:00
Paweł Gronowski 8675f4c177
Merge pull request #5352 from vvoland/c8d-multiplatform-list-2
list/tree: Print <untagged> as dangling image name
2024-08-16 16:56:08 +02:00
Paweł Gronowski 351249dce9
list/tree: Print <untagged> as dangling image name
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 16:36:33 +02:00
Paweł Gronowski 6979ab073c
list/tree: Fix some escape codes included in nonTTY
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 16:35:46 +02:00
Laura Brehm cab8a2e830
Merge pull request #4982 from vvoland/c8d-multiplatform-list
image/list: Add `--tree` flag
2024-08-16 14:27:15 +01:00
Paweł Gronowski a9b78da546
list/tree: Add spacing before the content and first image
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:10:00 +02:00
Paweł Gronowski 0242a1e3c6
list/tree: Capitalize column headers
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:09:59 +02:00
Paweł Gronowski d417d06682
list/tree: Add an experimental warning
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:09:57 +02:00
Paweł Gronowski b1a08f7841
list/tree: Sort by created date
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:09:55 +02:00
Paweł Gronowski 18ab78882c
list/tree: Align number right, text left
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:09:54 +02:00
Paweł Gronowski ea8aafcd9e
cli/tree: Add `Content size` column
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:09:52 +02:00
Paweł Gronowski be11b74ee9
image/list: Add `--tree` flag
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-16 15:09:51 +02:00
David Karlsson f1befabe9f docs: use gh alert syntax for callouts
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-08-16 11:02:10 +02:00
Sebastiaan van Stijn bbce5a0afa
Merge pull request #5344 from laurazard/auth-device-flow-pat
auth: add support for oauth device-code login
2024-08-15 09:29:45 +02:00
Laura Brehm c3fe7bc336
fallback to regular login if oauth login fails to start
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-14 19:48:09 +01:00
Laura Brehm 5eb3275c28
filestore: don't print warning multiple times
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-14 19:48:08 +01:00
Laura Brehm e6624676e0
login: normalize `registry-1.docker.io`
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-14 19:48:07 +01:00
Laura Brehm 6e4818e7d6
Refactor `cli/command/registry`
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-14 19:48:05 +01:00
Laura Brehm fcfdd7b91f
auth: add support for oauth device-code login
This commit adds support for the oauth [device-code](https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow)
login flow when authenticating against the official registry.

This is achieved by adding `cli/internal/oauth`, which contains code to manage
interacting with the Docker OAuth tenant (`login.docker.com`), including launching
the device-code flow, refreshing access using the refresh-token, and logging out.

The `OAuthManager` introduced here is also made available through the `command.Cli`
interface method `OAuthManager()`.

In order to maintain compatibility with any clients manually accessing
the credentials through `~/.docker/config.json` or via credential
helpers, the added `OAuthManager` uses the retrieved access token to
automatically generate a PAT with Hub, and store that in the
credentials.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-14 19:48:04 +01:00
David Karlsson 2dd4eb06ae docs: update link to moved build context doc
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-08-13 11:48:29 +02:00
Sebastiaan van Stijn 35666cf7cb
Merge pull request #5345 from thaJeztah/connhelper_cleanups
cli/connhelper: getConnectionHelper: move ssh-option funcs out of closure
2024-08-13 11:38:44 +02:00
Sebastiaan van Stijn 0fd3fb0840
cli/connhelper: getConnectionHelper: move ssh-option funcs out of closure
The addSSHTimeout and disablePseudoTerminalAllocation were added in commits
a5ebe2282a and f3c2c26b10,
and called inside the Dialer function, which means they're called every
time the Dialer is called. Given that the sshFlags slice is not mutated
by the Dialer, we can call these functions once.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-12 17:28:32 +02:00
Sebastiaan van Stijn 1a7b7dd7dd
Merge pull request #5320 from trajano/patch-1
disable pseudoterminal creation
2024-08-12 16:59:47 +02:00
Archimedes Trajano f3c2c26b10
disable pseudoterminal creation
avoided the join, also did manual iteration

added test, also added reflect for the DeepEqual comparison

Signed-off-by: Archimedes Trajano <developer@trajano.net>
2024-08-12 16:53:49 +02:00
David Karlsson 211a5403b3
Merge pull request #5342 from dvdksn/docs-update-internal-links
docs: update internal links after refactor
2024-08-12 10:10:05 +02:00
David Karlsson d4a362aa1c docs: update internal links after refactor
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-08-11 16:58:08 +02:00
Sebastiaan van Stijn 471862b122
Merge pull request #5323 from jongwu/fix_bps_limit
run: fix GetList return empty issue for throttledevice
2024-08-09 19:46:23 +02:00
David Karlsson fc3e949a66
Merge pull request #5338 from dvdksn/fix-proxy-doclink
docs: fix link to http proxy document
2024-08-09 19:11:04 +02:00
David Karlsson 78a8fba2cc docs: fix link to http proxy document
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-08-09 18:19:58 +02:00
Paweł Gronowski c537fb9f48
Merge pull request #5332 from thaJeztah/bump_engine
vendor: github.com/docker/docker 2269acc7a31d (master, v-next)
2024-08-09 09:45:24 +02:00
Sebastiaan van Stijn 6440816c7c
vendor: github.com/docker/docker 2269acc7a31d (master, v-next)
removes (indirect) dependencie on the moby/sys/user/userns package, which
was retracted and moved to moby/sys/userns

- full diff: f3cf9359bd...2269acc7a3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-08 13:37:58 +02:00
Sebastiaan van Stijn 7fc8802889
Merge pull request #5330 from vvoland/vendor-docker-master
vendor: github.com/docker/docker master  (f3cf9359bdf6)
2024-08-08 12:09:30 +02:00
Paweł Gronowski 91b173e69f
Merge pull request #5316 from thaJeztah/add_security
add security policy
2024-08-08 11:48:43 +02:00
Paweł Gronowski b8a53ee340
vendor: github.com/docker/docker master (f3cf9359bdf6)
full diff: 2b1097f080...f3cf9359bd

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-08 11:44:02 +02:00
Sebastiaan van Stijn 0052d2ce05
Merge pull request #5327 from laurazard/fix-panic-pluginserver
plugins: don't panic on Close if PluginServer nil
2024-08-07 17:16:00 +02:00
Laura Brehm 9c4480604e
plugins: don't panic on Close if PluginServer nil
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-08-07 14:04:31 +01:00
Sebastiaan van Stijn 87c6624cb7
Merge pull request #5324 from vvoland/update-go-1.21.13
update to go1.21.13
2024-08-07 12:01:32 +02:00
Paweł Gronowski 434d8b75e8
update to go1.21.13
- https://github.com/golang/go/issues?q=milestone%3AGo1.21.13+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.21.12...go1.21.13

go1.21.13 (released 2024-08-06) includes fixes to the go command, the
covdata command, and the bytes package. See the [Go 1.21.13 milestone](https://github.com/golang/go/issues?q=milestone%3AGo1.21.13+label%3ACherryPickApproved)
on our issue tracker for details.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-08-07 11:49:40 +02:00
Jianyong Wu 73e78a5822 run: fix GetList return empty issue for throttledevice
Test "--device-read-bps" "--device-write-bps" will fail. The root
cause is that GetList helper return empty as its local variable
initialized to zero size.

This patch fix it by setting the related slice size to non-zero.

Signed-off-by: Jianyong Wu <wujianyong@hygon.cn>
Fixes: #5321
2024-08-07 02:48:39 +00:00
Sebastiaan van Stijn e29292f921
add security policy
Based on the security policy in the Moby repository (with the name
of the project changed, and a link to to the Moby documentation for
maintained branches).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-05 11:58:34 +02:00
Laura Brehm 78de7da660
Merge pull request #5310 from thaJeztah/gha_permissions
gha: set permissions to read-only by default
2024-08-02 11:26:06 +01:00
Laura Brehm 93ee2e6638
Merge pull request #5311 from thaJeztah/vendor_otel_trace
vendor: go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.21.0
2024-08-02 11:25:20 +01:00
Sebastiaan van Stijn 40a5b297b6
vendor: go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.21.0
commit 89db01ef97 added these tracing modules
as dependency, but did not require the otlptracehttp module. This module
was added later through f0a29af0f3 as indirect
dependency for docker/docker. The otlptracehttp and otlptracegrpc modules
have no dependency between each-other, but similar to their otlpmetric
cousins, are preferred to be on the same version.

This patch aligns their versions. No changes in vendored code;

full diff: https://github.com/open-telemetry/opentelemetry-go/compare/exporters/otlp/otlptrace/otlptracehttp/v1.19.0...exporters/otlp/otlptrace/otlptracehttp/v1.21.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-31 22:28:36 +02:00
Sebastiaan van Stijn e4d99b4b60
gha: set permissions to read-only by default
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-31 14:19:02 +02:00
Laura Brehm ddd4c39930
Merge pull request #5303 from laurazard/fix-flaky-runattach-test
tests/run: fix flaky `RunAttachTermination` test
2024-07-29 13:43:31 +01:00
Laura Brehm eac83574c1
tests/run: fix flaky `RunAttachTermination` test
This test was just incorrect (and testing incorrect
behavior): it was checking that `docker run` exited with a `context
canceled` error after signalling the CLI/cancelling the command's
context, but this was incorrect (and was fixed in
991b1303da - which was when this test
started failing).

However, since this test assertion was happening inside of a goroutine,
it would sometimes pass if this assertion didn't get to run before the
test suite terminated. It was flaky because sometimes this assertion
inside the goroutine did get to execute, but after the test finished
execution, which is a big no-no.

As an aside, assertions inside goroutines are generally bad, and `govet`
even has a linter for this (but it only catches `t.Fatal` and `t.FailNow`
calls and not `assert.Xx`.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-29 13:29:12 +01:00
Paweł Gronowski 393de5f44f
Merge pull request #5252 from thaJeztah/migrate_userns
vendor: docker/docker 2b1097f08088 (removes containerd dependency)
2024-07-26 16:25:11 +02:00
Laura Brehm bc7e64d425
Merge pull request #5297 from laurazard/fix-context-cancel-attach-exit-code
attach: wait for exit code from `ContainerWait`
2024-07-26 14:11:01 +01:00
Laura Brehm 7b46bfc5ac
attach: wait for exit code from `ContainerWait`
Such as with `docker run`, if a user CTRL-Cs while attached to a
container, we should forward the signal and wait for the exit from
`ContainerWait`, instead of just returning.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-26 14:05:31 +01:00
Sebastiaan van Stijn f0a29af0f3
vendor: docker/docker 2b1097f08088 (removes containerd dependency)
full diff: aae044039c...2b1097f080

The userns package in libcontainer was integrated into the moby/sys/user
module at commit 3778ae603c706494fd1e2c2faf83b406e38d687d.

The userns package is used in many places, and currently either depends
on runc/libcontainer, or on containerd, both of which have a complex
dependency tree. This patch is part of a series of patches to unify the
implementations, and to migrate toward that implementation to simplify
the dependency tree.

[3778ae603c706494fd1e2c2faf83b406e38d687d]: 3778ae603c

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-25 14:57:30 +02:00
Sebastiaan van Stijn b34e8e4dff
vendor: github.com/moby/sys/sequential v0.6.0
full diff: https://github.com/moby/sys/compare/sequential/v0.5.0...sequential/v0.6.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-25 14:56:13 +02:00
Sebastiaan van Stijn ea37ac9bac
vendor: github.com/moby/sys/symlink v0.3.0
full diff: https://github.com/moby/sys/compare/symlink/v0.2.0...symlink/v0.3.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-25 14:55:23 +02:00
Sebastiaan van Stijn 435c658333
vendor: github.com/moby/sys/signal v0.7.1
full diff: https://github.com/moby/sys/compare/signal/v0.7.0...signal/v0.7.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-25 14:54:29 +02:00
Sebastiaan van Stijn 501904d48f
vendor: golang.org/x/sys v0.22.0
full diff: https://github.com/golang/sys/compare/v0.21.0...v0.22.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-25 14:53:35 +02:00
Laura Brehm 826fc32e82
Merge pull request #5298 from laurazard/fix-linter
lint: replace deprecated linter names
2024-07-25 12:37:19 +01:00
Laura Brehm cc4163296f
lint: replace deprecated linter names
`megacheck` has been deprecated/split into `gosimple`, `staticcheck`,
and `unused`, which we're already using.

d2b439faa5/pkg/lint/lintersdb/validator_test.go (L227)

`vet` is now `govet`.

d2b439faa5/pkg/lint/lintersdb/validator_test.go (L228)

For more context, see: https://github.com/golangci/golangci-lint/pull/4562

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-25 12:18:50 +01:00
Sebastiaan van Stijn 788e99620d
Merge pull request #5295 from laurazard/fix-context-cancel-attach
attach: don't return context cancelled error
2024-07-25 02:00:26 +02:00
Laura Brehm 66aa0f672c
attach: don't return context cancelled error
In 3f0d90a2a9 we introduced a global
signal handler and made sure all the contexts passed into command
execution get (appropriately) cancelled when we get a SIGINT.

Due to that change, and how we use this context during `docker attach`,
we started to return the context cancelation error when a user signals
the running `docker attach`.

Since this is the intended behavior, we shouldn't return an error, so
this commit adds checks to ignore this specific error in this case.

Also adds a regression test.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-25 00:49:33 +01:00
Sebastiaan van Stijn 0cc1b8c0df
Merge pull request #5289 from thaJeztah/remove_ubuntu_23.10
docs: refresh image versions in examples
2024-07-24 13:11:35 +02:00
Laura Brehm 1e0f669b00
Merge pull request #5291 from laurazard/fix-all-the-flaky-connhelper-tests
tests: fix other flaky `connhelper` tests
2024-07-24 12:03:55 +01:00
Laura Brehm 4a7388f0dd
tests: fix other flaky `connhelper` tests
Follow up to cc68c66c95 (there were more
tests with incorrect syntax).

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-24 11:52:23 +01:00
Laura Brehm 1055536c5c
Merge pull request #5290 from laurazard/fix-flaxy-connhelper-test
Fix flaky `TestCloseRunningCommand` test
2024-07-24 11:03:24 +01:00
Laura Brehm cc68c66c95
tests: fix flaxy `TestCloseRunningCommand` test
Looks like this test was failing due to bad syntax on the `while` loop,
which caused it to die after 1 second. If the test took a bit longer,
the process would be dead before the following assertions run, causing
the test to fail/be flaky.

Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-24 10:31:45 +01:00
Sebastiaan van Stijn b36522b473
docs: refresh image versions in examples
use current LTS versions of ubuntu where suitable, remove uses of
ubuntu:23.10 (which reache EOL), and and update some other examples
to use more current versions.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-24 09:47:36 +02:00
Paweł Gronowski a69c0365b6
Merge pull request #5273 from thaJeztah/vendor_containerd_1.7.20
vendor: github.com/containerd/containerd v1.7.20
2024-07-23 14:59:23 +02:00
Laura Brehm 8f20c9a238
Merge pull request #5259 from thaJeztah/move_file_warning
cli/config/credentials: move warning to fileStore
2024-07-22 17:59:14 +01:00
Sebastiaan van Stijn d5f90ed547
Merge pull request #5236 from thaJeztah/cleanup_run_errors
cli/command/container: remove reportError, and put StatusError to use
2024-07-22 17:56:16 +02:00
Sebastiaan van Stijn 6559d86217
Merge pull request #5145 from psaintlaurent/ENGINE-903
Add OomScoreAdj to "docker service create" and "docker compose"
2024-07-19 19:09:28 +02:00
plaurent aa2c2cd906 Allow for OomScoreAdj
Signed-off-by: plaurent <patrick@saint-laurent.us>
2024-07-19 13:02:01 -04:00
Sebastiaan van Stijn 401048b9cb
vendor: github.com/containerd/containerd v1.7.20
no changes in vendored code

full diff: https://github.com/containerd/containerd/compare/v1.7.19...v1.7.20

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 19:01:54 +02:00
Sebastiaan van Stijn 5568565b54
Merge pull request #5098 from thaJeztah/custom_headers_env_var
add support for DOCKER_CUSTOM_HEADERS env-var (experimental)
2024-07-19 16:43:56 +02:00
Sebastiaan van Stijn 6638deb9d6
add support for DOCKER_CUSTOM_HEADERS env-var (experimental)
This environment variable allows for setting additional headers
to be sent by the client. Headers set through this environment
variable are added to headers set through the config-file (through
the HttpHeaders field).

This environment variable can be used in situations where headers
must be set for a specific invocation of the CLI, but should not
be set by default, and therefore cannot be set in the config-file.

WARNING: If both config and environment-variable are set, the environment
variable currently overrides all headers set in the configuration file.
This behavior may change in a future update, as we are considering the
environment variable to be appending to existing headers (and to only
override headers with the same name).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 15:04:26 +02:00
Sebastiaan van Stijn cd92610bca
Merge pull request #5268 from thaJeztah/add_macos_apple_silicon
gha: update to macOS 13, add macOS 14 arm64 (Apple Silicon M1)
2024-07-19 13:29:35 +02:00
Sebastiaan van Stijn 9617e8d0ce
gha: update to macOS 13, add macOS 14 arm64 (Apple Silicon M1)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 13:05:43 +02:00
Sebastiaan van Stijn ef8b0bf066
Merge pull request #5262 from thaJeztah/relax_pr_check
gha: check-pr-branch: verify major version only
2024-07-19 12:48:41 +02:00
Sebastiaan van Stijn 6d8fcbb233
gha: check-pr-branch: verify major version only
We'll be using release branches for minor version updates, so instead
of (e.g.) a 27.0 branch, we'll be using 27.x and continue using the
branch for minor version updates.

This patch changes the validation step to only compare against the
major version.

Co-authored-by: Cory Snider <corhere@gmail.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 12:19:57 +02:00
Sebastiaan van Stijn 659a3bebf2
Merge pull request #5264 from thaJeztah/bump_buildx_compose
Dockerfile: update buildx to v0.16.1, compose to v2.29.0
2024-07-19 10:22:33 +02:00
Sebastiaan van Stijn 77c0d83602
Dockerfile: update compose to v2.29.0
This is the version used in the dev-container, and for testing.

release notes: https://github.com/docker/compose/releases/tag/v2.29.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 02:44:06 +02:00
Sebastiaan van Stijn d00e1abf55
Dockerfile: update buildx to v0.16.1
This is the version used in the dev-container, and for testing.

release notes:
https://github.com/docker/buildx/releases/tag/v0.16.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 02:42:47 +02:00
Sebastiaan van Stijn ab80ea355f
cli/config/credentials: move warning to fileStore
The fileStore itself is aware that it's insecure, so we can make it
responsible for printing the warning. It's not "perfect", as we use
`os.Stderr` unconditionally (not `dockerCli.Err()`), but probably won't
make a difference in _most_ cases.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-19 01:42:01 +02:00
Sebastiaan van Stijn 26b412e491
Merge pull request #5258 from thaJeztah/cleanup_unencrypted_warning
login: slightly cleanup warning about unencrypted store
2024-07-19 01:41:35 +02:00
Sebastiaan van Stijn fcefe44bda
login: slightly cleanup warning about unencrypted store
- Add an empty line before the warning to separate it from the command's output
- Use the `/go/` redirect URL that we have available.
- Put quotes around the filename used for storage.
- Use present tense for the message, as the message is printed while saving.
- User "credentials" instead of "password" for consistency with "credentials-store"

Before:

    docker login myregistry.example.com
    Username: thajeztah
    Password:
    WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
    Configure a credential helper to remove this warning. See
    https://docs.docker.com/engine/reference/commandline/login/#credential-stores

    Login Succeeded

After:

    docker login myregistry.example.com
    Username: thajeztah
    Password:

    WARNING! Your credentials are stored unencrypted in '/root/.docker/config.json'.
    Configure a credential helper to remove this warning. See
    https://docs.docker.com/go/credential-store/

    Login Succeeded

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-18 18:22:13 +02:00
Sebastiaan van Stijn a78ab63801
login: don't print "unencrypted" warning when failing to save credentials
If we fail to save credentials, make sure that the error about saving
doesn't get lost in the warning about credentials being stored unencrypted.

Also discard errors about printing the warning, as those would be unlikely,
and if they would occur, probably would fail to be printed as well.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-18 18:15:12 +02:00
Sebastiaan van Stijn 90058df305
cli/command/container: remove reportError, and put StatusError to use
The `reportError` utility was present because cli.StatusError would print
the error decorated with `Status: <error-message>, Code: <exit-code>`.
That was not desirable in many cases as it would mess-up the output. To
prevent this, the CLI had code to check for an empty `Status` (error message)
in which case the error would be "ignored" (and only used for the exit-status),
and the `reportError` utility would be used to manually print a custom error
message before returning the error.

Now that bca2090061 fixed the output format
of `cli.StatusError`, and 3dd6fc365d and
350a0b68a9 no longer discard these error,
we can get rid of this utility, and just set the error-message for
the status-error.

This patch:

- Introduces a `withHelp` which takes care of decorating errors with
  a "Run --help" hint for the user.
- Introduces a `toStatusError` utility that detects certain errors in
  the container to assign a corresponding exit-code (these error-codes
  can be used to distinguish "client" errors from "container" errors).
- Removes the `reportError` utility, and removes code that manually
  printed errors before returning.

Behavior is mostly unmodified, with the exception of some slight reformatting
of the errors:

- `withHelp` adds a `docker:` prefix to the error, to indicate the error
  is produced by the `docker` command. This prefix was already present
  in most cases.
- The "--help" hint is slightly updated ("Run 'docker run --help' for
  more information" instead of "See 'docker run --help'"), to make it
  more clear that it's a "call to action".
- An empty is added before the "--help" hint to separate it better from
  the error-message.

Before this patch:

    $ docker run --pull=invalid-option alpine
    docker: invalid pull option: 'invalid-option': must be one of "always", "missing" or "never".
    See 'docker run --help'.
    $ echo $?
    125

    $ docker run --rm alpine nosuchcommand
    docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "nosuchcommand": executable file not found in $PATH: unknown.
    $ echo $?
    127

With this patch:

    $ docker run --pull=invalid-option alpine
    docker: invalid pull option: 'invalid-option': must be one of "always", "missing" or "never"

    Run 'docker run --help' for more information
    $ echo $?
    125

    $ docker run --rm alpine nosuchcommand
    docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "nosuchcommand": executable file not found in $PATH: unknown.

    Run 'docker run --help' for more information
    $ echo $?
    127

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 15:59:30 +02:00
Sebastiaan van Stijn 07baebe90b
Merge pull request #5255 from thaJeztah/bump_docs_tool
vendor: github.com/docker/cli-docs-tool v0.8.0
2024-07-17 15:59:18 +02:00
Sebastiaan van Stijn 2da5f06962
Merge pull request #5238 from thaJeztah/completion_improvements
various improvements to shell completions
2024-07-17 15:35:14 +02:00
Sebastiaan van Stijn 64a3fb82dc
docs: fix typos and version for cli-docs-tool scripts
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 15:25:37 +02:00
Sebastiaan van Stijn e3e9b99015
vendor: github.com/docker/cli-docs-tool v0.8.0
no changes in vendored code

full diff: https://github.com/docker/cli-docs-tool/compare/v0.7.0...v0.8.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 15:23:23 +02:00
Sebastiaan van Stijn 05a808166b
Merge pull request #5233 from thaJeztah/nicer_errors
cli: FlagErrorFunc: don't print long usage output for invalid flags
2024-07-17 14:00:52 +02:00
Sebastiaan van Stijn f28fc7f82f
cli: FlagErrorFunc: don't print long usage output for invalid flags
When trying to use an invalid flag, the CLI currently prints the a short
error message, instructions to use the `--help` flag to learn about the
correct usage, followed by the command's usage output.

While this is a common convention, and may have been a nice gesture when
docker was still young and only had a few commands and options ("you did
something wrong, but here's an overview of what you can use"), that's no
longer the case, and many commands have a _very_ long output.

The result of this is that the error message, which is the relevant
information in this case - "You mis-typed something" - is lost in the
output, and hard to find (sometimes even requiring scrolling back).

The output is also confusing, because it _looks_ like something ran
successfully (most of the output is not about the error!).

Even further; the suggested resolution (try `--help` to see the correct
options) is rather redundant, because running teh command with `--help`
produces _exactly_ the same output as was just showh, baring the error
message. As a fun fact, due to the usage output being printed, the
output even contains not one, but _two_ "call to actions";

- `See 'docker volume --help'.` (under the erro message)
- `Run 'docker volume COMMAND --help' for more information on a command.`
  (under the usage output)

In short; the output is too verbose, confusing, and doesn't provide
a good UX. Let's reduce the output produced so that the focus is on the
important information.

This patch:

- Changes the usage to the short-usage.
- Prefixes the error message with the binary / root-command name
  (usually `docker:`) to be consistent with `unknon command`, and helps
  to distinguish where the message originated from (the `docker` CLI in
  this case).
- Adds an empty line between the error-message and the "call to action"
  (`Run 'docker volume --help' ...` in the example below). This helps
  separating the error message ("unkown flag") from the call-to-action.

Before this patch:

    docker volume --no-such-flag
    unknown flag: --no-such-flag
    See 'docker volume --help'.

    Usage:  docker volume COMMAND

    Manage volumes

    Commands:
      create      Create a volume
      inspect     Display detailed information on one or more volumes
      ls          List volumes
      prune       Remove unused local volumes
      rm          Remove one or more volumes
      update      Update a volume (cluster volumes only)

    Run 'docker volume COMMAND --help' for more information on a command.

With this patch:

    docker volume --no-such-flag
    docker: unknown flag: --no-such-flag

    Usage:  docker volume COMMAND

    Run 'docker volume --help' for more information

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 13:22:31 +02:00
Sebastiaan van Stijn b1c0ddca02
cli/command/container: add completion for --stop-signal
With this patch:

    docker run --stop-signal <TAB>
    ABRT  IOT      RTMAX-4   RTMIN     RTMIN+11  TSTP
    ALRM  KILL     RTMAX-5   RTMIN+1   RTMIN+12  TTIN
    BUS   PIPE     RTMAX-6   RTMIN+2   RTMIN+13  TTOU
    CHLD  POLL     RTMAX-7   RTMIN+3   RTMIN+14  URG
    CLD   PROF     RTMAX-8   RTMIN+4   RTMIN+15  USR1
    CONT  PWR      RTMAX-9   RTMIN+5   SEGV      USR2
    FPE   QUIT     RTMAX-10  RTMIN+6   STKFLT    VTALRM
    HUP   RTMAX    RTMAX-11  RTMIN+7   STOP      WINCH
    ILL   RTMAX-1  RTMAX-12  RTMIN+8   SYS       XCPU
    INT   RTMAX-2  RTMAX-13  RTMIN+9   TERM      XFSZ
    IO    RTMAX-3  RTMAX-14  RTMIN+10  TRAP

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:34 +02:00
Sebastiaan van Stijn d6f78cdbb1
cli/command/container: add completion for --volumes-from
With this patch:

    docker run --volumes-from amazing_nobel
    amazing_cannon     boring_wozniak         determined_banzai
    elegant_solomon    reverent_booth         amazing_nobel

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:34 +02:00
Sebastiaan van Stijn 7fe7223c2c
cli/command/container: add completion for --restart
With this patch:

    docker run --restart <TAB>
    always  no  on-failure  unless-stopped

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:34 +02:00
Sebastiaan van Stijn f30158dbf8
cli/command/container: add completion for --cap-add, --cap-drop
With this patch:

    docker run --cap-add <TAB>
    ALL                     CAP_KILL                CAP_SETUID
    CAP_AUDIT_CONTROL       CAP_LEASE               CAP_SYSLOG
    CAP_AUDIT_READ          CAP_LINUX_IMMUTABLE     CAP_SYS_ADMIN
    CAP_AUDIT_WRITE         CAP_MAC_ADMIN           CAP_SYS_BOOT
    CAP_BLOCK_SUSPEND       CAP_MAC_OVERRIDE        CAP_SYS_CHROOT
    CAP_BPF                 CAP_MKNOD               CAP_SYS_MODULE
    CAP_CHECKPOINT_RESTORE  CAP_NET_ADMIN           CAP_SYS_NICE
    CAP_CHOWN               CAP_NET_BIND_SERVICE    CAP_SYS_PACCT
    CAP_DAC_OVERRIDE        CAP_NET_BROADCAST       CAP_SYS_PTRACE
    CAP_DAC_READ_SEARCH     CAP_NET_RAW             CAP_SYS_RAWIO
    CAP_FOWNER              CAP_PERFMON             CAP_SYS_RESOURCE
    CAP_FSETID              CAP_SETFCAP             CAP_SYS_TIME
    CAP_IPC_LOCK            CAP_SETGID              CAP_SYS_TTY_CONFIG
    CAP_IPC_OWNER           CAP_SETPCAP             CAP_WAKE_ALARM

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:33 +02:00
Sebastiaan van Stijn e4dd8b1898
cli/context/store: Names(): fix panic when called with nil-interface
Before this, it would panic when a nil-interface was passed.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:33 +02:00
Sebastiaan van Stijn 42b68a3ed7
cmd/docker: fix completion for --context
registerCompletionFuncForGlobalFlags was called from newDockerCommand,
at which time no context-store is initialized yet, so it would return
a nil value, probably resulting in `store.Names` to panic, but these
errors are not shown when running the completion. As a result, the flag
completion would fall back to completing from filenames.

This patch changes the function to dynamically get the context-store;
this fixes the problem mentioned above, because at the time the completion
function is _invoked_, the CLI is fully initialized, and does have a
context-store available.

A (non-exported) interface is defined to allow the function to accept
alternative implementations (not requiring a full command.DockerCLI).

Before this patch:

    docker context create one
    docker context create two

    docker --context <TAB>
    .DS_Store                   .idea/                      Makefile
    .dockerignore               .mailmap                    build/
    ...

With this patch:

    docker context create one
    docker context create two

    docker --context <TAB>
    default  one      two

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:33 +02:00
Sebastiaan van Stijn 162d9748b9
cli/command/container: provide flag-completion for "docker create"
"docker run" and "docker create" are mostly identical, so we can copy
the same completion functions,

We could possibly create a utility for this (similar to `addFlags()` which
configures both commands with the flags they share). I considered combining
his with `addFlags()`, but that utility is also used in various tests, in
which we don't need this feature, so keeping that for a future exercise.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:33 +02:00
Sebastiaan van Stijn 5e7bcbeac6
cli/command/completion: add FromList utility
It's an alias for cobra.FixedCompletions but takes a variadic list
of strings, so that it's not needed to construct an array for this.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:33 +02:00
Sebastiaan van Stijn e3427f341b
cli/command/completion: add EnvVarNames utility
EnvVarNames offers completion for environment-variable names. This
completion can be used for "--env" and "--build-arg" flags, which
allow obtaining the value of the given environment-variable if present
in the local environment, so we only should complete the names of the
environment variables, and not their value. This also prevents the
completion script from printing values of environment variables
containing sensitive values.

For example;

    export MY_VAR=hello
    docker run --rm --env MY_VAR alpine printenv MY_VAR
    hello

Before this patch:

    docker run --env GO
    GO111MODULE=auto        GOLANG_VERSION=1.21.12  GOPATH=/go              GOTOOLCHAIN=local

With this patch:

    docker run --env GO<tab>
    GO111MODULE     GOLANG_VERSION  GOPATH          GOTOOLCHAIN

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:32 +02:00
Sebastiaan van Stijn 9207ff1046
cli/command/completion: add FileNames utility
This is just a convenience function to allow defining completion to
use the default (complete with filenames and directories).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:32 +02:00
Sebastiaan van Stijn eed0e5b02a
cli/command/container: NewRunCommand: slight cleanup of completion
- explicitly suppress unhandled errors
- remove names for unused arguments

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-17 01:25:32 +02:00
Sebastiaan van Stijn ce4469a696
Merge pull request #5234 from thaJeztah/nicer_missing_commands
cli: improve output and consistency for unknown (sub)commands
2024-07-17 01:22:03 +02:00
Sebastiaan van Stijn 45fc3b33eb
Merge pull request #5251 from thaJeztah/bump_engine
vendor: github.com/docker/docker aae044039ca4 (master, v-next)
2024-07-17 00:20:13 +02:00
Sebastiaan van Stijn e8baee9c7c
vendor: github.com/docker/docker aae044039ca4 (master, v-next)
full diff: 508cc7c612...aae044039c

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-16 19:01:14 +02:00
Sebastiaan van Stijn a77ba7eda8
vendor: google.golang.org/genproto/googleapis/api 49dd2c1f3d0b
No changes in vendored files. This one got out of sync with the other modules
from the same repository.

full diff: d307bd883b...49dd2c1f3d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-16 19:00:14 +02:00
Sebastiaan van Stijn caa5d15e98
vendor: github.com/prometheus/procfs v0.15.1
full diff: https://github.com/prometheus/procfs/compare/v0.12.0...v0.15.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-16 18:46:30 +02:00
Sebastiaan van Stijn 0f712827f1
vendor: github.com/containerd/containerd v1.7.19
no changes in vendored code

full diff: https://github.com/containerd/containerd/compare/v1.7.18...v1.7.19

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-16 18:45:37 +02:00
Sebastiaan van Stijn b28a1cd029
vendor: golang.org/x/sync v0.7.0
no changes in vendored code

full diff: https://github.com/golang/sync/compare/v0.6.0...v0.7.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-16 18:44:28 +02:00
Paweł Gronowski dc23e77507
Merge pull request #5247 from Benehiko/hotfix-sigterm-container
fix: container stream should not be terminated by ctx
2024-07-12 14:44:10 +02:00
Paweł Gronowski 2f529a1965
Merge pull request #5246 from vvoland/push-nodefault-pre146
push: Don't default to `DOCKER_DEFAULT_PLATFORM`, improve message
2024-07-11 12:05:26 +02:00
Alano Terblanche 991b1303da
chore: restore ctx without cancel on container run
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-07-11 09:49:14 +02:00
Paweł Gronowski 6c04adc05e
push: Improve note message and colors
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-07-10 11:36:40 +02:00
Alano Terblanche 0579cd7971
test: e2e SIGTERM attached container on `docker run`
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-07-09 13:23:38 +02:00
Paweł Gronowski d40199440d
c8d: Remove `docker convert` mention
It's not merged yet.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-07-09 12:30:03 +02:00
Paweł Gronowski 4ce6e50e2e
push: Don't default to DOCKER_DEFAULT_PLATFORM
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-07-09 12:30:02 +02:00
Sebastiaan van Stijn cfbf88fd9f
Merge pull request #5232 from thaJeztah/dev_completion
install bash-completion in dev container
2024-07-08 12:21:15 -05:00
Sebastiaan van Stijn 3f3ecb94c5
Makefile: add completion target
Add a "completion" target to install the generated completion
scripts inside the dev-container. As generating this script
depends on the docker binary, it calls "make binary" first.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-08 10:58:56 -05:00
Alano Terblanche 150fb55a8f
fix: container stream should not be terminated by ctx
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-07-08 17:44:33 +02:00
Sebastiaan van Stijn 3d80b7b0a7
Dockerfile.dev: install bash-completion in dev container
It's not initialized, because there's no `docker` command installed
by default, but at least this makes sure that the basics are present
for testing.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 15:23:06 +02:00
David Karlsson 9bb1a62735
Merge pull request #5010 from dvdksn/cli-reference-overview-base-cmd
cli reference overview base cmd
2024-07-05 15:19:26 +02:00
Sebastiaan van Stijn 61c6ff2d4a
Merge pull request #5229 from thaJeztah/exit_error
cmd/docker: split handling exit-code to a separate utility
2024-07-05 11:47:30 +02:00
Sebastiaan van Stijn eae75092a0
cmd/docker: split handling exit-code to a separate utility
This allows dockerMain() to return an error "as usual", and puts the
responsibility for turning that into an appropriate exit-code in
main() (which also sets the exit-code when terminating).

We could consider putting this utility in the cli package and exporting
it if would be useful for doing a similar handling in plugins.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 11:02:22 +02:00
Sebastiaan van Stijn b7695d6c79
cli-plugins: RunPlugin(): rename error-variable that's possibly shadowed
The logic in this function is confusing; let's start make it obvious where
the error that is returned is produced,

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 11:01:41 +02:00
Sebastiaan van Stijn 350a0b68a9
cli-plugins: Run(): don't discard cli.StatusError errors without message
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:27 +02:00
Sebastiaan van Stijn 3dd6fc365d
cmd/docker: don't discard cli.StatusError errors without custom message
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:27 +02:00
Sebastiaan van Stijn 2f83064ec4
e2e/cli-plugins: check for exit-errors in tests
Verify that we get the expected exit-code, not just the message.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:26 +02:00
Sebastiaan van Stijn baf35da401
e2e/cli-plugins: use cmd.CombinedOutput() instead of custom buffer
Also remove a debug-log, as the output would already be shown if
the test would fail.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:26 +02:00
Sebastiaan van Stijn c6b40640cc
e2e/cli-plugins: use identifiable output for test
This confused me fore a bit, because I thought the test was checking for
an actual `context.Canceled` error (which is spelled "context canceled"
with a single "l". But then I found that this was a string that's printed
as part of a test-utility, just looking very similar but with the British
spelling ("cancelled").

Let's change this to a message that's unique for the test, also to make it
more grep'able.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:26 +02:00
Sebastiaan van Stijn e9f32edac5
e2e/cli-plugins: explicitly ignore fmt.Printxx errors
To keep some linters happier, and my IDE to be less noisy.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:26 +02:00
Sebastiaan van Stijn 5e7948ec83
e2e/cli-plugins: rename var that shadowed import
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 10:59:13 +02:00
Sebastiaan van Stijn cad08ff3b1
Merge pull request #5231 from thaJeztah/prettier_exit_status
cli: make cli.StatusError slightly prettier
2024-07-05 10:50:46 +02:00
Paweł Gronowski be6a415f86
Merge pull request #5230 from thaJeztah/clean_skip
cli/command/container: TestSplitCpArg: cleaner skip
2024-07-05 10:41:36 +02:00
Sebastiaan van Stijn c60b360c33
cli: improve argument validation output
Improve the output for these validation errors:

- Removes the short command description from the output. This information
  does not provide much useful help, and distracts from the error message.
- Reduces punctuation, and
- Prefixes the error message with the binary / root-command name
  (usually `docker:`) to be consistent with other similar errors.
- Adds an empty line between the error-message and the "call to action"
  (`Run 'docker volume --help'...` in the example below). This helps
  separating the error message and "usage" from the call-to-action.

Before this patch:

    $ docker volume ls one two three
    "docker volume ls" accepts no arguments.
    See 'docker volume ls --help'.

    Usage:  docker volume ls [OPTIONS]

    List volumes

    $ docker volume create one two three
    "docker volume create" requires at most 1 argument.
    See 'docker volume create --help'.

    Usage:  docker volume create [OPTIONS] [VOLUME]

    Create a volume

With this patch:

    $ docker volume ls one two three
    docker: 'docker volume ls' accepts no arguments

    Usage:  docker volume ls [OPTIONS]

    Run 'docker volume ls --help' for more information

    $ docker voludocker volume create one two three
    docker: 'docker volume create' requires at most 1 argument

    Usage:  docker volume create [OPTIONS] [VOLUME]

    SRun 'docker volume create --help' for more information

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 03:35:14 +02:00
Sebastiaan van Stijn a6e96c758e
cli: improve output and consistency for unknown (sub)commands
Before this patch, output for invalid top-level and sub-commands differed.
For top-level commands, the CLI would print an error-message and a suggestion
to use `--help`. For missing *subcommands*, we would hit a different code-path,
and different output, which includes full "usage" / "help" output.

While it is a common convention to show usage output, and may have been
a nice gesture when docker was still young and only had a few commands
and options ("you did something wrong; here's an overview of what you
can use"), that's no longer the case, and many commands have a _very_
long output.

The result of this is that the error message, which is the relevant
information in this case - "You mis-typed something" - is lost in the
output, and hard to find (sometimes even requiring scrolling back).

The output is also confusing, because it _looks_ like something ran
successfully (most of the output is not about the error!).

Even further; the suggested resolution (try `--help` to see the correct
options) is rather redundant, because running teh command with `--help`
produces _exactly_ the same output as was just showh, baring the error
message. As a fun fact, due to the usage output being printed, the
output even contains not one, but _two_ "call to actions";

- `See 'docker volume --help'.` (under the erro message)
- `Run 'docker volume COMMAND --help' for more information on a command.`
  (under the usage output)

In short; the output is too verbose, confusing, and doesn't provide
a good UX. Let's reduce the output produced so that the focus is on the
important information.

This patch:

- Changes the usage to the short-usage.
- Changes the error-message to mention the _full_ command instead of only
  the command after `docker` (so `docker no-such-command` instead of
  `no-such-command`).
- Prefixes the error message with the binary / root-command name
  (usually `docker:`); this is something we can still decide on, but
  it's a pattern we already use in some places. The motivation for this
  is that `docker` commands can often produce output that's a combination
  of output from the CLI itself, output from the daemon, and even output
  from the container. The `docker:` prefix helps to distinguish where
  the message originated from (the `docker` CLI in this case).
- Adds an empty line between the error-message and the "call to action"
  (`Run 'docker volume --help'...` in the example below). This helps
  separating the error message ("unkown flag") from the call-to-action.

Before this patch:

Unknown top-level command:

    docker nosuchcommand foo
    docker: 'nosuchcommand' is not a docker command.
    See 'docker --help'

Unknown sub-command:

    docker volume nosuchcommand foo

    Usage:  docker volume COMMAND

    Manage volumes

    Commands:
      create      Create a volume
      inspect     Display detailed information on one or more volumes
      ls          List volumes
      prune       Remove unused local volumes
      rm          Remove one or more volumes
      update      Update a volume (cluster volumes only)

    Run 'docker volume COMMAND --help' for more information on a command.

After this patch:

Unknown top-level command:

    docker nosuchcommand foo
    docker: unknown command: docker nosuchcommand

    Run 'docker --help' for more information

Unknown sub-command:

    docker volume nosuchcommand foo
    docker: unknown command: 'docker volume nosuchcommand'

    Usage:  docker volume COMMAND

    Run 'docker volume --help' for more information

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-05 02:28:11 +02:00
Sebastiaan van Stijn bca2090061
cli: make cli.StatusError slightly prettier
This error didn't do a great job at formatting. If a StatusError was
produced without a Status message, it would print a very non-informative
error, with information missing.

Let's update the output:

- If a status-message is provided; print just that (after all the
  status code is something that can be found from the shell, e.g.
  through `echo $?` in Bash).
- If no status-message is provided: print a message more similar to
  Go's `exec.ExecError`, which uses `os.rocessState.String()` (see [1]).

Before this patch, an error without custom status would print:

    Status: , Code: 2

After this patch:

    exit status 2

In situations where a custom error-message is provided, the error-message
is print as-is, whereas before this patch, the message got combined with
the `Status:` and `Code:`, which resulted in some odd output.

Before this patch:

    docker volume --no-such-flag
    Status: unknown flag: --no-such-flag
    See 'docker volume --help'.

    Usage:  docker volume COMMAND

    Manage volumes

    Commands:
      create      Create a volume
      inspect     Display detailed information on one or more volumes
      ls          List volumes
      prune       Remove unused local volumes
      rm          Remove one or more volumes
      update      Update a volume (cluster volumes only)

    Run 'docker volume COMMAND --help' for more information on a command.
    , Code: 125

With this patch, the error is shown as-is;

    docker volume --no-such-flag
    unknown flag: --no-such-flag
    See 'docker volume --help'.

    Usage:  docker volume COMMAND

    Manage volumes

    Commands:
      create      Create a volume
      inspect     Display detailed information on one or more volumes
      ls          List volumes
      prune       Remove unused local volumes
      rm          Remove one or more volumes
      update      Update a volume (cluster volumes only)

    Run 'docker volume COMMAND --help' for more information on a command.

While the exit-code is no longer printed, it's still properly handled;

    echo $?
    125

[1]: 82c14346d8/src/os/exec_posix.go (L107-L135)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 22:08:18 +02:00
Sebastiaan van Stijn 88896eeaab
cli/command/container: TestSplitCpArg: cleaner skip
Trying to make the logic slightly clearer, and adding a custom
message for the skip,

Before this:

    === RUN   TestSplitCpArg/absolute_path_with_drive
        cp_test.go:184: tc.os == "windows" && runtime.GOOS != "windows" || tc.os == "linux" && runtime.GOOS == "windows"

After this:

    === RUN   TestSplitCpArg/absolute_path_with_drive
	cp_test.go:184: skipping windows test on non-windows platform

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 19:57:43 +02:00
Sebastiaan van Stijn 5aae44baaa
Merge pull request #5226 from thaJeztah/bump_engine_temp
vendor: github.com/docker/docker 508cc7c61226 (master)
2024-07-04 15:36:03 +02:00
Sebastiaan van Stijn b194274beb
replace uses of deprecated API types
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 15:22:18 +02:00
Sebastiaan van Stijn 4cac8efb56
vendor: github.com/docker/docker 508cc7c61226 (master)
full diff: https://github.com/docker/docker/v27.0.3..508cc7c6122651c4dfeeec2e626568704cfaf0f9

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 15:20:27 +02:00
Laura Brehm f5ce584ce0
Merge pull request #5223 from fredden/feature/completion/images
Enable completion for some 'image' sub commands
2024-07-04 11:15:23 +01:00
Sebastiaan van Stijn e99dfcd13e
Merge pull request #5224 from thaJeztah/test_spring_cleaning
test spring-cleaning
2024-07-04 12:14:00 +02:00
Paweł Gronowski 6abed4e3c4
Merge pull request #5225 from thaJeztah/network_cleanups
cli/command/network: some cleanup and pass smaller interfaces
2024-07-04 12:05:46 +02:00
Paweł Gronowski 404bf267f9
Merge pull request #5228 from thaJeztah/bump_bk_deps
vendor: update various dependencies
2024-07-04 11:10:05 +02:00
David Karlsson dc22572e3e chore: regenerate docs
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:30:56 +02:00
David Karlsson 8549d250f6 docs: update cli-docs-tool (v0.8.0)
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
David Karlsson 3d4c12af73 docs: update links to docker cli reference
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
David Karlsson bf33c8f10a docs: regenerate base command
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
David Karlsson b0650f281e docs: align heading structure for base command
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
David Karlsson cfea2353b3 docs: remove frontmatter for base command
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
David Karlsson 03961449aa docs: rename cli.md to docker.md (base command)
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
David Karlsson a683823383 docs: remove empty docker base command reference
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-04 10:28:53 +02:00
Sebastiaan van Stijn a0c4e56dea
vendor: golang.org/x/net v0.25.0
full diff: https://github.com/golang/net/compare/v0.24.0...v0.25.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 09:39:45 +02:00
Sebastiaan van Stijn 723130d7fe
vendor: golang.org/x/crypto v0.23.0
no changes in vendored code

full diff: https://github.com/golang/crypto/compare/v0.22.0...v0.23.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 09:38:44 +02:00
Sebastiaan van Stijn d33ef57dcb
vendor: golang.org/x/text v0.15.0
no changes in vendored files

full diff: https://github.com/golang/text/compare/v0.14.0...v0.15.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 09:38:04 +02:00
Sebastiaan van Stijn 21dbedd419
vendor: golang.org/x/sys v0.21.0
full diff: https://github.com/golang/sys/compare/v0.19.0...v0.21.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 09:32:57 +02:00
Sebastiaan van Stijn f8e7c0a0d6
vendor: github.com/klauspost/compress v1.17.9
full diff: https://github.com/klauspost/compress/compare/v1.17.4...v1.17.9

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 09:32:06 +02:00
David Karlsson 1dee86b4ba
Merge pull request #5002 from dvdksn/buildx_build_canonical
docs: make buildx build the canonical reference doc
2024-07-04 09:06:57 +02:00
Sebastiaan van Stijn f30d1ecc91
Merge pull request #5216 from Benehiko/force-lf
feat: force lf line endings by default
2024-07-04 02:09:34 +02:00
Sebastiaan van Stijn 10a015f871
cli/command/network: NewPruneCommand: explicitly ignore error
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 01:39:28 +02:00
Sebastiaan van Stijn b3d8809f42
cli/command/network: rewrite consolidateIpam to take an option-struct
Introduce a (non-exported) ipamOptions that collects all options for
creating a network.IPAM, so that this utility is more atomic (potentially
even could be moved to a separate package and exported).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 01:39:27 +02:00
Sebastiaan van Stijn ab230240ad
test spring-cleaning
This makes a quick pass through our tests;

Discard output/err
----------------------------------------------

Many tests were testing for error-conditions, but didn't discard output.
This produced a lot of noise when running the tests, and made it hard
to discover if there were actual failures, or if the output was expected.
For example:

    === RUN   TestConfigCreateErrors
    Error: "create" requires exactly 2 arguments.
    See 'create --help'.

    Usage:  create [OPTIONS] CONFIG file|- [flags]

    Create a config from a file or STDIN
    Error: "create" requires exactly 2 arguments.
    See 'create --help'.

    Usage:  create [OPTIONS] CONFIG file|- [flags]

    Create a config from a file or STDIN
    Error: error creating config
    --- PASS: TestConfigCreateErrors (0.00s)

And after discarding output:

    === RUN   TestConfigCreateErrors
    --- PASS: TestConfigCreateErrors (0.00s)

Use sub-tests where possible
----------------------------------------------

Some tests were already set-up to use test-tables, and even had a usable
name (or in some cases "error" to check for). Change them to actual sub-
tests. Same test as above, but now with sub-tests and output discarded:

    === RUN   TestConfigCreateErrors
    === RUN   TestConfigCreateErrors/requires_exactly_2_arguments
    === RUN   TestConfigCreateErrors/requires_exactly_2_arguments#01
    === RUN   TestConfigCreateErrors/error_creating_config
    --- PASS: TestConfigCreateErrors (0.00s)
        --- PASS: TestConfigCreateErrors/requires_exactly_2_arguments (0.00s)
        --- PASS: TestConfigCreateErrors/requires_exactly_2_arguments#01 (0.00s)
        --- PASS: TestConfigCreateErrors/error_creating_config (0.00s)
    PASS

It's not perfect in all cases (in the above, there's duplicate "expected"
errors, but Go conveniently adds "#01" for the duplicate). There's probably
also various tests I missed that could still use the same changes applied;
we can improve these in follow-ups.

Set cmd.Args to prevent test-failures
----------------------------------------------

When running tests from my IDE, it compiles the tests before running,
then executes the compiled binary to run the tests. Cobra doesn't like
that, because in that situation `os.Args` is taken as argument for the
command that's executed. The command that's tested now sees the test-
flags as arguments (`-test.v -test.run ..`), which causes various tests
to fail ("Command XYZ does not accept arguments").

    # compile the tests:
    go test -c -o foo.test

    # execute the test:
    ./foo.test -test.v -test.run TestFoo
    === RUN   TestFoo
    Error: "foo" accepts no arguments.

The Cobra maintainers ran into the same situation, and for their own
use have added a special case to ignore `os.Args` in these cases;
https://github.com/spf13/cobra/blob/v1.8.1/command.go#L1078-L1083

    args := c.args

    // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
    if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
        args = os.Args[1:]
    }

Unfortunately, that exception is too specific (only checks for `cobra.test`),
so doesn't automatically fix the issue for other test-binaries. They did
provide a `cmd.SetArgs()` utility for this purpose
https://github.com/spf13/cobra/blob/v1.8.1/command.go#L276-L280

    // SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
    // particularly useful when testing.
    func (c *Command) SetArgs(a []string) {
        c.args = a
    }

And the fix is to explicitly set the command's args to an empty slice to
prevent Cobra from falling back to using `os.Args[1:]` as arguments.

    cmd := newSomeThingCommand()
    cmd.SetArgs([]string{})

Some tests already take this issue into account, and I updated some tests
for this, but there's likely many other ones that can use the same treatment.

Perhaps the Cobra maintainers would accept a contribution to make their
condition less specific and to look for binaries ending with a `.test`
suffix (which is what compiled binaries usually are named as).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-04 01:35:12 +02:00
Dan Wallis c7d46aa7a1
Enable completion for 'image' sub commands
Signed-off-by: Dan Wallis <dan@wallis.nz>
2024-07-03 17:00:40 +01:00
Sebastiaan van Stijn 2eb61318b5
cli/command/network: some cleanup and pass smaller interfaces
Pass the appropriate API-client where possible instead of all of
DockerCLI, and some cleaning up.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-03 17:40:35 +02:00
Sebastiaan van Stijn 3837aa62d8
Merge pull request #5222 from thaJeztah/cleanup_for_engine_update
assorted minor changes in preparation of updating docker/docker dependency
2024-07-03 17:38:18 +02:00
Sebastiaan van Stijn b711372cab
cli/command/container: TestNewAttachCommandErrors: use struct-literals
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-03 17:09:41 +02:00
Sebastiaan van Stijn 229616e173
cli/command/image: fakeClient.ImagesPrune: fix unhandled err-return
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-03 17:09:41 +02:00
Sebastiaan van Stijn 42ba29395b
rename vars to prevent colliding with imports
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-03 17:09:41 +02:00
Sebastiaan van Stijn 3a77fdd91f
cli/command/trust: unconvert
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-03 17:09:40 +02:00
Sebastiaan van Stijn 26223f7017
cli/command/formatter: don't use unkeyed structs
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-03 17:09:40 +02:00
Paweł Gronowski bab48ebcc8
Merge pull request #5168 from Benehiko/fix-cli-login
fix: ctx cancellation on login prompt
2024-07-03 15:20:12 +02:00
Alano Terblanche c56f4a1ef7
workflow: remove git `autocrlf=false` setup on windows
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-07-03 13:43:07 +02:00
Laura Brehm e2361a5ca8
Merge pull request #5218 from vvoland/update-go
update to go1.21.12
2024-07-03 11:03:40 +01:00
Paweł Gronowski d73d7d4ed3
update to go1.21.12
- https://github.com/golang/go/issues?q=milestone%3AGo1.21.12+label%3ACherryPickApproved
- full diff: https://github.com/golang/go/compare/go1.21.11...go1.21.12

These minor releases include 1 security fixes following the security policy:

net/http: denial of service due to improper 100-continue handling

The net/http HTTP/1.1 client mishandled the case where a server responds to a request with an "Expect: 100-continue" header with a non-informational (200 or higher) status. This mishandling could leave a client connection in an invalid state, where the next request sent on the connection will fail.

An attacker sending a request to a net/http/httputil.ReverseProxy proxy can exploit this mishandling to cause a denial of service by sending "Expect: 100-continue" requests which elicit a non-informational response from the backend. Each such request leaves the proxy with an invalid connection, and causes one subsequent request using that connection to fail.

Thanks to Geoff Franks for reporting this issue.

This is CVE-2024-24791 and Go issue https://go.dev/issue/67555.
View the release notes for more information:
https://go.dev/doc/devel/release#go1.21.12

**- Description for the changelog**

```markdown changelog
Update Go runtime to 1.21.12
```

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-07-03 10:59:37 +02:00
David Karlsson e91f0ded9c docs: make buildx build the canonical reference doc
Move common flag descriptions to the buildx build reference, and make
that page the canonical page in docs. Also rewrite some content in
image_build to make clear that this page is only for the legacy builder.

Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-07-03 08:55:16 +02:00
Alano Terblanche c15ade0c64
fix: ctx cancellation on login prompt
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-07-02 12:07:16 +02:00
Alano Terblanche 2bd4e95bf1
feat: force lf line endings by default
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
2024-07-02 11:53:42 +02:00
Paweł Gronowski 03409219af
Merge pull request #5213 from thaJeztah/vendor_sortorder_v1.1.0
vendor: github.com/fvbommel/sortorder v1.1.0
2024-07-01 17:20:24 +02:00
Sebastiaan van Stijn cd982b111a
Merge pull request #5212 from thaJeztah/fix_stack_sorting
cli/command/stack: fix faulty sort for sorting stacks
2024-07-01 15:08:04 +02:00
Paweł Gronowski ab2373a18e
Merge pull request #5207 from thaJeztah/bump_engine_27.0.3
vendor: github.com/docker/docker v27.0.3
2024-07-01 13:41:34 +02:00
Sebastiaan van Stijn be14edca2a
cli/command/stack: fix faulty sort for sorting stacks
This code was updated in 7b9580df51, which
removed support for using kubernetes as orchestrator, but in doing so
made this `sort.Slice` (probably) not do what it was expected to do ':)

    index 412cc2e5ee86..861ae1be2fb9 100644
    @@ -75,8 +54,7 @@ func format(dockerCli command.Cli, opts options.List, orchestrator command.Orche
        }
        sort.Slice(stacks, func(i, j int) bool {
            return sortorder.NaturalLess(stacks[i].Name, stacks[j].Name) ||
    -            !sortorder.NaturalLess(stacks[j].Name, stacks[i].Name) &&
    -            sortorder.NaturalLess(stacks[j].Namespace, stacks[i].Namespace)
    +            !sortorder.NaturalLess(stacks[j].Name, stacks[i].Name)
        })
        return formatter.StackWrite(stackCtx, stacks)
     }

The extra condition was added in 84241cc393
to support multiple namespaces. This patch removes it, bringing it back to
the state it was before that commit.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-01 13:19:37 +02:00
Sebastiaan van Stijn 0f6370c94b
vendor: github.com/fvbommel/sortorder v1.1.0
- Add a case-folding version of Natural sort order
  This can be used to perform case-insensitive comparisons and sorting.
  It's been placed in a separate sub-package because it requires the Unicode
  tables in the standard library, which can add significantly to binary size.

full diff: https://github.com/fvbommel/sortorder/compare/v1.0.2...v1.1.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-01 13:10:44 +02:00
Sebastiaan van Stijn 2e6aaf05d4
vendor: github.com/docker/docker v27.0.3
full diff: https://github.com/docker/docker/compare/v27.0.2...v27.0.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-01 12:28:52 +02:00
Laura Brehm 4270341cad
Merge pull request #5205 from thaJeztah/docker_27.0.2
vendor: github.com/docker/docker v27.0.2
2024-06-28 15:56:18 +01:00
Sebastiaan van Stijn 9455d61768
vendor: github.com/docker/docker v27.0.2
no diff, as it's the same commit tagged: https://github.com/docker/docker/compare/e953d76450b6...v27.0.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-28 09:06:28 +02:00
Paweł Gronowski 1382fbe61e
vendor: github.com/docker/docker v27.0.2-dev (e953d76450b6)
full diff: 861fde8cc9...e953d76450

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
(cherry picked from commit c97e8091a6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-28 09:01:39 +02:00
Paweł Gronowski ab0898ee32
vendor: github.com/docker/docker v27.0.2-dev (861fde8cc974)
full diff: https://github.com/docker/docker/compare/v27.0.1...861fde8cc974

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
(cherry picked from commit 8945848025)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-28 09:01:01 +02:00
Paweł Gronowski cfec21f28b
vendor: github.com/docker/docker v27.0.1
no change in vendored files, just changing a tag

full diff: https://github.com/docker/docker/compare/ff1e2c0de72a...v27.0.1

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
(cherry picked from commit bf1a701820)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-28 08:59:48 +02:00
Sebastiaan van Stijn 01dd6ab6c6
Merge pull request #5191 from vvoland/dind-test-versions
gha/e2e: Update latest version to 27.0
2024-06-26 15:36:10 +02:00
Sebastiaan van Stijn 1996259c78
Merge pull request #5196 from thaJeztah/carry_fix_custom_ports
cli/config/credentials: ConvertToHostname: handle IP-addresses
2024-06-26 15:09:11 +02:00
Sebastiaan van Stijn 8b0a7b025d
cli/config/credentials: ConvertToHostname: handle IP-addresses
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-26 13:43:02 +02:00
Paweł Gronowski 94e9aa6891
Merge pull request #5195 from CarstonSchilds/master
re-introduced support for port numbers in docker registry URL
2024-06-26 13:42:05 +02:00
Carston Schilds 2380481609 re-introduced support for port numbers in docker registry URL
Signed-off-by: Carston Schilds <Carston.Schilds@visier.com>
2024-06-25 15:36:31 -07:00
Paweł Gronowski ffb842597a
Merge pull request #5189 from thaJeztah/bump_golangci_lint
update golangci-lint to v1.59.1
2024-06-25 14:44:52 +02:00
Paweł Gronowski 60775b6150
gha/e2e: Update latest version to 27.0
27.0 is out - update the latest version used for e2e and drop the 25.0

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2024-06-25 14:43:31 +02:00
Sebastiaan van Stijn b5d1b4de1a
update golangci-lint to v1.59.1
full diff: https://github.com/golangci/golangci-lint/compare/v1.59.0...v1.59.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-24 16:42:42 +02:00
Tianon Gravi ce639151e0 Merge pull request #47109 from whalelines/git-url-regex
Fix isGitURL regular expression
2024-01-18 14:02:57 -08:00
David Dooling 52c62bd13b Fix isGitURL regular expression
Escape period (.) so regular expression does not match any character before "git".

Signed-off-by: David Dooling <david.dooling@docker.com>
2024-01-18 14:14:08 -06:00
Sebastiaan van Stijn 8f865184a6 builder/remotecontext: format code with gofumpt
Formatting the code with https://github.com/mvdan/gofumpt

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2023-06-29 00:25:21 +02:00
Tianon Gravi ee957e144b Merge pull request #44381 from thaJeztah/strings_cut
Replace uses of `strings.Split(N)` with `strings.Cut()`
2022-12-21 09:16:05 -08:00
Sebastiaan van Stijn 6291744fa4 builder/remotecontext/git: use strings.Cut()
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-12-21 11:09:00 +01:00
Sebastiaan van Stijn 60b326f814 builder/remotecontext/gitutils: switch back to os/exec
This is a partial revert of 389ada7188, which
switched from os/exec to the golang.org/x/sys/execabs package to mitigate
security issues (mainly on Windows) with lookups resolving to binaries in the
current directory.

from the go1.19 release notes https://go.dev/doc/go1.19#os-exec-path

> ## PATH lookups
>
> Command and LookPath no longer allow results from a PATH search to be found
> relative to the current directory. This removes a common source of security
> problems but may also break existing programs that depend on using, say,
> exec.Command("prog") to run a binary named prog (or, on Windows, prog.exe) in
> the current directory. See the os/exec package documentation for information
> about how best to update such programs.
>
> On Windows, Command and LookPath now respect the NoDefaultCurrentDirectoryInExePath
> environment variable, making it possible to disable the default implicit search
> of “.” in PATH lookups on Windows systems.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-11-09 12:28:17 +01:00
Sebastiaan van Stijn aa6ad06304 Merge pull request #44344 from thaJeztah/go1.18_compat
builder/remotecontext/git: allow building on go1.18
2022-10-21 19:38:54 +02:00
Sebastiaan van Stijn 66713384c3 builder/remotecontext/git: allow building on go1.18
cmd.Environ() is new in go1.19, and not needed for this specific case.
Without this, trying to use this package in code that uses go1.18 will fail;

    builder/remotecontext/git/gitutils.go:216:23: cmd.Environ undefined (type *exec.Cmd has no field or method Environ)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-10-21 17:41:41 +02:00
Cory Snider 5c21ec520e builder: add missing doc comment
Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-10-20 16:47:18 -04:00
Cory Snider 212213e81e builder: fix running git commands on Windows
Setting cmd.Env overrides the default of passing through the parent
process' environment, which works out fine most of the time, except when
it doesn't. For whatever reason, leaving out all the environment causes
git-for-windows sh.exe subprocesses to enter an infinite loop of
access violations during Cygwin initialization in certain environments
(specifically, our very own dev container image).

Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-10-20 16:47:18 -04:00
Cory Snider bcd6c45731 builder: make git config isolation opt-in
While it is undesirable for the system or user git config to be used
when the daemon clones a Git repo, it could break workflows if it was
unconditionally applied to docker/cli as well.

Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-10-20 16:47:18 -04:00
Cory Snider 876fc1dac4 builder: isolate git from local system
Prevent git commands we run from reading the user or system
configuration, or cloning submodules from the local filesystem.

Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-10-20 16:47:18 -04:00
Cory Snider 3bfb30acd7 builder: explicitly set CWD for all git commands
Keep It Simple! Set the working directory for git commands by...setting
the git process's working directory. Git commands can be run in the
parent process's working directory by passing the empty string.

Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-10-20 16:47:18 -04:00
Cory Snider 3f4cc89f64 builder: modernize TestCheckoutGit
Make the test more debuggable by logging all git command output and
running each table-driven test case as a subtest.

Signed-off-by: Cory Snider <csnider@mirantis.com>
2022-10-20 16:47:18 -04:00
Sebastiaan van Stijn a12090d787 gofmt GoDoc comments with go1.19
Older versions of Go don't format comments, so committing this as
a separate commit, so that we can already make these changes before
we upgrade to Go 1.19.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-07-08 19:56:23 +02:00
Sebastiaan van Stijn f1b0ef127d Merge pull request #43477 from thaJeztah/deprecate_urlutil
pkg/urlutil: deprecate, and move to builder/remotecontext/urlutil
2022-04-13 17:16:15 +02:00
Sebastiaan van Stijn 26a11366a7 builder/remotecontext/urlutil: simplify and improve documentation
Simplify some of the logic, and add documentation about the package,
as well as warnings that this package should not be used as a general-
purpose utility.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-04-12 19:58:09 +02:00
Sebastiaan van Stijn 9e39630a05 pkg/urlutil: deprecate, and move to builder/remotecontext/urlutil
pkg/urlutil (despite its poorly chosen name) is not really intended as a generic
utility to handle URLs, and should only be used by the builder to handle (remote)
build contexts.

- IsURL() only does a very rudimentary check for http(s):// prefixes, without any
  other validation, but due to its name may give incorrect expectations.
- IsGitURL() is written specifically with docker build remote git contexts in
  mind, and has handling for backward-compatibility, where strings that are
  not URLs, but start with "github.com/" are accepted.

Because of the above, this patch:

- moves the package inside builder/remotecontext, close to where it's intended
  to be used (ideally this would be part of build/remotecontext itself, but this
  package imports many other dependencies, which would introduce those as extra
  dependencies in the CLI).
- deprecates pkg/urlutil, but adds aliases as there are some external consumers.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-04-12 19:58:05 +02:00
Eng Zer Jun 6d2a901118 refactor: move from io/ioutil to io and os package
The io/ioutil package has been deprecated in Go 1.16. This commit
replaces the existing io/ioutil functions with their new definitions in
io and os packages.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2021-08-27 14:56:57 +08:00
Tibor Vass 389ada7188 Use golang.org/x/sys/execabs
Signed-off-by: Tibor Vass <tibor@docker.com>
2021-01-25 19:13:12 +00:00
Tibor Vass 613477b489 Merge pull request #41606 from thaJeztah/moby_sys_symlink
replace pkg/symlink with github.com/moby/sys/symlink
2020-11-03 09:58:08 -08:00
Sebastiaan van Stijn a4c8c72411 replace pkg/symlink with github.com/moby/sys/symlink
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2020-11-03 11:17:12 +01:00
Sebastiaan van Stijn 5896d383ca bump gotest.tools v3.0.1 for compatibility with Go 1.14
full diff: https://github.com/gotestyourself/gotest.tools/compare/v2.3.0...v3.0.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2020-02-11 00:06:42 +01:00
Sebastiaan van Stijn ea850377cd builder/remotecontext: allow ssh:// urls for remote context
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2019-12-05 21:22:49 +01:00
Sebastiaan van Stijn 2d0d4ce4af builder/remotecontext: use net/url instead of urlutil
urlutil.IsUrl() was merely checking if the url had a http(s)://
prefix, which is just as well handled through using url.Parse()

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2019-11-05 18:04:01 -08:00
Sebastiaan van Stijn a0d9b0cf0d TestParseRemoteURL: use subtests
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2019-11-05 14:00:18 -08:00
Yong Tang b3d0327781 Merge pull request #39668 from thaJeztah/replace_gometalinter
Replace gometalinter with golangci-lint
2019-09-18 07:30:18 -07:00
Sebastiaan van Stijn 70aef9f502 gosec: add ignore comments for reported issues that can be ignored
```
builder/remotecontext/remote.go:48:        G107: Potential HTTP request made with variable url (gosec)
builder/remotecontext/git/gitutils.go:145: G107: Potential HTTP request made with variable url (gosec)
builder/remotecontext/git/gitutils.go:147: G107: Potential HTTP request made with variable url (gosec)
pkg/fileutils/fileutils_test.go:185:       G303: File creation in shared tmp directory without using ioutil.Tempfile (gosec)
pkg/tarsum/tarsum_test.go:7:               G501: Blacklisted import `crypto/md5`: weak cryptographic primitive (gosec)
pkg/tarsum/tarsum_test.go:9:               G505: Blacklisted import `crypto/sha1`: weak cryptographic primitive (gosec)
```

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2019-09-18 12:57:43 +02:00
Sebastiaan van Stijn 80dd489f21 Merge pull request #38944 from andrewhsu/gitutils
gitutils: add validation for ref
2019-03-27 02:03:47 +01:00
Tonis Tiigi 04e2a24a9e gitutils: add validation for ref
Signed-off-by: Tonis Tiigi <tonistiigi@gmail.com>
(cherry picked from commit 723b107ca4fba14580a6cd971e63d8af2e7d2bbe)
Signed-off-by: Andrew Hsu <andrewhsu@docker.com>
2019-03-26 22:05:46 +00:00
Vincent Demeester 84c375f430 Merge pull request #37243 from vdemeester/gotestyourself-with-tools
Update gotestyourself to gotest.tools
2018-06-13 16:23:26 +02:00
Vincent Demeester 71672ece9c Update tests to use gotest.tools 👼
Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2018-06-13 09:04:30 +02:00
Daniel Nephin db857b5d9c Post migration assertion fixes
Signed-off-by: Daniel Nephin <dnephin@docker.com>
2018-03-16 11:03:46 -04:00
Daniel Nephin 242f176825 Automated migration using
gty-migrate-from-testify --ignore-build-tags

Signed-off-by: Daniel Nephin <dnephin@docker.com>
2018-03-16 11:03:43 -04:00
Daniel Nephin 6ea4877cff Add canonical import comment
Signed-off-by: Daniel Nephin <dnephin@docker.com>
2018-02-05 16:51:57 -05:00
Tonis Tiigi 7bc503344a gitutils: remove checkout directory on error
Signed-off-by: Tonis Tiigi <tonistiigi@gmail.com>
2017-12-08 11:58:13 -08:00
Tonis Tiigi e2cc22d076 gitutils: fix checking out submodules
Signed-off-by: Tonis Tiigi <tonistiigi@gmail.com>
2017-12-07 14:25:19 -08:00
Andrew He e9831d75e2 Fix shallow git clone in docker-build
If the HEAD request fails, use a GET request to properly test if git
server is smart-http.

Signed-off-by: Andrew He <he.andrew.mail@gmail.com>
2017-07-25 13:20:59 -07:00
Sebastiaan van Stijn 9450481b7e Move IsGitTransport() to gitutils
This function was only used inside gitutils,
and is written specifically for the requirements
there.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2017-06-26 10:07:04 -07:00
Sebastiaan van Stijn a6cc6cd878 Fix handling of remote "git@" notation
`docker build` accepts remote repositories
using either the `git://` notation, or `git@`.

Docker attempted to parse both as an URL, however,
`git@` is not an URL, but an argument to `git clone`.

Go 1.7 silently ignored this, and managed to
extract the needed information from these
remotes, however, Go 1.8 does a more strict
validation, and invalidated these.

This patch adds a different path for `git@` remotes,
to prevent them from being handled as URL (and
invalidated).

A test is also added, because there were no
tests for handling of `git@` remotes.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2017-06-26 10:02:12 -07:00
Daniel Nephin e907d54fe6 Move pkg/gitutils to remotecontext/git
Signed-off-by: Daniel Nephin <dnephin@docker.com>
2017-06-02 16:54:50 -04:00
2282 changed files with 118681 additions and 65326 deletions

View File

@ -1,6 +1,6 @@
/build/
/cli/winresources/versioninfo.json
/cli/winresources/*.syso
/cmd/docker/winresources/versioninfo.json
/cmd/docker/winresources/*.syso
/man/man*/
/man/vendor/
/man/go.sum

11
.gitattributes vendored
View File

@ -1,3 +1,14 @@
* text=auto
Dockerfile* linguist-language=Dockerfile
vendor.mod linguist-language=Go-Module
vendor.sum linguist-language=Go-Checksums
*.go -text diff=golang
# scripts directory contains shell scripts
# without extensions, so we need to force
scripts/** text=auto eol=lf
# shell scripts should always have LF
*.sh text eol=lf

View File

@ -19,11 +19,14 @@ Provide the following information:
**- How to verify it**
**- Description for the changelog**
**- Human readable description for the release notes**
<!--
Write a short (one line) summary that describes the changes in this
pull request for inclusion in the changelog.
It must be placed inside the below triple backticks section:
It must be placed inside the below triple backticks section.
NOTE: Only fill this section if changes introduced in this PR are user-facing.
The PR must have a relevant impact/ label.
-->
```markdown changelog

View File

@ -1,5 +1,14 @@
name: build
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
@ -13,6 +22,7 @@ on:
branches:
- 'master'
- '[0-9]+.[0-9]+'
- '[0-9]+.x'
tags:
- 'v*'
pull_request:
@ -51,17 +61,12 @@ jobs:
- ""
- glibc
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Build
uses: docker/bake-action@v5
uses: docker/bake-action@v6
with:
targets: ${{ matrix.target }}
set: |
@ -94,8 +99,12 @@ jobs:
if: ${{ github.event_name != 'pull_request' && github.repository == 'docker/cli' }}
steps:
-
name: Checkout
uses: actions/checkout@v4
name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_CLIBIN_USERNAME }}
password: ${{ secrets.DOCKERHUB_CLIBIN_TOKEN }}
-
name: Set up QEMU
uses: docker/setup-qemu-action@v3
@ -112,21 +121,15 @@ jobs:
type=semver,pattern={{version}}
type=ref,event=branch
type=ref,event=pr
type=sha
-
name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_CLIBIN_USERNAME }}
password: ${{ secrets.DOCKERHUB_CLIBIN_TOKEN }}
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
-
name: Build and push image
uses: docker/bake-action@v5
uses: docker/bake-action@v6
with:
files: |
./docker-bake.hcl
${{ steps.meta.outputs.bake-file }}
cwd://${{ steps.meta.outputs.bake-file }}
targets: bin-image-cross
push: ${{ github.event_name != 'pull_request' }}
set: |
@ -160,15 +163,12 @@ jobs:
matrix:
platform: ${{ fromJson(needs.prepare-plugins.outputs.matrix) }}
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Build
uses: docker/bake-action@v5
uses: docker/bake-action@v6
with:
targets: plugins-cross
set: |

View File

@ -1,15 +1,25 @@
name: codeql
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
on:
push:
branches:
- 'master'
- '[0-9]+.[0-9]+'
tags:
- 'v*'
branches:
- 'master'
- '[0-9]+.[0-9]+'
- '[0-9]+.x'
tags:
- 'v*'
pull_request:
# The branches below must be a subset of the branches above
branches: [ "master" ]
branches: ["master"]
schedule:
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
@ -24,26 +34,21 @@ on:
jobs:
codeql:
runs-on: 'ubuntu-latest'
timeout-minutes: 360
runs-on: ubuntu-24.04
timeout-minutes: 10
env:
DISABLE_WARN_OUTSIDE_CONTAINER: '1'
permissions:
actions: read
contents: read
security-events: write
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2
-
name: Checkout HEAD on PR
if: ${{ github.event_name == 'pull_request' }}
run: |
git checkout HEAD^2
# CodeQL 2.16.4's auto-build added support for multi-module repositories,
# and is trying to be smart by searching for modules in every directory,
# including vendor directories. If no module is found, it's creating one
@ -58,7 +63,7 @@ jobs:
name: Update Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
go-version: "1.24.5"
-
name: Initialize CodeQL
uses: github/codeql-action/init@v3

View File

@ -1,5 +1,14 @@
name: e2e
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
@ -10,30 +19,28 @@ on:
branches:
- 'master'
- '[0-9]+.[0-9]+'
- '[0-9]+.x'
tags:
- 'v*'
pull_request:
jobs:
e2e:
tests:
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
target:
- non-experimental
- experimental
- local
- connhelper-ssh
base:
- alpine
- debian
engine-version:
- 27-rc # testing
- 26.1 # latest
- 25.0 # latest - 1
- 23.0 # mirantis lts
# TODO(krissetto) 19.03 needs a look, doesn't work ubuntu 22.04 (cgroup errors).
# we could have a separate job that tests it against ubuntu 20.04
- 28 # latest
- 27 # latest - 1
- 26 # github actions default
- 23 # mirantis lts
steps:
-
name: Checkout
@ -67,7 +74,7 @@ jobs:
TESTFLAGS: -coverprofile=/tmp/coverage/coverage.txt
-
name: Send to Codecov
uses: codecov/codecov-action@v4
uses: codecov/codecov-action@v5
with:
file: ./build/coverage/coverage.txt
files: ./build/coverage/coverage.txt
token: ${{ secrets.CODECOV_TOKEN }}

View File

@ -1,5 +1,14 @@
name: test
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
@ -10,6 +19,7 @@ on:
branches:
- 'master'
- '[0-9]+.[0-9]+'
- '[0-9]+.x'
tags:
- 'v*'
pull_request:
@ -18,22 +28,19 @@ jobs:
ctn:
runs-on: ubuntu-24.04
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Test
uses: docker/bake-action@v5
uses: docker/bake-action@v6
with:
targets: test-coverage
-
name: Send to Codecov
uses: codecov/codecov-action@v4
uses: codecov/codecov-action@v5
with:
file: ./build/coverage/coverage.txt
files: ./build/coverage/coverage.txt
token: ${{ secrets.CODECOV_TOKEN }}
host:
@ -46,15 +53,10 @@ jobs:
fail-fast: false
matrix:
os:
- macos-12
- macos-13 # macOS 13 on Intel
- macos-14 # macOS 14 on arm64 (Apple Silicon M1)
# - windows-2022 # FIXME: some tests are failing on the Windows runner, as well as on Appveyor since June 24, 2018: https://ci.appveyor.com/project/docker/cli/history
steps:
-
name: Prepare git
if: matrix.os == 'windows-latest'
run: |
git config --system core.autocrlf false
git config --system core.eol lf
-
name: Checkout
uses: actions/checkout@v4
@ -64,7 +66,7 @@ jobs:
name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.21.11
go-version: "1.24.5"
-
name: Test
run: |
@ -74,8 +76,8 @@ jobs:
shell: bash
-
name: Send to Codecov
uses: codecov/codecov-action@v4
uses: codecov/codecov-action@v5
with:
file: /tmp/coverage.txt
files: /tmp/coverage.txt
working-directory: ${{ env.GOPATH }}/src/github.com/docker/cli
token: ${{ secrets.CODECOV_TOKEN }}

View File

@ -1,12 +1,22 @@
name: validate-pr
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
on:
pull_request:
types: [opened, edited, labeled, unlabeled]
jobs:
check-area-label:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
timeout-minutes: 120 # guardrails timeout for the whole job
steps:
- name: Missing `area/` label
if: contains(join(github.event.pull_request.labels.*.name, ','), 'impact/') && !contains(join(github.event.pull_request.labels.*.name, ','), 'area/')
@ -17,9 +27,10 @@ jobs:
run: exit 0
check-changelog:
if: contains(join(github.event.pull_request.labels.*.name, ','), 'impact/')
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
timeout-minutes: 120 # guardrails timeout for the whole job
env:
HAS_IMPACT_LABEL: ${{ contains(join(github.event.pull_request.labels.*.name, ','), 'impact/') }}
PR_BODY: |
${{ github.event.pull_request.body }}
steps:
@ -31,32 +42,47 @@ jobs:
# Strip empty lines
desc=$(echo "$block" | awk NF)
if [ -z "$desc" ]; then
echo "::error::Changelog section is empty. Provide a description for the changelog."
exit 1
fi
if [ "$HAS_IMPACT_LABEL" = "true" ]; then
if [ -z "$desc" ]; then
echo "::error::Changelog section is empty. Please provide a description for the changelog."
exit 1
fi
len=$(echo -n "$desc" | wc -c)
if [[ $len -le 6 ]]; then
echo "::error::Description looks too short: $desc"
exit 1
len=$(echo -n "$desc" | wc -c)
if [[ $len -le 6 ]]; then
echo "::error::Description looks too short: $desc"
exit 1
fi
else
if [ -n "$desc" ]; then
echo "::error::PR has a changelog description, but no changelog label"
echo "::error::Please add the relevant 'impact/' label to the PR or remove the changelog description"
exit 1
fi
fi
echo "This PR will be included in the release notes with the following note:"
echo "$desc"
check-pr-branch:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
timeout-minutes: 120 # guardrails timeout for the whole job
env:
PR_TITLE: ${{ github.event.pull_request.title }}
steps:
# Backports or PR that target a release branch directly should mention the target branch in the title, for example:
# [X.Y backport] Some change that needs backporting to X.Y
# [X.Y] Change directly targeting the X.Y branch
- name: Get branch from PR title
id: title_branch
run: echo "$PR_TITLE" | sed -n 's/^\[\([0-9]*\.[0-9]*\)[^]]*\].*/branch=\1/p' >> $GITHUB_OUTPUT
- name: Check release branch
if: github.event.pull_request.base.ref != steps.title_branch.outputs.branch && !(github.event.pull_request.base.ref == 'master' && steps.title_branch.outputs.branch == '')
run: echo "::error::PR title suggests targetting the ${{ steps.title_branch.outputs.branch }} branch, but is opened against ${{ github.event.pull_request.base.ref }}" && exit 1
id: title_branch
run: |
# get the intended major version prefix ("[27.1 backport]" -> "27.") from the PR title.
[[ "$PR_TITLE" =~ ^\[([0-9]*\.)[^]]*\] ]] && branch="${BASH_REMATCH[1]}"
# get major version prefix from the release branch ("27.x -> "27.")
[[ "$GITHUB_BASE_REF" =~ ^([0-9]*\.) ]] && target_branch="${BASH_REMATCH[1]}" || target_branch="$GITHUB_BASE_REF"
if [[ "$target_branch" != "$branch" ]] && ! [[ "$GITHUB_BASE_REF" == "master" && "$branch" == "" ]]; then
echo "::error::PR is opened against the $GITHUB_BASE_REF branch, but its title suggests otherwise."
exit 1
fi

View File

@ -1,5 +1,14 @@
name: validate
# Default to 'contents: read', which grants actions to read commits.
#
# If any permission is set, any permission not included in the list is
# implicitly set to "none".
#
# see https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
@ -10,6 +19,7 @@ on:
branches:
- 'master'
- '[0-9]+.[0-9]+'
- '[0-9]+.x'
tags:
- 'v*'
pull_request:
@ -26,12 +36,9 @@ jobs:
- validate-vendor
- update-authors # ensure authors update target runs fine
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Run
uses: docker/bake-action@v5
uses: docker/bake-action@v6
with:
targets: ${{ matrix.target }}

4
.gitignore vendored
View File

@ -8,8 +8,8 @@
Thumbs.db
.editorconfig
/build/
/cli/winresources/versioninfo.json
/cli/winresources/*.syso
/cmd/docker/winresources/versioninfo.json
/cmd/docker/winresources/*.syso
profile.out
# top-level go.mod is not meant to be checked in

View File

@ -1,187 +1,226 @@
linters:
version: "2"
run:
# prevent golangci-lint from deducting the go version to lint for through go.mod,
# which causes it to fallback to go1.17 semantics.
#
# TODO(thaJeztah): update "usetesting" settings to enable go1.24 features once our minimum version is go1.24
go: "1.24.5"
timeout: 5m
issues:
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0
formatters:
enable:
- bodyclose
- depguard
- dogsled
- dupword # Detects duplicate words.
- durationcheck
- errchkjson
- exportloopref # Detects pointers to enclosing loop variables.
- gocritic # Metalinter; detects bugs, performance, and styling issues.
- gocyclo
- gofumpt # Detects whether code was gofumpt-ed.
- goimports
- gosec # Detects security problems.
- gosimple
exclusions:
generated: strict
linters:
enable:
- asasalint # Detects "[]any" used as argument for variadic "func(...any)".
- bodyclose
- copyloopvar # Detects places where loop variables are copied.
- depguard
- dogsled # Detects assignments with too many blank identifiers.
- dupword # Detects duplicate words.
- durationcheck # Detect cases where two time.Duration values are being multiplied in possibly erroneous ways.
- errcheck
- errchkjson # Detects unsupported types passed to json encoding functions and reports if checks for the returned error can be omitted.
- exhaustive # Detects missing options in enum switch statements.
- exptostd # Detects functions from golang.org/x/exp/ that can be replaced by std functions.
- fatcontext # Detects nested contexts in loops and function literals.
- forbidigo
- gocheckcompilerdirectives # Detects invalid go compiler directive comments (//go:).
- gocritic # Metalinter; detects bugs, performance, and styling issues.
- gocyclo
- gosec # Detects security problems.
- govet
- iface # Detects incorrect use of interfaces. Currently only used for "identical" interfaces in the same package.
- importas # Enforces consistent import aliases.
- ineffassign
- lll
- megacheck
- misspell # Detects commonly misspelled English words in comments.
- nakedret
- nilerr # Detects code that returns nil even if it checks that the error is not nil.
- nolintlint # Detects ill-formed or insufficient nolint directives.
- perfsprint # Detects fmt.Sprintf uses that can be replaced with a faster alternative.
- prealloc # Detects slice declarations that could potentially be pre-allocated.
- predeclared # Detects code that shadows one of Go's predeclared identifiers
- reassign
- revive # Metalinter; drop-in replacement for golint.
- makezero # Finds slice declarations with non-zero initial length.
- mirror # Detects wrong mirror patterns of bytes/strings usage.
- misspell # Detects commonly misspelled English words in comments.
- nakedret # Detects uses of naked returns.
- nilnesserr # Detects returning nil errors. It combines the features of nilness and nilerr,
- nosprintfhostport # Detects misuse of Sprintf to construct a host with port in a URL.
- nolintlint # Detects ill-formed or insufficient nolint directives.
- perfsprint # Detects fmt.Sprintf uses that can be replaced with a faster alternative.
- prealloc # Detects slice declarations that could potentially be pre-allocated.
- predeclared # Detects code that shadows one of Go's predeclared identifiers
- reassign # Detects reassigning a top-level variable in another package.
- revive # Metalinter; drop-in replacement for golint.
- spancheck # Detects mistakes with OpenTelemetry/Census spans.
- staticcheck
- stylecheck # Replacement for golint
- tenv # Detects using os.Setenv instead of t.Setenv.
- thelper # Detects test helpers without t.Helper().
- tparallel # Detects inappropriate usage of t.Parallel().
- typecheck
- unconvert # Detects unnecessary type conversions.
- thelper # Detects test helpers without t.Helper().
- tparallel # Detects inappropriate usage of t.Parallel().
- unconvert # Detects unnecessary type conversions.
- unparam
- unused
- usestdlibvars
- vet
- wastedassign
- usestdlibvars # Detects the possibility to use variables/constants from the Go standard library.
- usetesting # Reports uses of functions with replacement inside the testing package.
- wastedassign # Detects wasted assignment statements.
disable:
- errcheck
run:
timeout: 5m
settings:
depguard:
rules:
main:
deny:
- pkg: "github.com/containerd/containerd/errdefs"
desc: The containerd errdefs package was migrated to a separate module. Use github.com/containerd/errdefs instead.
- pkg: "github.com/containerd/containerd/log"
desc: The containerd log package was migrated to a separate module. Use github.com/containerd/log instead.
- pkg: "github.com/containerd/containerd/pkg/userns"
desc: Use github.com/moby/sys/userns instead.
- pkg: "github.com/containerd/containerd/platforms"
desc: The containerd platforms package was migrated to a separate module. Use github.com/containerd/platforms instead.
- pkg: "github.com/docker/docker/pkg/system"
desc: This package should not be used unless strictly necessary.
- pkg: "github.com/docker/distribution/uuid"
desc: Use github.com/google/uuid instead.
- pkg: "io/ioutil"
desc: The io/ioutil package has been deprecated, see https://go.dev/doc/go1.16#ioutil
linters-settings:
depguard:
rules:
main:
deny:
- pkg: io/ioutil
desc: The io/ioutil package has been deprecated, see https://go.dev/doc/go1.16#ioutil
gocyclo:
min-complexity: 16
govet:
enable:
- shadow
settings:
shadow:
strict: true
lll:
line-length: 200
nakedret:
command: nakedret
pattern: ^(?P<path>.*?\\.go):(?P<line>\\d+)\\s*(?P<message>.*)$
forbidigo:
forbid:
- pkg: ^regexp$
pattern: ^regexp\.MustCompile
msg: Use internal/lazyregexp.New instead.
revive:
rules:
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#import-shadowing
- name: import-shadowing
severity: warning
disabled: false
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-block
- name: empty-block
severity: warning
disabled: false
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-lines
- name: empty-lines
severity: warning
disabled: false
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#use-any
- name: use-any
severity: warning
disabled: false
gocyclo:
min-complexity: 16
issues:
# The default exclusion rules are a bit too permissive, so copying the relevant ones below
exclude-use-default: false
gosec:
excludes:
- G104 # G104: Errors unhandled; (TODO: reduce unhandled errors, or explicitly ignore)
- G115 # G115: integer overflow conversion; (TODO: verify these: https://github.com/docker/cli/issues/5584)
- G306 # G306: Expect WriteFile permissions to be 0600 or less (too restrictive; also flags "0o644" permissions)
- G307 # G307: Deferring unsafe method "*os.File" on type "Close" (also EXC0008); (TODO: evaluate these and fix where needed: G307: Deferring unsafe method "*os.File" on type "Close")
exclude:
- parameter .* always receives
govet:
enable:
- shadow
settings:
shadow:
strict: true
exclude-files:
- cli/compose/schema/bindata.go
- .*generated.*
lll:
line-length: 200
exclude-rules:
# We prefer to use an "exclude-list" so that new "default" exclusions are not
importas:
# Do not allow unaliased imports of aliased packages.
no-unaliased: true
alias:
# Enforce alias to prevent it accidentally being used instead of our
# own errdefs package (or vice-versa).
- pkg: github.com/containerd/errdefs
alias: cerrdefs
- pkg: github.com/opencontainers/image-spec/specs-go/v1
alias: ocispec
# Enforce that gotest.tools/v3/assert/cmp is always aliased as "is"
- pkg: gotest.tools/v3/assert/cmp
alias: is
nakedret:
# Disallow naked returns if func has more lines of code than this setting.
# Default: 30
max-func-lines: 0
staticcheck:
checks:
- all
- -QF1008 # Omit embedded fields from selector expression; https://staticcheck.dev/docs/checks/#QF1008
revive:
rules:
- name: empty-block # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-block
- name: empty-lines # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-lines
- name: import-shadowing # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#import-shadowing
- name: line-length-limit # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#line-length-limit
arguments: [200]
- name: unused-receiver # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-receiver
- name: use-any # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#use-any
usetesting:
os-chdir: false # FIXME(thaJeztah): Disable `os.Chdir()` detections; should be automatically disabled on Go < 1.24; see https://github.com/docker/cli/pull/5835#issuecomment-2665302478
context-background: false # FIXME(thaJeztah): Disable `context.Background()` detections; should be automatically disabled on Go < 1.24; see https://github.com/docker/cli/pull/5835#issuecomment-2665302478
context-todo: false # FIXME(thaJeztah): Disable `context.TODO()` detections; should be automatically disabled on Go < 1.24; see https://github.com/docker/cli/pull/5835#issuecomment-2665302478
exclusions:
# We prefer to use an "linters.exclusions.rules" so that new "default" exclusions are not
# automatically inherited. We can decide whether or not to follow upstream
# defaults when updating golang-ci-lint versions.
# Unfortunately, this means we have to copy the whole exclusion pattern, as
# (unlike the "include" option), the "exclude" option does not take exclusion
# ID's.
#
# These exclusion patterns are copied from the default excluses at:
# https://github.com/golangci/golangci-lint/blob/v1.44.0/pkg/config/issues.go#L10-L104
# These exclusion patterns are copied from the default excludes at:
# https://github.com/golangci/golangci-lint/blob/v1.61.0/pkg/config/issues.go#L11-L104
#
# The default list of exclusions can be found at:
# https://golangci-lint.run/usage/false-positives/#default-exclusions
generated: strict
# EXC0001
- text: "Error return value of .((os\\.)?std(out|err)\\..*|.*Close|.*Flush|os\\.Remove(All)?|.*print(f|ln)?|os\\.(Un)?Setenv). is not checked"
linters:
- errcheck
# EXC0003
- text: "func name will be used as test\\.Test.* by other packages, and that stutters; consider calling this"
linters:
- revive
# EXC0006
- text: "Use of unsafe calls should be audited"
linters:
- gosec
# EXC0007
- text: "Subprocess launch(ed with variable|ing should be audited)"
linters:
- gosec
# EXC0008
# TODO: evaluate these and fix where needed: G307: Deferring unsafe method "*os.File" on type "Close" (gosec)
- text: "G307"
linters:
- gosec
# EXC0009
- text: "(Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less)"
linters:
- gosec
# EXC0010
- text: "Potential file inclusion via variable"
linters:
- gosec
rules:
# EXC0003
- text: "func name will be used as test\\.Test.* by other packages, and that stutters; consider calling this"
linters:
- revive
# G113 Potential uncontrolled memory consumption in Rat.SetString (CVE-2022-23772)
# only affects gp < 1.16.14. and go < 1.17.7
- text: "G113"
linters:
- gosec
# TODO: G104: Errors unhandled. (gosec)
- text: "G104"
linters:
- gosec
# Looks like the match in "EXC0007" above doesn't catch this one
# TODO: consider upstreaming this to golangci-lint's default exclusion rules
- text: "G204: Subprocess launched with a potential tainted input or cmd arguments"
linters:
- gosec
# Looks like the match in "EXC0009" above doesn't catch this one
# TODO: consider upstreaming this to golangci-lint's default exclusion rules
- text: "G306: Expect WriteFile permissions to be 0600 or less"
linters:
- gosec
# EXC0007
- text: "Subprocess launch(ed with variable|ing should be audited)"
linters:
- gosec
# TODO: make sure all packages have a description. Currently, there's 67 packages without.
- text: "package-comments: should have a package comment"
linters:
- revive
# FIXME temporarily suppress these (see https://github.com/gotestyourself/gotest.tools/issues/272)
- text: "SA1019: (assert|cmp|is)\\.ErrorType is deprecated"
linters:
- staticcheck
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- errcheck
- gosec
- text: "ST1000: at least one file in a package should have a package comment"
linters:
- stylecheck
# EXC0009
- text: "(Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less)"
linters:
- gosec
# Allow "err" and "ok" vars to shadow existing declarations, otherwise we get too many false positives.
- text: '^shadow: declaration of "(err|ok)" shadows declaration'
linters:
- govet
# EXC0010
- text: "Potential file inclusion via variable"
linters:
- gosec
# TODO: make sure all packages have a description. Currently, there's 67 packages without.
- text: "package-comments: should have a package comment"
linters:
- revive
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- errcheck
- gosec
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0
- text: "ST1000: at least one file in a package should have a package comment"
linters:
- staticcheck
# Allow "err" and "ok" vars to shadow existing declarations, otherwise we get too many false positives.
- text: '^shadow: declaration of "(err|ok)" shadows declaration'
linters:
- govet
# Ignore for cli/command/formatter/tabwriter, which is forked from go stdlib, so we want to align with it.
- text: '^(ST1020|ST1022): comment on exported'
path: "cli/command/formatter/tabwriter"
linters:
- staticcheck
# Log a warning if an exclusion rule is unused.
# Default: false
warn-unused: true

View File

@ -43,6 +43,7 @@ Alexis Couvreur <alexiscouvreur.pro@gmail.com>
Alicia Lauerman <alicia@eta.im> <allydevour@me.com>
Allen Sun <allensun.shl@alibaba-inc.com> <allen.sun@daocloud.io>
Allen Sun <allensun.shl@alibaba-inc.com> <shlallen1990@gmail.com>
Allie Sadler <allie.sadler@docker.com>
Andrew Weiss <andrew.weiss@docker.com> <andrew.weiss@microsoft.com>
Andrew Weiss <andrew.weiss@docker.com> <andrew.weiss@outlook.com>
André Martins <aanm90@gmail.com> <martins@noironetworks.com>
@ -65,6 +66,9 @@ Arnaud Porterie <icecrime@gmail.com>
Arnaud Porterie <icecrime@gmail.com> <arnaud.porterie@docker.com>
Arthur Gautier <baloo@gandi.net> <superbaloo+registrations.github@superbaloo.net>
Arthur Peka <arthur.peka@outlook.com> <arthrp@users.noreply.github.com>
Austin Vazquez <austin.vazquez.dev@gmail.com>
Austin Vazquez <austin.vazquez.dev@gmail.com> <55906459+austinvazquez@users.noreply.github.com>
Austin Vazquez <austin.vazquez.dev@gmail.com> <macedonv@amazon.com>
Avi Miller <avi.miller@oracle.com> <avi.miller@gmail.com>
Ben Bonnefoy <frenchben@docker.com>
Ben Golub <ben.golub@dotcloud.com>
@ -195,6 +199,8 @@ Gaetan de Villele <gdevillele@gmail.com>
Gang Qiao <qiaohai8866@gmail.com> <1373319223@qq.com>
George Kontridze <george@bugsnag.com>
Gerwim Feiken <g.feiken@tfe.nl> <gerwim@gmail.com>
Giau. Tran Minh <hello@giautm.dev>
Giau. Tran Minh <hello@giautm.dev> <12751435+giautm@users.noreply.github.com>
Giampaolo Mancini <giampaolo@trampolineup.com>
Gopikannan Venugopalsamy <gopikannan.venugopalsamy@gmail.com>
Gou Rao <gou@portworx.com> <gourao@users.noreply.github.com>
@ -214,6 +220,7 @@ Günther Jungbluth <gunther@gameslabs.net>
Hakan Özler <hakan.ozler@kodcu.com>
Hao Shu Wei <haosw@cn.ibm.com>
Hao Shu Wei <haosw@cn.ibm.com> <haoshuwei1989@163.com>
Harald Albers <github@albersweb.de>
Harald Albers <github@albersweb.de> <albers@users.noreply.github.com>
Harold Cooper <hrldcpr@gmail.com>
Harry Zhang <harryz@hyper.sh> <harryzhang@zju.edu.cn>
@ -330,6 +337,8 @@ Lajos Papp <lajos.papp@sequenceiq.com> <lalyos@yahoo.com>
Lei Jitang <leijitang@huawei.com>
Lei Jitang <leijitang@huawei.com> <leijitang@gmail.com>
Li Fu Bang <lifubang@acmcoder.com>
Li Yi <denverdino@gmail.com>
Li Yi <denverdino@gmail.com> <weiyuan.yl@alibaba-inc.com>
Liang Mingqiang <mqliang.zju@gmail.com>
Liang-Chi Hsieh <viirya@gmail.com>
Liao Qingwei <liaoqingwei@huawei.com>
@ -339,6 +348,7 @@ Lokesh Mandvekar <lsm5@fedoraproject.org> <lsm5@redhat.com>
Lorenzo Fontana <lo@linux.com> <fontanalorenzo@me.com>
Louis Opter <kalessin@kalessin.fr>
Louis Opter <kalessin@kalessin.fr> <louis@dotcloud.com>
Lovekesh Kumar <lovekesh.kumar@rtcamp.com>
Luca Favatella <luca.favatella@erlang-solutions.com> <lucafavatella@users.noreply.github.com>
Luke Marsden <me@lukemarsden.net> <luke@digital-crocus.com>
Lyn <energylyn@zju.edu.cn>
@ -396,6 +406,7 @@ Mike Dalton <mikedalton@github.com> <19153140+mikedalton@users.noreply.github.co
Mike Goelzer <mike.goelzer@docker.com> <mgoelzer@docker.com>
Milind Chawre <milindchawre@gmail.com>
Misty Stanley-Jones <misty@docker.com> <misty@apache.org>
Mohammad Hossein <mhm98035@gmail.com>
Mohit Soni <mosoni@ebay.com> <mohitsoni1989@gmail.com>
Moorthy RS <rsmoorthy@gmail.com> <rsmoorthy@users.noreply.github.com>
Morten Hekkvang <morten.hekkvang@sbab.se>
@ -419,6 +430,7 @@ O.S. Tezer <ostezer@gmail.com> <ostezer@users.noreply.github.com>
Oh Jinkyun <tintypemolly@gmail.com> <tintypemolly@Ohui-MacBook-Pro.local>
Oliver Pomeroy <oppomeroy@gmail.com>
Ouyang Liduo <oyld0210@163.com>
Patrick St. laurent <patrick@saint-laurent.us>
Patrick Stapleton <github@gdi2290.com>
Paul Liljenberg <liljenberg.paul@gmail.com> <letters@paulnotcom.se>
Pavel Tikhomirov <ptikhomirov@virtuozzo.com> <ptikhomirov@parallels.com>
@ -498,6 +510,7 @@ Stephen Day <stevvooe@gmail.com> <stephen.day@docker.com>
Stephen Day <stevvooe@gmail.com> <stevvooe@users.noreply.github.com>
Steve Desmond <steve@vtsv.ca> <stevedesmond-ca@users.noreply.github.com>
Steve Richards <steve.richards@docker.com> stevejr <>
Stuart Williams <pid@pidster.com>
Sun Gengze <690388648@qq.com>
Sun Jianbo <wonderflow.sun@gmail.com>
Sun Jianbo <wonderflow.sun@gmail.com> <wonderflow@zju.edu.cn>

31
AUTHORS
View File

@ -48,6 +48,7 @@ Alfred Landrum <alfred.landrum@docker.com>
Ali Rostami <rostami.ali@gmail.com>
Alicia Lauerman <alicia@eta.im>
Allen Sun <allensun.shl@alibaba-inc.com>
Allie Sadler <allie.sadler@docker.com>
Alvin Deng <alvin.q.deng@utexas.edu>
Amen Belayneh <amenbelayneh@gmail.com>
Amey Shrivastava <72866602+AmeyShrivastava@users.noreply.github.com>
@ -81,6 +82,7 @@ Antonis Kalipetis <akalipetis@gmail.com>
Anusha Ragunathan <anusha.ragunathan@docker.com>
Ao Li <la9249@163.com>
Arash Deshmeh <adeshmeh@ca.ibm.com>
Archimedes Trajano <developer@trajano.net>
Arko Dasgupta <arko@tetrate.io>
Arnaud Porterie <icecrime@gmail.com>
Arnaud Rebillout <elboulangero@gmail.com>
@ -88,6 +90,7 @@ Arthur Peka <arthur.peka@outlook.com>
Ashly Mathew <ashly.mathew@sap.com>
Ashwini Oruganti <ashwini.oruganti@gmail.com>
Aslam Ahemad <aslamahemad@gmail.com>
Austin Vazquez <austin.vazquez.dev@gmail.com>
Azat Khuyiyakhmetov <shadow_uz@mail.ru>
Bardia Keyoumarsi <bkeyouma@ucsc.edu>
Barnaby Gray <barnaby@pickle.me.uk>
@ -132,6 +135,7 @@ Cao Weiwei <cao.weiwei30@zte.com.cn>
Carlo Mion <mion00@gmail.com>
Carlos Alexandro Becker <caarlos0@gmail.com>
Carlos de Paula <me@carlosedp.com>
Carston Schilds <Carston.Schilds@visier.com>
Casey Korver <casey@korver.dev>
Ce Gao <ce.gao@outlook.com>
Cedric Davies <cedricda@microsoft.com>
@ -189,6 +193,7 @@ Daisuke Ito <itodaisuke00@gmail.com>
dalanlan <dalanlan925@gmail.com>
Damien Nadé <github@livna.org>
Dan Cotora <dan@bluevision.ro>
Dan Wallis <dan@wallis.nz>
Danial Gharib <danial.mail.gh@gmail.com>
Daniel Artine <daniel.artine@ufrj.br>
Daniel Cassidy <mail@danielcassidy.me.uk>
@ -237,6 +242,7 @@ Deshi Xiao <dxiao@redhat.com>
Dharmit Shah <shahdharmit@gmail.com>
Dhawal Yogesh Bhanushali <dbhanushali@vmware.com>
Dieter Reuter <dieter.reuter@me.com>
Dilep Dev <34891655+DilepDev@users.noreply.github.com>
Dima Stopel <dima@twistlock.com>
Dimitry Andric <d.andric@activevideo.com>
Ding Fei <dingfei@stars.org.cn>
@ -308,6 +314,8 @@ George MacRorie <gmacr31@gmail.com>
George Margaritis <gmargaritis@protonmail.com>
George Xie <georgexsh@gmail.com>
Gianluca Borello <g.borello@gmail.com>
Giau. Tran Minh <hello@giautm.dev>
Giedrius Jonikas <giedriusj1@gmail.com>
Gildas Cuisinier <gildas.cuisinier@gcuisinier.net>
Gio d'Amelio <giodamelio@gmail.com>
Gleb Stsenov <gleb.stsenov@gmail.com>
@ -344,6 +352,7 @@ Hugo Gabriel Eyherabide <hugogabriel.eyherabide@gmail.com>
huqun <huqun@zju.edu.cn>
Huu Nguyen <huu@prismskylabs.com>
Hyzhou Zhy <hyzhou.zhy@alibaba-inc.com>
Iain MacDonald <IJMacD@gmail.com>
Iain Samuel McLean Elder <iain@isme.es>
Ian Campbell <ian.campbell@docker.com>
Ian Philpot <ian.philpot@microsoft.com>
@ -393,6 +402,7 @@ Jesse Adametz <jesseadametz@gmail.com>
Jessica Frazelle <jess@oxide.computer>
Jezeniel Zapanta <jpzapanta22@gmail.com>
Jian Zhang <zhangjian.fnst@cn.fujitsu.com>
Jianyong Wu <wujianyong@hygon.cn>
Jie Luo <luo612@zju.edu.cn>
Jilles Oldenbeuving <ojilles@gmail.com>
Jim Chen <njucjc@gmail.com>
@ -446,6 +456,7 @@ Julian <gitea+julian@ic.thejulian.uk>
Julien Barbier <write0@gmail.com>
Julien Kassar <github@kassisol.com>
Julien Maitrehenry <julien.maitrehenry@me.com>
Julio Cesar Garcia <juliogarciamelgarejo@gmail.com>
Justas Brazauskas <brazauskasjustas@gmail.com>
Justin Chadwell <me@jedevc.com>
Justin Cormack <justin.cormack@docker.com>
@ -490,19 +501,22 @@ Kunal Kushwaha <kushwaha_kunal_v7@lab.ntt.co.jp>
Kyle Mitofsky <Kylemit@gmail.com>
Lachlan Cooper <lachlancooper@gmail.com>
Lai Jiangshan <jiangshanlai@gmail.com>
Lajos Papp <lajos.papp@sequenceiq.com>
Lars Kellogg-Stedman <lars@redhat.com>
Laura Brehm <laurabrehm@hey.com>
Laura Frank <ljfrank@gmail.com>
Laurent Erignoux <lerignoux@gmail.com>
Laurent Goderre <laurent.goderre@docker.com>
Lee Gaines <eightlimbed@gmail.com>
Lei Jitang <leijitang@huawei.com>
Lennie <github@consolejunkie.net>
lentil32 <lentil32@icloud.com>
Leo Gallucci <elgalu3@gmail.com>
Leonid Skorospelov <leosko94@gmail.com>
Lewis Daly <lewisdaly@me.com>
Li Fu Bang <lifubang@acmcoder.com>
Li Yi <denverdino@gmail.com>
Li Yi <weiyuan.yl@alibaba-inc.com>
Li Zeghong <zeghong@hotmail.com>
Liang-Chi Hsieh <viirya@gmail.com>
Lihua Tang <lhtang@alauda.io>
Lily Guo <lily.guo@docker.com>
@ -515,6 +529,7 @@ lixiaobing10051267 <li.xiaobing1@zte.com.cn>
Lloyd Dewolf <foolswisdom@gmail.com>
Lorenzo Fontana <lo@linux.com>
Louis Opter <kalessin@kalessin.fr>
Lovekesh Kumar <lovekesh.kumar@rtcamp.com>
Luca Favatella <luca.favatella@erlang-solutions.com>
Luca Marturana <lucamarturana@gmail.com>
Lucas Chan <lucas-github@lucaschan.com>
@ -559,6 +574,7 @@ Matt Robenolt <matt@ydekproductions.com>
Matteo Orefice <matteo.orefice@bites4bits.software>
Matthew Heon <mheon@redhat.com>
Matthieu Hauglustaine <matt.hauglustaine@gmail.com>
Matthieu MOREL <matthieu.morel35@gmail.com>
Mauro Porras P <mauroporrasp@gmail.com>
Max Shytikov <mshytikov@gmail.com>
Max-Julian Pogner <max-julian@pogner.at>
@ -566,6 +582,7 @@ Maxime Petazzoni <max@signalfuse.com>
Maximillian Fan Xavier <maximillianfx@gmail.com>
Mei ChunTao <mei.chuntao@zte.com.cn>
Melroy van den Berg <melroy@melroy.org>
Mert Şişmanoğlu <mert190737fb@gmail.com>
Metal <2466052+tedhexaflow@users.noreply.github.com>
Micah Zoltu <micah@newrelic.com>
Michael A. Smith <michael@smith-li.com>
@ -598,7 +615,9 @@ Mindaugas Rukas <momomg@gmail.com>
Miroslav Gula <miroslav.gula@naytrolabs.com>
Misty Stanley-Jones <misty@docker.com>
Mohammad Banikazemi <mb@us.ibm.com>
Mohammad Hossein <mhm98035@gmail.com>
Mohammed Aaqib Ansari <maaquib@gmail.com>
Mohammed Aminu Futa <mohammedfuta2000@gmail.com>
Mohini Anne Dsouza <mohini3917@gmail.com>
Moorthy RS <rsmoorthy@gmail.com>
Morgan Bauer <mbauer@us.ibm.com>
@ -633,9 +652,11 @@ Nicolas De Loof <nicolas.deloof@gmail.com>
Nikhil Chawla <chawlanikhil24@gmail.com>
Nikolas Garofil <nikolas.garofil@uantwerpen.be>
Nikolay Milovanov <nmil@itransformers.net>
NinaLua <iturf@sina.cn>
Nir Soffer <nsoffer@redhat.com>
Nishant Totla <nishanttotla@gmail.com>
NIWA Hideyuki <niwa.niwa@nifty.ne.jp>
Noah Silas <noah@hustle.com>
Noah Treuhaft <noah.treuhaft@docker.com>
O.S. Tezer <ostezer@gmail.com>
Oded Arbel <oded@geek.co.il>
@ -653,10 +674,12 @@ Patrick Böänziger <patrick.baenziger@bsi-software.com>
Patrick Daigle <114765035+pdaig@users.noreply.github.com>
Patrick Hemmer <patrick.hemmer@gmail.com>
Patrick Lang <plang@microsoft.com>
Patrick St. laurent <patrick@saint-laurent.us>
Paul <paul9869@gmail.com>
Paul Kehrer <paul.l.kehrer@gmail.com>
Paul Lietar <paul@lietar.net>
Paul Mulders <justinkb@gmail.com>
Paul Rogalski <mail@paul-rogalski.de>
Paul Seyfert <pseyfert.mathphys@gmail.com>
Paul Weaver <pauweave@cisco.com>
Pavel Pospisil <pospispa@gmail.com>
@ -678,7 +701,6 @@ Philip Alexander Etling <paetling@gmail.com>
Philipp Gillé <philipp.gille@gmail.com>
Philipp Schmied <pschmied@schutzwerk.com>
Phong Tran <tran.pho@northeastern.edu>
pidster <pid@pidster.com>
Pieter E Smit <diepes@github.com>
pixelistik <pixelistik@users.noreply.github.com>
Pratik Karki <prertik@outlook.com>
@ -738,6 +760,7 @@ Samuel Cochran <sj26@sj26.com>
Samuel Karp <skarp@amazon.com>
Sandro Jäckel <sandro.jaeckel@gmail.com>
Santhosh Manohar <santhosh@docker.com>
Sarah Sanders <sarah.sanders@docker.com>
Sargun Dhillon <sargun@netflix.com>
Saswat Bhattacharya <sas.saswat@gmail.com>
Saurabh Kumar <saurabhkumar0184@gmail.com>
@ -770,6 +793,7 @@ Spencer Brown <spencer@spencerbrown.org>
Spring Lee <xi.shuai@outlook.com>
squeegels <lmscrewy@gmail.com>
Srini Brahmaroutu <srbrahma@us.ibm.com>
Stavros Panakakis <stavrospanakakis@gmail.com>
Stefan S. <tronicum@user.github.com>
Stefan Scherer <stefan.scherer@docker.com>
Stefan Weil <sw@weilnetz.de>
@ -780,6 +804,7 @@ Steve Durrheimer <s.durrheimer@gmail.com>
Steve Richards <steve.richards@docker.com>
Steven Burgess <steven.a.burgess@hotmail.com>
Stoica-Marcu Floris-Andrei <floris.sm@gmail.com>
Stuart Williams <pid@pidster.com>
Subhajit Ghosh <isubuz.g@gmail.com>
Sun Jianbo <wonderflow.sun@gmail.com>
Sune Keller <absukl@almbrand.dk>
@ -867,6 +892,7 @@ Wang Yumu <37442693@qq.com>
Wataru Ishida <ishida.wataru@lab.ntt.co.jp>
Wayne Song <wsong@docker.com>
Wen Cheng Ma <wenchma@cn.ibm.com>
Wenlong Zhang <zhangwenlong@loongson.cn>
Wenzhi Liang <wenzhi.liang@gmail.com>
Wes Morgan <cap10morgan@gmail.com>
Wewang Xiaorenfine <wang.xiaoren@zte.com.cn>
@ -908,3 +934,4 @@ Zhuo Zhi <h.dwwwwww@gmail.com>
Átila Camurça Alves <camurca.home@gmail.com>
Александр Менщиков <__Singleton__@hackerdom.ru>
徐俊杰 <paco.xu@daocloud.io>
林博仁 Buo-ren Lin <Buo.Ren.Lin@gmail.com>

View File

@ -66,7 +66,7 @@ anybody starts working on it.
We are always thrilled to receive pull requests. We do our best to process them
quickly. If your pull request is not accepted on the first try,
don't get discouraged! Our contributor's guide explains [the review process we
use for simple changes](https://docs.docker.com/opensource/workflow/make-a-contribution/).
use for simple changes](https://github.com/docker/docker/blob/master/project/REVIEWING.md).
### Talking to other Docker users and contributors
@ -124,8 +124,8 @@ submitting a pull request.
Update the documentation when creating or modifying features. Test your
documentation changes for clarity, concision, and correctness, as well as a
clean documentation build. See our contributors guide for [our style
guide](https://docs.docker.com/opensource/doc-style) and instructions on [building
the documentation](https://docs.docker.com/opensource/project/test-and-docs/#build-and-test-the-documentation).
guide](https://docs.docker.com/contribute/style/grammar/) and instructions on [building
the documentation](https://docs.docker.com/contribute/).
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
@ -134,9 +134,41 @@ committing your changes. Most editors have plug-ins that do this automatically.
Pull request descriptions should be as clear as possible and include a reference
to all the issues that they address.
Commit messages must start with a capitalized and short summary (max. 50 chars)
written in the imperative, followed by an optional, more detailed explanatory
text which is separated from the summary by an empty line.
Commit messages must be written in the imperative mood (max. 72 chars), followed
by an optional, more detailed explanatory text usually expanding on
why the work is necessary. The explanatory text should be separated by an
empty line.
The commit message *could* have a prefix scoping the change, however this is
not enforced. Common prefixes are `docs: <message>`, `vendor: <message>`,
`chore: <message>` or the package/area related to the change such as `pkg/foo: <message>`
or `telemetry: <message>`.
A standard commit.
```
Fix the exploding flux capacitor
A call to function A causes the flux capacitor to blow up every time
the sun and the moon align.
```
Using a package as prefix.
```
pkg/foo: prevent panic in flux capacitor
Calling function A causes the flux capacitor to blow up every time
the sun and the moon align.
```
Updating a specific vendored package.
```
vendor: github.com/docker/docker 6ac445c42bad (master, v28.0-dev)
```
Fixing a broken docs link.
```
docs: fix style/lint issues in deprecated.md
```
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Post

View File

@ -1,22 +1,37 @@
# syntax=docker/dockerfile:1
ARG BASE_VARIANT=alpine
ARG ALPINE_VERSION=3.20
# ALPINE_VERSION sets the version of the alpine base image to use, including for the golang image.
# It must be a supported tag in the docker.io/library/alpine image repository
# that's also available as alpine image variant for the Golang version used.
ARG ALPINE_VERSION=3.22
ARG BASE_DEBIAN_DISTRO=bookworm
ARG GO_VERSION=1.21.11
ARG XX_VERSION=1.4.0
ARG GOVERSIONINFO_VERSION=v1.3.0
ARG GOTESTSUM_VERSION=v1.10.0
ARG BUILDX_VERSION=0.15.1
ARG COMPOSE_VERSION=v2.28.0
ARG GO_VERSION=1.24.5
ARG XX_VERSION=1.6.1
ARG GOVERSIONINFO_VERSION=v1.4.1
# GOTESTSUM_VERSION sets the version of gotestsum to install in the dev container.
# It must be a valid tag in the https://github.com/gotestyourself/gotestsum repository.
ARG GOTESTSUM_VERSION=v1.12.3
# BUILDX_VERSION sets the version of buildx to use for the e2e tests.
# It must be a tag in the docker.io/docker/buildx-bin image repository
# on Docker Hub.
ARG BUILDX_VERSION=0.25.0
# COMPOSE_VERSION is the version of compose to install in the dev container.
# It must be a tag in the docker.io/docker/compose-bin image repository
# on Docker Hub.
ARG COMPOSE_VERSION=v2.38.2
FROM --platform=$BUILDPLATFORM tonistiigi/xx:${XX_VERSION} AS xx
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS build-base-alpine
ENV GOTOOLCHAIN=local
COPY --link --from=xx / /
RUN apk add --no-cache bash clang lld llvm file git
RUN apk add --no-cache bash clang lld llvm file git git-daemon
WORKDIR /go/src/github.com/docker/cli
FROM build-base-alpine AS build-alpine
@ -63,7 +78,7 @@ ARG PACKAGER_NAME
COPY --link --from=goversioninfo /out/goversioninfo /usr/bin/goversioninfo
RUN --mount=type=bind,target=.,ro \
--mount=type=cache,target=/root/.cache \
--mount=type=tmpfs,target=cli/winresources \
--mount=type=tmpfs,target=cmd/docker/winresources \
# override the default behavior of go with xx-go
xx-go --wrap && \
# export GOCACHE=$(go env GOCACHE)/$(xx-info)$([ -f /etc/alpine-release ] && echo "alpine") && \
@ -113,7 +128,7 @@ COPY --link --from=compose /docker-compose /usr/libexec/docker/cli-plugins/docke
COPY --link . .
ENV DOCKER_BUILDKIT=1
ENV PATH=/go/src/github.com/docker/cli/build:$PATH
CMD ./scripts/test/e2e/entry
CMD ["./scripts/test/e2e/entry"]
FROM build-base-${BASE_VARIANT} AS dev
COPY --link . .

View File

@ -52,7 +52,7 @@ shellcheck: ## run shellcheck validation
.PHONY: fmt
fmt: ## run gofumpt (if present) or gofmt
@if command -v gofumpt > /dev/null; then \
gofumpt -w -d -lang=1.21 . ; \
gofumpt -w -d -lang=1.23 . ; \
else \
go list -f {{.Dir}} ./... | xargs gofmt -w -s -d ; \
fi
@ -67,36 +67,63 @@ dynbinary: ## build dynamically linked binary
.PHONY: plugins
plugins: ## build example CLI plugins
./scripts/build/plugins
scripts/build/plugins
.PHONY: vendor
vendor: ## update vendor with go modules
rm -rf vendor
./scripts/vendor update
scripts/with-go-mod.sh scripts/vendor update
.PHONY: validate-vendor
validate-vendor: ## validate vendor
./scripts/vendor validate
scripts/with-go-mod.sh scripts/vendor validate
.PHONY: mod-outdated
mod-outdated: ## check outdated dependencies
./scripts/vendor outdated
scripts/with-go-mod.sh scripts/vendor outdated
.PHONY: authors
authors: ## generate AUTHORS file from git history
scripts/docs/generate-authors.sh
.PHONY: completion
completion: shell-completion
completion: ## generate and install the shell-completion scripts
# Note: this uses system-wide paths, and so may overwrite completion
# scripts installed as part of deb/rpm packages.
#
# Given that this target is intended to debug/test updated versions, we could
# consider installing in per-user (~/.config, XDG_DATA_DIR) paths instead, but
# this will add more complexity.
#
# See https://github.com/docker/cli/pull/5770#discussion_r1927772710
install -D -p -m 0644 ./build/completion/bash/docker /usr/share/bash-completion/completions/docker
install -D -p -m 0644 ./build/completion/fish/docker.fish debian/docker-ce-cli/usr/share/fish/vendor_completions.d/docker.fish
install -D -p -m 0644 ./build/completion/zsh/_docker debian/docker-ce-cli/usr/share/zsh/vendor-completions/_docker
build/docker:
# This target is used by the "shell-completion" target, which requires either
# "binary" or "dynbinary" to have been built. We don't want to trigger those
# to prevent replacing a static binary with a dynamic one, or vice-versa.
@echo "Run 'make binary' or 'make dynbinary' first" && exit 1
.PHONY: shell-completion
shell-completion: build/docker # requires either "binary" or "dynbinary" to be built.
shell-completion: ## generate shell-completion scripts
@ ./scripts/build/shell-completion
.PHONY: manpages
manpages: ## generate man pages from go source and markdown
scripts/docs/generate-man.sh
scripts/with-go-mod.sh scripts/docs/generate-man.sh
.PHONY: mddocs
mddocs: ## generate markdown files from go source
scripts/docs/generate-md.sh
scripts/with-go-mod.sh scripts/docs/generate-md.sh
.PHONY: yamldocs
yamldocs: ## generate documentation YAML files consumed by docs repo
scripts/docs/generate-yaml.sh
scripts/with-go-mod.sh scripts/docs/generate-yaml.sh
.PHONY: help
help: ## print this help

View File

@ -1,9 +1,10 @@
# Docker CLI
[![PkgGoDev](https://img.shields.io/badge/go.dev-docs-007d9c?logo=go&logoColor=white)](https://pkg.go.dev/github.com/docker/cli)
[![PkgGoDev](https://pkg.go.dev/badge/github.com/docker/cli)](https://pkg.go.dev/github.com/docker/cli)
[![Build Status](https://img.shields.io/github/actions/workflow/status/docker/cli/build.yml?branch=master&label=build&logo=github)](https://github.com/docker/cli/actions?query=workflow%3Abuild)
[![Test Status](https://img.shields.io/github/actions/workflow/status/docker/cli/test.yml?branch=master&label=test&logo=github)](https://github.com/docker/cli/actions?query=workflow%3Atest)
[![Go Report Card](https://goreportcard.com/badge/github.com/docker/cli)](https://goreportcard.com/report/github.com/docker/cli)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/docker/cli/badge)](https://scorecard.dev/viewer/?uri=github.com/docker/cli)
[![Codecov](https://img.shields.io/codecov/c/github/docker/cli?logo=codecov)](https://codecov.io/gh/docker/cli)
## About

44
SECURITY.md Normal file
View File

@ -0,0 +1,44 @@
# Security Policy
The maintainers of the Docker CLI take security seriously. If you discover
a security issue, please bring it to their attention right away!
## Reporting a Vulnerability
Please **DO NOT** file a public issue, instead send your report privately
to [security@docker.com](mailto:security@docker.com).
Reporter(s) can expect a response within 72 hours, acknowledging the issue was
received.
## Review Process
After receiving the report, an initial triage and technical analysis is
performed to confirm the report and determine its scope. We may request
additional information in this stage of the process.
Once a reviewer has confirmed the relevance of the report, a draft security
advisory will be created on GitHub. The draft advisory will be used to discuss
the issue with maintainers, the reporter(s), and where applicable, other
affected parties under embargo.
If the vulnerability is accepted, a timeline for developing a patch, public
disclosure, and patch release will be determined. If there is an embargo period
on public disclosure before the patch release, the reporter(s) are expected to
participate in the discussion of the timeline and abide by agreed upon dates
for public disclosure.
## Accreditation
Security reports are greatly appreciated and we will publicly thank you,
although we will keep your name confidential if you request it. We also like to
send gifts - if you're into swag, make sure to let us know. We do not currently
offer a paid security bounty program at this time.
## Supported Versions
This project uses long-lived branches to maintain releases, and follows
the maintenance cycle of the Moby project.
Refer to [BRANCHES-AND-TAGS.md](https://github.com/moby/moby/blob/master/project/BRANCHES-AND-TAGS.md)
in the default branch of the moby repository to learn about the current
maintenance status of each branch.

View File

@ -1 +1 @@
27.0.1-dev
28.3.0-dev

View File

@ -5,31 +5,31 @@ import (
"fmt"
"os"
"github.com/docker/cli/cli-plugins/manager"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/cli-plugins/plugin"
"github.com/docker/cli/cli/command"
"github.com/spf13/cobra"
)
func main() {
plugin.Run(func(dockerCli command.Cli) *cobra.Command {
plugin.Run(func(dockerCLI command.Cli) *cobra.Command {
goodbye := &cobra.Command{
Use: "goodbye",
Short: "Say Goodbye instead of Hello",
Run: func(cmd *cobra.Command, _ []string) {
fmt.Fprintln(dockerCli.Out(), "Goodbye World!")
_, _ = fmt.Fprintln(dockerCLI.Out(), "Goodbye World!")
},
}
apiversion := &cobra.Command{
Use: "apiversion",
Short: "Print the API version of the server",
RunE: func(_ *cobra.Command, _ []string) error {
cli := dockerCli.Client()
ping, err := cli.Ping(context.Background())
apiClient := dockerCLI.Client()
ping, err := apiClient.Ping(context.Background())
if err != nil {
return err
}
fmt.Println(ping.APIVersion)
_, _ = fmt.Println(ping.APIVersion)
return nil
},
}
@ -38,7 +38,7 @@ func main() {
Use: "exitstatus2",
Short: "Exit with status 2",
RunE: func(_ *cobra.Command, _ []string) error {
fmt.Fprintln(dockerCli.Err(), "Exiting with error status 2")
_, _ = fmt.Fprintln(dockerCLI.Err(), "Exiting with error status 2")
os.Exit(2)
return nil
},
@ -56,33 +56,33 @@ func main() {
return err
}
if preRun {
fmt.Fprintf(dockerCli.Err(), "Plugin PersistentPreRunE called")
_, _ = fmt.Fprintln(dockerCLI.Err(), "Plugin PersistentPreRunE called")
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if debug {
fmt.Fprintf(dockerCli.Err(), "Plugin debug mode enabled")
_, _ = fmt.Fprintln(dockerCLI.Err(), "Plugin debug mode enabled")
}
switch optContext {
case "Christmas":
fmt.Fprintf(dockerCli.Out(), "Merry Christmas!\n")
_, _ = fmt.Fprintln(dockerCLI.Out(), "Merry Christmas!")
return nil
case "":
// nothing
}
if who == "" {
who, _ = dockerCli.ConfigFile().PluginConfig("helloworld", "who")
who, _ = dockerCLI.ConfigFile().PluginConfig("helloworld", "who")
}
if who == "" {
who = "World"
}
fmt.Fprintf(dockerCli.Out(), "Hello %s!\n", who)
dockerCli.ConfigFile().SetPluginConfig("helloworld", "lastwho", who)
return dockerCli.ConfigFile().Save()
_, _ = fmt.Fprintln(dockerCLI.Out(), "Hello", who)
dockerCLI.ConfigFile().SetPluginConfig("helloworld", "lastwho", who)
return dockerCLI.ConfigFile().Save()
},
}
@ -97,7 +97,7 @@ func main() {
cmd.AddCommand(goodbye, apiversion, exitStatus2)
return cmd
},
manager.Metadata{
metadata.Metadata{
SchemaVersion: "0.1.0",
Vendor: "Docker Inc.",
Version: "testing",

View File

@ -11,8 +11,8 @@ func PrintNextSteps(out io.Writer, messages []string) {
if len(messages) == 0 {
return
}
fmt.Fprintln(out, aec.Bold.Apply("\nWhat's next:"))
_, _ = fmt.Fprintln(out, aec.Bold.Apply("\nWhat's next:"))
for _, n := range messages {
_, _ = fmt.Fprintf(out, " %s\n", n)
_, _ = fmt.Fprintln(out, " ", n)
}
}

View File

@ -0,0 +1,30 @@
package manager
import "github.com/docker/cli/cli-plugins/metadata"
const (
// CommandAnnotationPlugin is added to every stub command added by
// AddPluginCommandStubs with the value "true" and so can be
// used to distinguish plugin stubs from regular commands.
CommandAnnotationPlugin = metadata.CommandAnnotationPlugin
// CommandAnnotationPluginVendor is added to every stub command
// added by AddPluginCommandStubs and contains the vendor of
// that plugin.
CommandAnnotationPluginVendor = metadata.CommandAnnotationPluginVendor
// CommandAnnotationPluginVersion is added to every stub command
// added by AddPluginCommandStubs and contains the version of
// that plugin.
CommandAnnotationPluginVersion = metadata.CommandAnnotationPluginVersion
// CommandAnnotationPluginInvalid is added to any stub command
// added by AddPluginCommandStubs for an invalid command (that
// is, one which failed it's candidate test) and contains the
// reason for the failure.
CommandAnnotationPluginInvalid = metadata.CommandAnnotationPluginInvalid
// CommandAnnotationPluginCommandPath is added to overwrite the
// command path for a plugin invocation.
CommandAnnotationPluginCommandPath = metadata.CommandAnnotationPluginCommandPath
)

View File

@ -1,6 +1,10 @@
package manager
import "os/exec"
import (
"os/exec"
"github.com/docker/cli/cli-plugins/metadata"
)
// Candidate represents a possible plugin candidate, for mocking purposes
type Candidate interface {
@ -17,5 +21,5 @@ func (c *candidate) Path() string {
}
func (c *candidate) Metadata() ([]byte, error) {
return exec.Command(c.path, MetadataSubcommandName).Output()
return exec.Command(c.path, metadata.MetadataSubcommandName).Output() // #nosec G204 -- ignore "Subprocess launched with a potential tainted input or cmd arguments"
}

View File

@ -6,9 +6,10 @@ import (
"strings"
"testing"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
"gotest.tools/v3/assert/cmp"
is "gotest.tools/v3/assert/cmp"
)
type fakeCandidate struct {
@ -30,10 +31,10 @@ func (c *fakeCandidate) Metadata() ([]byte, error) {
func TestValidateCandidate(t *testing.T) {
const (
goodPluginName = NamePrefix + "goodplugin"
goodPluginName = metadata.NamePrefix + "goodplugin"
builtinName = NamePrefix + "builtin"
builtinAlias = NamePrefix + "alias"
builtinName = metadata.NamePrefix + "builtin"
builtinAlias = metadata.NamePrefix + "alias"
badPrefixPath = "/usr/local/libexec/cli-plugins/wobble"
badNamePath = "/usr/local/libexec/cli-plugins/docker-123456"
@ -43,9 +44,9 @@ func TestValidateCandidate(t *testing.T) {
fakeroot := &cobra.Command{Use: "docker"}
fakeroot.AddCommand(&cobra.Command{
Use: strings.TrimPrefix(builtinName, NamePrefix),
Use: strings.TrimPrefix(builtinName, metadata.NamePrefix),
Aliases: []string{
strings.TrimPrefix(builtinAlias, NamePrefix),
strings.TrimPrefix(builtinAlias, metadata.NamePrefix),
},
})
@ -59,7 +60,7 @@ func TestValidateCandidate(t *testing.T) {
}{
/* Each failing one of the tests */
{name: "empty path", c: &fakeCandidate{path: ""}, err: "plugin candidate path cannot be empty"},
{name: "bad prefix", c: &fakeCandidate{path: badPrefixPath}, err: fmt.Sprintf("does not have %q prefix", NamePrefix)},
{name: "bad prefix", c: &fakeCandidate{path: badPrefixPath}, err: fmt.Sprintf("does not have %q prefix", metadata.NamePrefix)},
{name: "bad path", c: &fakeCandidate{path: badNamePath}, invalid: "did not match"},
{name: "builtin command", c: &fakeCandidate{path: builtinName}, invalid: `plugin "builtin" duplicates builtin command`},
{name: "builtin alias", c: &fakeCandidate{path: builtinAlias}, invalid: `plugin "alias" duplicates an alias of builtin command "builtin"`},
@ -80,11 +81,11 @@ func TestValidateCandidate(t *testing.T) {
assert.ErrorContains(t, err, tc.err)
case tc.invalid != "":
assert.NilError(t, err)
assert.Assert(t, cmp.ErrorType(p.Err, reflect.TypeOf(&pluginError{})))
assert.Assert(t, is.ErrorType(p.Err, reflect.TypeOf(&pluginError{})))
assert.ErrorContains(t, p.Err, tc.invalid)
default:
assert.NilError(t, err)
assert.Equal(t, NamePrefix+p.Name, goodPluginName)
assert.Equal(t, metadata.NamePrefix+p.Name, goodPluginName)
assert.Equal(t, p.SchemaVersion, "0.1.0")
assert.Equal(t, p.Vendor, "e2e-testing")
}

View File

@ -2,41 +2,12 @@ package manager
import (
"fmt"
"net/url"
"os"
"strings"
"sync"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/cli/config"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel/attribute"
)
const (
// CommandAnnotationPlugin is added to every stub command added by
// AddPluginCommandStubs with the value "true" and so can be
// used to distinguish plugin stubs from regular commands.
CommandAnnotationPlugin = "com.docker.cli.plugin"
// CommandAnnotationPluginVendor is added to every stub command
// added by AddPluginCommandStubs and contains the vendor of
// that plugin.
CommandAnnotationPluginVendor = "com.docker.cli.plugin.vendor"
// CommandAnnotationPluginVersion is added to every stub command
// added by AddPluginCommandStubs and contains the version of
// that plugin.
CommandAnnotationPluginVersion = "com.docker.cli.plugin.version"
// CommandAnnotationPluginInvalid is added to any stub command
// added by AddPluginCommandStubs for an invalid command (that
// is, one which failed it's candidate test) and contains the
// reason for the failure.
CommandAnnotationPluginInvalid = "com.docker.cli.plugin-invalid"
// CommandAnnotationPluginCommandPath is added to overwrite the
// command path for a plugin invocation.
CommandAnnotationPluginCommandPath = "com.docker.cli.plugin.command_path"
)
var pluginCommandStubsOnce sync.Once
@ -44,26 +15,25 @@ var pluginCommandStubsOnce sync.Once
// AddPluginCommandStubs adds a stub cobra.Commands for each valid and invalid
// plugin. The command stubs will have several annotations added, see
// `CommandAnnotationPlugin*`.
func AddPluginCommandStubs(dockerCli command.Cli, rootCmd *cobra.Command) (err error) {
func AddPluginCommandStubs(dockerCLI config.Provider, rootCmd *cobra.Command) (err error) {
pluginCommandStubsOnce.Do(func() {
var plugins []Plugin
plugins, err = ListPlugins(dockerCli, rootCmd)
plugins, err = ListPlugins(dockerCLI, rootCmd)
if err != nil {
return
}
for _, p := range plugins {
p := p
vendor := p.Vendor
if vendor == "" {
vendor = "unknown"
}
annotations := map[string]string{
CommandAnnotationPlugin: "true",
CommandAnnotationPluginVendor: vendor,
CommandAnnotationPluginVersion: p.Version,
metadata.CommandAnnotationPlugin: "true",
metadata.CommandAnnotationPluginVendor: vendor,
metadata.CommandAnnotationPluginVersion: p.Version,
}
if p.Err != nil {
annotations[CommandAnnotationPluginInvalid] = p.Err.Error()
annotations[metadata.CommandAnnotationPluginInvalid] = p.Err.Error()
}
rootCmd.AddCommand(&cobra.Command{
Use: p.Name,
@ -82,7 +52,7 @@ func AddPluginCommandStubs(dockerCli command.Cli, rootCmd *cobra.Command) (err e
cmd.HelpFunc()(rootCmd, args)
return nil
}
return fmt.Errorf("docker: '%s' is not a docker command.\nSee 'docker --help'", cmd.Name())
return fmt.Errorf("docker: unknown command: docker %s\n\nRun 'docker --help' for more information", cmd.Name())
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// Delegate completion to plugin
@ -90,7 +60,7 @@ func AddPluginCommandStubs(dockerCli command.Cli, rootCmd *cobra.Command) (err e
cargs = append(cargs, args...)
cargs = append(cargs, toComplete)
os.Args = cargs
runCommand, runErr := PluginRunCommand(dockerCli, p.Name, cmd)
runCommand, runErr := PluginRunCommand(dockerCLI, p.Name, cmd)
if runErr != nil {
return nil, cobra.ShellCompDirectiveError
}
@ -105,44 +75,3 @@ func AddPluginCommandStubs(dockerCli command.Cli, rootCmd *cobra.Command) (err e
})
return err
}
const (
dockerCliAttributePrefix = attribute.Key("docker.cli")
cobraCommandPath = attribute.Key("cobra.command_path")
)
func getPluginResourceAttributes(cmd *cobra.Command, plugin Plugin) attribute.Set {
commandPath := cmd.Annotations[CommandAnnotationPluginCommandPath]
if commandPath == "" {
commandPath = fmt.Sprintf("%s %s", cmd.CommandPath(), plugin.Name)
}
attrSet := attribute.NewSet(
cobraCommandPath.String(commandPath),
)
kvs := make([]attribute.KeyValue, 0, attrSet.Len())
for iter := attrSet.Iter(); iter.Next(); {
attr := iter.Attribute()
kvs = append(kvs, attribute.KeyValue{
Key: dockerCliAttributePrefix + "." + attr.Key,
Value: attr.Value,
})
}
return attribute.NewSet(kvs...)
}
func appendPluginResourceAttributesEnvvar(env []string, cmd *cobra.Command, plugin Plugin) []string {
if attrs := getPluginResourceAttributes(cmd, plugin); attrs.Len() > 0 {
// values in environment variables need to be in baggage format
// otel/baggage package can be used after update to v1.22, currently it encodes incorrectly
attrsSlice := make([]string, attrs.Len())
for iter := attrs.Iter(); iter.Next(); {
i, v := iter.IndexedAttribute()
attrsSlice[i] = string(v.Key) + "=" + url.PathEscape(v.Value.AsString())
}
env = append(env, ResourceAttributesEnvvar+"="+strings.Join(attrsSlice, ","))
}
return env
}

View File

@ -0,0 +1,26 @@
package manager
import (
"testing"
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
)
func TestPluginResourceAttributesEnvvar(t *testing.T) {
cmd := &cobra.Command{
Annotations: map[string]string{
cobra.CommandDisplayNameAnnotation: "docker",
},
}
// Ensure basic usage is fine.
env := appendPluginResourceAttributesEnvvar(nil, cmd, Plugin{Name: "compose"})
assert.DeepEqual(t, []string{"OTEL_RESOURCE_ATTRIBUTES=docker.cli.cobra.command_path=docker%20compose"}, env)
// Add a user-based environment variable to OTEL_RESOURCE_ATTRIBUTES.
t.Setenv("OTEL_RESOURCE_ATTRIBUTES", "a.b.c=foo")
env = appendPluginResourceAttributesEnvvar(nil, cmd, Plugin{Name: "compose"})
assert.DeepEqual(t, []string{"OTEL_RESOURCE_ATTRIBUTES=a.b.c=foo,docker.cli.cobra.command_path=docker%20compose"}, env)
}

View File

@ -1,10 +1,10 @@
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
//go:build go1.23
package manager
import (
"github.com/pkg/errors"
"fmt"
)
// pluginError is set as Plugin.Err by NewPlugin if the plugin
@ -39,16 +39,16 @@ func (e *pluginError) MarshalText() (text []byte, err error) {
}
// wrapAsPluginError wraps an error in a pluginError with an
// additional message, analogous to errors.Wrapf.
// additional message.
func wrapAsPluginError(err error, msg string) error {
if err == nil {
return nil
}
return &pluginError{cause: errors.Wrap(err, msg)}
return &pluginError{cause: fmt.Errorf("%s: %w", msg, err)}
}
// NewPluginError creates a new pluginError, analogous to
// errors.Errorf.
func NewPluginError(msg string, args ...any) error {
return &pluginError{cause: errors.Errorf(msg, args...)}
return &pluginError{cause: fmt.Errorf(msg, args...)}
}

View File

@ -6,7 +6,8 @@ import (
"strings"
"github.com/docker/cli/cli-plugins/hooks"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@ -29,29 +30,28 @@ type HookPluginData struct {
// a main CLI command was executed. It calls the hook subcommand for all
// present CLI plugins that declare support for hooks in their metadata and
// parses/prints their responses.
func RunCLICommandHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCommand *cobra.Command, cmdErrorMessage string) {
func RunCLICommandHooks(ctx context.Context, dockerCLI config.Provider, rootCmd, subCommand *cobra.Command, cmdErrorMessage string) {
commandName := strings.TrimPrefix(subCommand.CommandPath(), rootCmd.Name()+" ")
flags := getCommandFlags(subCommand)
runHooks(ctx, dockerCli, rootCmd, subCommand, commandName, flags, cmdErrorMessage)
runHooks(ctx, dockerCLI.ConfigFile(), rootCmd, subCommand, commandName, flags, cmdErrorMessage)
}
// RunPluginHooks is the entrypoint for the hooks execution flow
// after a plugin command was just executed by the CLI.
func RunPluginHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCommand *cobra.Command, args []string) {
func RunPluginHooks(ctx context.Context, dockerCLI config.Provider, rootCmd, subCommand *cobra.Command, args []string) {
commandName := strings.Join(args, " ")
flags := getNaiveFlags(args)
runHooks(ctx, dockerCli, rootCmd, subCommand, commandName, flags, "")
runHooks(ctx, dockerCLI.ConfigFile(), rootCmd, subCommand, commandName, flags, "")
}
func runHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCommand *cobra.Command, invokedCommand string, flags map[string]string, cmdErrorMessage string) {
nextSteps := invokeAndCollectHooks(ctx, dockerCli, rootCmd, subCommand, invokedCommand, flags, cmdErrorMessage)
hooks.PrintNextSteps(dockerCli.Err(), nextSteps)
func runHooks(ctx context.Context, cfg *configfile.ConfigFile, rootCmd, subCommand *cobra.Command, invokedCommand string, flags map[string]string, cmdErrorMessage string) {
nextSteps := invokeAndCollectHooks(ctx, cfg, rootCmd, subCommand, invokedCommand, flags, cmdErrorMessage)
hooks.PrintNextSteps(subCommand.ErrOrStderr(), nextSteps)
}
func invokeAndCollectHooks(ctx context.Context, dockerCli command.Cli, rootCmd, subCmd *cobra.Command, subCmdStr string, flags map[string]string, cmdErrorMessage string) []string {
func invokeAndCollectHooks(ctx context.Context, cfg *configfile.ConfigFile, rootCmd, subCmd *cobra.Command, subCmdStr string, flags map[string]string, cmdErrorMessage string) []string {
// check if the context was cancelled before invoking hooks
select {
case <-ctx.Done():
@ -59,19 +59,20 @@ func invokeAndCollectHooks(ctx context.Context, dockerCli command.Cli, rootCmd,
default:
}
pluginsCfg := dockerCli.ConfigFile().Plugins
pluginsCfg := cfg.Plugins
if pluginsCfg == nil {
return nil
}
pluginDirs := getPluginDirs(cfg)
nextSteps := make([]string, 0, len(pluginsCfg))
for pluginName, cfg := range pluginsCfg {
match, ok := pluginMatch(cfg, subCmdStr)
for pluginName, pluginCfg := range pluginsCfg {
match, ok := pluginMatch(pluginCfg, subCmdStr)
if !ok {
continue
}
p, err := GetPlugin(pluginName, dockerCli, rootCmd)
p, err := getPlugin(pluginName, pluginDirs, rootCmd)
if err != nil {
continue
}

View File

@ -9,7 +9,7 @@ import (
"strings"
"sync"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/fvbommel/sortorder"
@ -22,17 +22,19 @@ const (
// used to originally invoke the docker CLI when executing a
// plugin. Assuming $PATH and $CWD remain unchanged this should allow
// the plugin to re-execute the original CLI.
ReexecEnvvar = "DOCKER_CLI_PLUGIN_ORIGINAL_CLI_COMMAND"
ReexecEnvvar = metadata.ReexecEnvvar
// ResourceAttributesEnvvar is the name of the envvar that includes additional
// resource attributes for OTEL.
//
// Deprecated: The "OTEL_RESOURCE_ATTRIBUTES" env-var is part of the OpenTelemetry specification; users should define their own const for this. This const will be removed in the next release.
ResourceAttributesEnvvar = "OTEL_RESOURCE_ATTRIBUTES"
)
// errPluginNotFound is the error returned when a plugin could not be found.
type errPluginNotFound string
func (e errPluginNotFound) NotFound() {}
func (errPluginNotFound) NotFound() {}
func (e errPluginNotFound) Error() string {
return "Error: No such CLI plugin: " + string(e)
@ -59,29 +61,27 @@ func IsNotFound(err error) bool {
// 3. Platform-specific defaultSystemPluginDirs.
//
// [ConfigFile.CLIPluginsExtraDirs]: https://pkg.go.dev/github.com/docker/cli@v26.1.4+incompatible/cli/config/configfile#ConfigFile.CLIPluginsExtraDirs
func getPluginDirs(cfg *configfile.ConfigFile) ([]string, error) {
func getPluginDirs(cfg *configfile.ConfigFile) []string {
var pluginDirs []string
if cfg != nil {
pluginDirs = append(pluginDirs, cfg.CLIPluginsExtraDirs...)
}
pluginDir, err := config.Path("cli-plugins")
if err != nil {
return nil, err
}
pluginDir := filepath.Join(config.Dir(), "cli-plugins")
pluginDirs = append(pluginDirs, pluginDir)
pluginDirs = append(pluginDirs, defaultSystemPluginDirs...)
return pluginDirs, nil
return pluginDirs
}
func addPluginCandidatesFromDir(res map[string][]string, d string) error {
func addPluginCandidatesFromDir(res map[string][]string, d string) {
dentries, err := os.ReadDir(d)
// Silently ignore any directories which we cannot list (e.g. due to
// permissions or anything else) or which is not a directory
if err != nil {
return err
return
}
for _, dentry := range dentries {
switch dentry.Type() & os.ModeType {
switch dentry.Type() & os.ModeType { //nolint:exhaustive,nolintlint // no need to include all possible file-modes in this list
case 0, os.ModeSymlink:
// Regular file or symlink, keep going
default:
@ -89,52 +89,35 @@ func addPluginCandidatesFromDir(res map[string][]string, d string) error {
continue
}
name := dentry.Name()
if !strings.HasPrefix(name, NamePrefix) {
if !strings.HasPrefix(name, metadata.NamePrefix) {
continue
}
name = strings.TrimPrefix(name, NamePrefix)
name = strings.TrimPrefix(name, metadata.NamePrefix)
var err error
if name, err = trimExeSuffix(name); err != nil {
continue
}
res[name] = append(res[name], filepath.Join(d, dentry.Name()))
}
return nil
}
// listPluginCandidates returns a map from plugin name to the list of (unvalidated) Candidates. The list is in descending order of priority.
func listPluginCandidates(dirs []string) (map[string][]string, error) {
func listPluginCandidates(dirs []string) map[string][]string {
result := make(map[string][]string)
for _, d := range dirs {
// Silently ignore any directories which we cannot
// Stat (e.g. due to permissions or anything else) or
// which is not a directory.
if fi, err := os.Stat(d); err != nil || !fi.IsDir() {
continue
}
if err := addPluginCandidatesFromDir(result, d); err != nil {
// Silently ignore paths which don't exist.
if os.IsNotExist(err) {
continue
}
return nil, err // Or return partial result?
}
addPluginCandidatesFromDir(result, d)
}
return result, nil
return result
}
// GetPlugin returns a plugin on the system by its name
func GetPlugin(name string, dockerCli command.Cli, rootcmd *cobra.Command) (*Plugin, error) {
pluginDirs, err := getPluginDirs(dockerCli.ConfigFile())
if err != nil {
return nil, err
}
candidates, err := listPluginCandidates(pluginDirs)
if err != nil {
return nil, err
}
func GetPlugin(name string, dockerCLI config.Provider, rootcmd *cobra.Command) (*Plugin, error) {
pluginDirs := getPluginDirs(dockerCLI.ConfigFile())
return getPlugin(name, pluginDirs, rootcmd)
}
func getPlugin(name string, pluginDirs []string, rootcmd *cobra.Command) (*Plugin, error) {
candidates := listPluginCandidates(pluginDirs)
if paths, ok := candidates[name]; ok {
if len(paths) == 0 {
return nil, errPluginNotFound(name)
@ -154,20 +137,21 @@ func GetPlugin(name string, dockerCli command.Cli, rootcmd *cobra.Command) (*Plu
}
// ListPlugins produces a list of the plugins available on the system
func ListPlugins(dockerCli command.Cli, rootcmd *cobra.Command) ([]Plugin, error) {
pluginDirs, err := getPluginDirs(dockerCli.ConfigFile())
if err != nil {
return nil, err
}
candidates, err := listPluginCandidates(pluginDirs)
if err != nil {
return nil, err
func ListPlugins(dockerCli config.Provider, rootcmd *cobra.Command) ([]Plugin, error) {
pluginDirs := getPluginDirs(dockerCli.ConfigFile())
candidates := listPluginCandidates(pluginDirs)
if len(candidates) == 0 {
return nil, nil
}
var plugins []Plugin
var mu sync.Mutex
eg, _ := errgroup.WithContext(context.TODO())
ctx := rootcmd.Context()
if ctx == nil {
// Fallback, mostly for tests that pass a bare cobra.command
ctx = context.Background()
}
eg, _ := errgroup.WithContext(ctx)
cmds := rootcmd.Commands()
for _, paths := range candidates {
func(paths []string) {
@ -204,7 +188,7 @@ func ListPlugins(dockerCli command.Cli, rootcmd *cobra.Command) ([]Plugin, error
// PluginRunCommand returns an "os/exec".Cmd which when .Run() will execute the named plugin.
// The rootcmd argument is referenced to determine the set of builtin commands in order to detect conficts.
// The error returned satisfies the IsNotFound() predicate if no plugin was found or if the first candidate plugin was invalid somehow.
func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command) (*exec.Cmd, error) {
func PluginRunCommand(dockerCli config.Provider, name string, rootcmd *cobra.Command) (*exec.Cmd, error) {
// This uses the full original args, not the args which may
// have been provided by cobra to our caller. This is because
// they lack e.g. global options which we must propagate here.
@ -214,11 +198,8 @@ func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command
// fallback to their "invalid" command path.
return nil, errPluginNotFound(name)
}
exename := addExeSuffix(NamePrefix + name)
pluginDirs, err := getPluginDirs(dockerCli.ConfigFile())
if err != nil {
return nil, err
}
exename := addExeSuffix(metadata.NamePrefix + name)
pluginDirs := getPluginDirs(dockerCli.ConfigFile())
for _, d := range pluginDirs {
path := filepath.Join(d, exename)
@ -240,7 +221,8 @@ func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command
// TODO: why are we not returning plugin.Err?
return nil, errPluginNotFound(name)
}
cmd := exec.Command(plugin.Path, args...)
cmd := exec.Command(plugin.Path, args...) // #nosec G204 -- ignore "Subprocess launched with a potential tainted input or cmd arguments"
// Using dockerCli.{In,Out,Err}() here results in a hang until something is input.
// See: - https://github.com/golang/go/issues/10338
// - https://github.com/golang/go/commit/d000e8742a173aa0659584aa01b7ba2834ba28ab
@ -250,7 +232,7 @@ func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(cmd.Environ(), ReexecEnvvar+"="+os.Args[0])
cmd.Env = append(cmd.Environ(), metadata.ReexecEnvvar+"="+os.Args[0])
cmd.Env = appendPluginResourceAttributesEnvvar(cmd.Env, rootcmd, plugin)
return cmd, nil
@ -260,5 +242,5 @@ func PluginRunCommand(dockerCli command.Cli, name string, rootcmd *cobra.Command
// IsPluginCommand checks if the given cmd is a plugin-stub.
func IsPluginCommand(cmd *cobra.Command) bool {
return cmd.Annotations[CommandAnnotationPlugin] == "true"
return cmd.Annotations[metadata.CommandAnnotationPlugin] == "true"
}

View File

@ -1,6 +1,7 @@
package manager
import (
"path/filepath"
"strings"
"testing"
@ -51,8 +52,7 @@ func TestListPluginCandidates(t *testing.T) {
dirs = append(dirs, dir.Join(d))
}
candidates, err := listPluginCandidates(dirs)
assert.NilError(t, err)
candidates := listPluginCandidates(dirs)
exp := map[string][]string{
"plugin1": {
dir.Join("plugins1", "docker-plugin1"),
@ -82,6 +82,35 @@ func TestListPluginCandidates(t *testing.T) {
assert.DeepEqual(t, candidates, exp)
}
func TestListPluginCandidatesEmpty(t *testing.T) {
tmpDir := t.TempDir()
candidates := listPluginCandidates([]string{tmpDir, filepath.Join(tmpDir, "no-such-dir")})
assert.Assert(t, len(candidates) == 0)
}
// Regression test for https://github.com/docker/cli/issues/5643.
// Check that inaccessible directories that come before accessible ones are ignored
// and do not prevent the latter from being processed.
func TestListPluginCandidatesInaccesibleDir(t *testing.T) {
dir := fs.NewDir(t, t.Name(),
fs.WithDir("no-perm", fs.WithMode(0)),
fs.WithDir("plugins",
fs.WithFile("docker-buildx", ""),
),
)
defer dir.Remove()
candidates := listPluginCandidates([]string{
dir.Join("no-perm"),
dir.Join("plugins"),
})
assert.DeepEqual(t, candidates, map[string][]string{
"buildx": {
dir.Join("plugins", "docker-buildx"),
},
})
}
func TestGetPlugin(t *testing.T) {
dir := fs.NewDir(t, t.Name(),
fs.WithFile("docker-bbb", `
@ -144,14 +173,11 @@ func TestErrPluginNotFound(t *testing.T) {
func TestGetPluginDirs(t *testing.T) {
cli := test.NewFakeCli(nil)
pluginDir, err := config.Path("cli-plugins")
assert.NilError(t, err)
pluginDir := filepath.Join(config.Dir(), "cli-plugins")
expected := append([]string{pluginDir}, defaultSystemPluginDirs...)
var pluginDirs []string
pluginDirs, err = getPluginDirs(cli.ConfigFile())
pluginDirs := getPluginDirs(cli.ConfigFile())
assert.Equal(t, strings.Join(expected, ":"), strings.Join(pluginDirs, ":"))
assert.NilError(t, err)
extras := []string{
"foo", "bar", "baz",
@ -160,7 +186,6 @@ func TestGetPluginDirs(t *testing.T) {
cli.SetConfigFile(&configfile.ConfigFile{
CLIPluginsExtraDirs: extras,
})
pluginDirs, err = getPluginDirs(cli.ConfigFile())
pluginDirs = getPluginDirs(cli.ConfigFile())
assert.DeepEqual(t, expected, pluginDirs)
assert.NilError(t, err)
}

View File

@ -1,30 +1,23 @@
package manager
import (
"github.com/docker/cli/cli-plugins/metadata"
)
const (
// NamePrefix is the prefix required on all plugin binary names
NamePrefix = "docker-"
NamePrefix = metadata.NamePrefix
// MetadataSubcommandName is the name of the plugin subcommand
// which must be supported by every plugin and returns the
// plugin metadata.
MetadataSubcommandName = "docker-cli-plugin-metadata"
MetadataSubcommandName = metadata.MetadataSubcommandName
// HookSubcommandName is the name of the plugin subcommand
// which must be implemented by plugins declaring support
// for hooks in their metadata.
HookSubcommandName = "docker-cli-plugin-hooks"
HookSubcommandName = metadata.HookSubcommandName
)
// Metadata provided by the plugin.
type Metadata struct {
// SchemaVersion describes the version of this struct. Mandatory, must be "0.1.0"
SchemaVersion string `json:",omitempty"`
// Vendor is the name of the plugin vendor. Mandatory
Vendor string `json:",omitempty"`
// Version is the optional version of this plugin.
Version string `json:",omitempty"`
// ShortDescription should be suitable for a single line help message.
ShortDescription string `json:",omitempty"`
// URL is a pointer to the plugin's homepage.
URL string `json:",omitempty"`
}
type Metadata = metadata.Metadata

View File

@ -3,21 +3,23 @@ package manager
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/internal/lazyregexp"
"github.com/spf13/cobra"
)
var pluginNameRe = regexp.MustCompile("^[a-z][a-z0-9]*$")
var pluginNameRe = lazyregexp.New("^[a-z][a-z0-9]*$")
// Plugin represents a potential plugin with all it's metadata.
type Plugin struct {
Metadata
metadata.Metadata
Name string `json:",omitempty"`
Path string `json:",omitempty"`
@ -44,18 +46,18 @@ func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) {
// which would fail here, so there are all real errors.
fullname := filepath.Base(path)
if fullname == "." {
return Plugin{}, errors.Errorf("unable to determine basename of plugin candidate %q", path)
return Plugin{}, fmt.Errorf("unable to determine basename of plugin candidate %q", path)
}
var err error
if fullname, err = trimExeSuffix(fullname); err != nil {
return Plugin{}, errors.Wrapf(err, "plugin candidate %q", path)
return Plugin{}, fmt.Errorf("plugin candidate %q: %w", path, err)
}
if !strings.HasPrefix(fullname, NamePrefix) {
return Plugin{}, errors.Errorf("plugin candidate %q: does not have %q prefix", path, NamePrefix)
if !strings.HasPrefix(fullname, metadata.NamePrefix) {
return Plugin{}, fmt.Errorf("plugin candidate %q: does not have %q prefix", path, metadata.NamePrefix)
}
p := Plugin{
Name: strings.TrimPrefix(fullname, NamePrefix),
Name: strings.TrimPrefix(fullname, metadata.NamePrefix),
Path: path,
}
@ -112,9 +114,9 @@ func (p *Plugin) RunHook(ctx context.Context, hookData HookPluginData) ([]byte,
return nil, wrapAsPluginError(err, "failed to marshall hook data")
}
pCmd := exec.CommandContext(ctx, p.Path, p.Name, HookSubcommandName, string(hDataBytes))
pCmd := exec.CommandContext(ctx, p.Path, p.Name, metadata.HookSubcommandName, string(hDataBytes)) // #nosec G204 -- ignore "Subprocess launched with a potential tainted input or cmd arguments"
pCmd.Env = os.Environ()
pCmd.Env = append(pCmd.Env, ReexecEnvvar+"="+os.Args[0])
pCmd.Env = append(pCmd.Env, metadata.ReexecEnvvar+"="+os.Args[0])
hookCmdOutput, err := pCmd.Output()
if err != nil {
return nil, wrapAsPluginError(err, "failed to execute plugin hook subcommand")

View File

@ -1,22 +1,16 @@
package manager
import (
"fmt"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
// This is made slightly more complex due to needing to be case insensitive.
// This is made slightly more complex due to needing to be case-insensitive.
func trimExeSuffix(s string) (string, error) {
ext := filepath.Ext(s)
if ext == "" {
return "", errors.Errorf("path %q lacks required file extension", s)
}
exe := ".exe"
if !strings.EqualFold(ext, exe) {
return "", errors.Errorf("path %q lacks required %q suffix", s, exe)
if ext == "" || !strings.EqualFold(ext, ".exe") {
return "", fmt.Errorf("path %q lacks required file extension (.exe)", s)
}
return strings.TrimSuffix(s, ext), nil
}

View File

@ -0,0 +1,85 @@
package manager
import (
"fmt"
"os"
"strings"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/baggage"
)
const (
// resourceAttributesEnvVar is the name of the envvar that includes additional
// resource attributes for OTEL as defined in the [OpenTelemetry specification].
//
// [OpenTelemetry specification]: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration
resourceAttributesEnvVar = "OTEL_RESOURCE_ATTRIBUTES"
// dockerCLIAttributePrefix is the prefix for any docker cli OTEL attributes.
//
// It is a copy of the const defined in [command.dockerCLIAttributePrefix].
dockerCLIAttributePrefix = "docker.cli."
cobraCommandPath = attribute.Key("cobra.command_path")
)
func getPluginResourceAttributes(cmd *cobra.Command, plugin Plugin) attribute.Set {
commandPath := cmd.Annotations[metadata.CommandAnnotationPluginCommandPath]
if commandPath == "" {
commandPath = fmt.Sprintf("%s %s", cmd.CommandPath(), plugin.Name)
}
attrSet := attribute.NewSet(
cobraCommandPath.String(commandPath),
)
kvs := make([]attribute.KeyValue, 0, attrSet.Len())
for iter := attrSet.Iter(); iter.Next(); {
attr := iter.Attribute()
kvs = append(kvs, attribute.KeyValue{
Key: dockerCLIAttributePrefix + attr.Key,
Value: attr.Value,
})
}
return attribute.NewSet(kvs...)
}
func appendPluginResourceAttributesEnvvar(env []string, cmd *cobra.Command, plugin Plugin) []string {
if attrs := getPluginResourceAttributes(cmd, plugin); attrs.Len() > 0 {
// Construct baggage members for each of the attributes.
// Ignore any failures as these aren't significant and
// represent an internal issue.
members := make([]baggage.Member, 0, attrs.Len())
for iter := attrs.Iter(); iter.Next(); {
attr := iter.Attribute()
m, err := baggage.NewMemberRaw(string(attr.Key), attr.Value.AsString())
if err != nil {
otel.Handle(err)
continue
}
members = append(members, m)
}
// Combine plugin added resource attributes with ones found in the environment
// variable. Our own attributes should be namespaced so there shouldn't be a
// conflict. We do not parse the environment variable because we do not want
// to handle errors in user configuration.
attrsSlice := make([]string, 0, 2)
if v := strings.TrimSpace(os.Getenv(resourceAttributesEnvVar)); v != "" {
attrsSlice = append(attrsSlice, v)
}
if b, err := baggage.New(members...); err != nil {
otel.Handle(err)
} else if b.Len() > 0 {
attrsSlice = append(attrsSlice, b.String())
}
if len(attrsSlice) > 0 {
env = append(env, resourceAttributesEnvVar+"="+strings.Join(attrsSlice, ","))
}
}
return env
}

View File

@ -0,0 +1,28 @@
package metadata
const (
// CommandAnnotationPlugin is added to every stub command added by
// AddPluginCommandStubs with the value "true" and so can be
// used to distinguish plugin stubs from regular commands.
CommandAnnotationPlugin = "com.docker.cli.plugin"
// CommandAnnotationPluginVendor is added to every stub command
// added by AddPluginCommandStubs and contains the vendor of
// that plugin.
CommandAnnotationPluginVendor = "com.docker.cli.plugin.vendor"
// CommandAnnotationPluginVersion is added to every stub command
// added by AddPluginCommandStubs and contains the version of
// that plugin.
CommandAnnotationPluginVersion = "com.docker.cli.plugin.version"
// CommandAnnotationPluginInvalid is added to any stub command
// added by AddPluginCommandStubs for an invalid command (that
// is, one which failed it's candidate test) and contains the
// reason for the failure.
CommandAnnotationPluginInvalid = "com.docker.cli.plugin-invalid"
// CommandAnnotationPluginCommandPath is added to overwrite the
// command path for a plugin invocation.
CommandAnnotationPluginCommandPath = "com.docker.cli.plugin.command_path"
)

View File

@ -0,0 +1,36 @@
package metadata
const (
// NamePrefix is the prefix required on all plugin binary names
NamePrefix = "docker-"
// MetadataSubcommandName is the name of the plugin subcommand
// which must be supported by every plugin and returns the
// plugin metadata.
MetadataSubcommandName = "docker-cli-plugin-metadata"
// HookSubcommandName is the name of the plugin subcommand
// which must be implemented by plugins declaring support
// for hooks in their metadata.
HookSubcommandName = "docker-cli-plugin-hooks"
// ReexecEnvvar is the name of an ennvar which is set to the command
// used to originally invoke the docker CLI when executing a
// plugin. Assuming $PATH and $CWD remain unchanged this should allow
// the plugin to re-execute the original CLI.
ReexecEnvvar = "DOCKER_CLI_PLUGIN_ORIGINAL_CLI_COMMAND"
)
// Metadata provided by the plugin.
type Metadata struct {
// SchemaVersion describes the version of this struct. Mandatory, must be "0.1.0"
SchemaVersion string `json:",omitempty"`
// Vendor is the name of the plugin vendor. Mandatory
Vendor string `json:",omitempty"`
// Version is the optional version of this plugin.
Version string `json:",omitempty"`
// ShortDescription should be suitable for a single line help message.
ShortDescription string `json:",omitempty"`
// URL is a pointer to the plugin's homepage.
URL string `json:",omitempty"`
}

View File

@ -3,17 +3,18 @@ package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli-plugins/manager"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/cli-plugins/socket"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/connhelper"
"github.com/docker/cli/cli/debug"
"github.com/docker/docker/client"
"github.com/moby/moby/client"
"github.com/spf13/cobra"
"go.opentelemetry.io/otel"
)
@ -29,12 +30,12 @@ import (
var PersistentPreRunE func(*cobra.Command, []string) error
// RunPlugin executes the specified plugin command
func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager.Metadata) error {
func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta metadata.Metadata) error {
tcmd := newPluginCommand(dockerCli, plugin, meta)
var persistentPreRunOnce sync.Once
PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
var err error
var retErr error
persistentPreRunOnce.Do(func() {
ctx, cancel := context.WithCancel(cmd.Context())
cmd.SetContext(ctx)
@ -46,7 +47,7 @@ func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager
opts = append(opts, withPluginClientConn(plugin.Name()))
}
opts = append(opts, command.WithEnableGlobalMeterProvider(), command.WithEnableGlobalTracerProvider())
err = tcmd.Initialize(opts...)
retErr = tcmd.Initialize(opts...)
ogRunE := cmd.RunE
if ogRunE == nil {
ogRun := cmd.Run
@ -66,7 +67,7 @@ func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager
return err
}
})
return err
return retErr
}
cmd, args, err := tcmd.HandleGlobalFlags()
@ -80,7 +81,7 @@ func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager
}
// Run is the top-level entry point to the CLI plugin framework. It should be called from your plugin's `main()` function.
func Run(makeCmd func(command.Cli) *cobra.Command, meta manager.Metadata) {
func Run(makeCmd func(command.Cli) *cobra.Command, meta metadata.Metadata) {
otel.SetErrorHandler(debug.OTELErrorHandler)
dockerCli, err := command.NewDockerCli()
@ -92,26 +93,25 @@ func Run(makeCmd func(command.Cli) *cobra.Command, meta manager.Metadata) {
plugin := makeCmd(dockerCli)
if err := RunPlugin(dockerCli, plugin, meta); err != nil {
if sterr, ok := err.(cli.StatusError); ok {
if sterr.Status != "" {
fmt.Fprintln(dockerCli.Err(), sterr.Status)
}
var stErr cli.StatusError
if errors.As(err, &stErr) {
// StatusError should only be used for errors, and all errors should
// have a non-zero exit status, so never exit with 0
if sterr.StatusCode == 0 {
os.Exit(1)
if stErr.StatusCode == 0 { // FIXME(thaJeztah): this should never be used with a zero status-code. Check if we do this anywhere.
stErr.StatusCode = 1
}
os.Exit(sterr.StatusCode)
_, _ = fmt.Fprintln(dockerCli.Err(), stErr)
os.Exit(stErr.StatusCode)
}
fmt.Fprintln(dockerCli.Err(), err)
_, _ = fmt.Fprintln(dockerCli.Err(), err)
os.Exit(1)
}
}
func withPluginClientConn(name string) command.CLIOption {
return command.WithInitializeClient(func(dockerCli *command.DockerCli) (client.APIClient, error) {
return func(cli *command.DockerCli) error {
cmd := "docker"
if x := os.Getenv(manager.ReexecEnvvar); x != "" {
if x := os.Getenv(metadata.ReexecEnvvar); x != "" {
cmd = x
}
var flags []string
@ -133,16 +133,19 @@ func withPluginClientConn(name string) command.CLIOption {
helper, err := connhelper.GetCommandConnectionHelper(cmd, flags...)
if err != nil {
return nil, err
return err
}
return client.NewClientWithOpts(client.WithDialContext(helper.Dialer))
})
apiClient, err := client.NewClientWithOpts(client.WithDialContext(helper.Dialer))
if err != nil {
return err
}
return command.WithAPIClient(apiClient)(cli)
}
}
func newPluginCommand(dockerCli *command.DockerCli, plugin *cobra.Command, meta manager.Metadata) *cli.TopLevelCommand {
func newPluginCommand(dockerCli *command.DockerCli, plugin *cobra.Command, meta metadata.Metadata) *cli.TopLevelCommand {
name := plugin.Name()
fullname := manager.NamePrefix + name
fullname := metadata.NamePrefix + name
cmd := &cobra.Command{
Use: fmt.Sprintf("docker [OPTIONS] %s [ARG...]", name),
@ -158,7 +161,7 @@ func newPluginCommand(dockerCli *command.DockerCli, plugin *cobra.Command, meta
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: false,
HiddenDefaultCmd: true,
DisableDescriptions: true,
DisableDescriptions: os.Getenv("DOCKER_CLI_DISABLE_COMPLETION_DESCRIPTION") != "",
},
}
opts, _ := cli.SetupPluginRootCommand(cmd)
@ -177,12 +180,12 @@ func newPluginCommand(dockerCli *command.DockerCli, plugin *cobra.Command, meta
return cli.NewTopLevelCommand(cmd, dockerCli, opts, cmd.Flags())
}
func newMetadataSubcommand(plugin *cobra.Command, meta manager.Metadata) *cobra.Command {
func newMetadataSubcommand(plugin *cobra.Command, meta metadata.Metadata) *cobra.Command {
if meta.ShortDescription == "" {
meta.ShortDescription = plugin.Short
}
cmd := &cobra.Command{
Use: manager.MetadataSubcommandName,
Use: metadata.MetadataSubcommandName,
Hidden: true,
// Suppress the global/parent PersistentPreRunE, which
// needlessly initializes the client and tries to
@ -200,8 +203,8 @@ func newMetadataSubcommand(plugin *cobra.Command, meta manager.Metadata) *cobra.
// RunningStandalone tells a CLI plugin it is run standalone by direct execution
func RunningStandalone() bool {
if os.Getenv(manager.ReexecEnvvar) != "" {
if os.Getenv(metadata.ReexecEnvvar) != "" {
return false
}
return len(os.Args) < 2 || os.Args[1] != manager.MetadataSubcommandName
return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName
}

View File

@ -95,6 +95,9 @@ func (pl *PluginServer) Addr() net.Addr {
//
// The error value is that of the underlying [net.Listner.Close] call.
func (pl *PluginServer) Close() error {
if pl == nil {
return nil
}
logrus.Trace("Closing plugin server")
// Close connections first to ensure the connections get io.EOF instead
// of a connection reset.

View File

@ -117,6 +117,18 @@ func TestPluginServer(t *testing.T) {
assert.NilError(t, err, "failed to dial returned server")
checkDirNoNewPluginServer(t)
})
t.Run("does not panic on Close if server is nil", func(t *testing.T) {
var srv *PluginServer
defer func() {
if r := recover(); r != nil {
t.Errorf("panicked on Close")
}
}()
err := srv.Close()
assert.NilError(t, err)
})
}
func checkDirNoNewPluginServer(t *testing.T) {
@ -166,24 +178,39 @@ func TestConnectAndWait(t *testing.T) {
// TODO: this test cannot be executed with `t.Parallel()`, due to
// relying on goroutine numbers to ensure correct behaviour
t.Run("connect goroutine exits after EOF", func(t *testing.T) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
srv, err := NewPluginServer(nil)
assert.NilError(t, err, "failed to setup server")
defer srv.Close()
t.Setenv(EnvKey, srv.Addr().String())
runtime.Gosched()
numGoroutines := runtime.NumGoroutine()
ConnectAndWait(func() {})
assert.Equal(t, runtime.NumGoroutine(), numGoroutines+1)
runtime.Gosched()
poll.WaitOn(t, func(t poll.LogT) poll.Result {
// +1 goroutine for the poll.WaitOn
// +1 goroutine for the connect goroutine
if runtime.NumGoroutine() < numGoroutines+1+1 {
return poll.Continue("waiting for connect goroutine to spawn")
}
return poll.Success()
}, poll.WithDelay(1*time.Millisecond), poll.WithTimeout(500*time.Millisecond))
srv.Close()
runtime.Gosched()
poll.WaitOn(t, func(t poll.LogT) poll.Result {
// +1 goroutine for the poll.WaitOn
if runtime.NumGoroutine() > numGoroutines+1 {
return poll.Continue("waiting for connect goroutine to exit")
}
return poll.Success()
}, poll.WithDelay(1*time.Millisecond), poll.WithTimeout(10*time.Millisecond))
}, poll.WithDelay(1*time.Millisecond), poll.WithTimeout(500*time.Millisecond))
})
}

View File

@ -3,15 +3,12 @@ package cli
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
pluginmanager "github.com/docker/cli/cli-plugins/manager"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/cli/command"
cliflags "github.com/docker/cli/cli/flags"
"github.com/docker/docker/pkg/homedir"
"github.com/docker/docker/registry"
"github.com/fvbommel/sortorder"
"github.com/moby/term"
"github.com/morikuni/aec"
@ -62,13 +59,6 @@ func setupCommonRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *c
"docs.code-delimiter": `"`, // https://github.com/docker/cli-docs-tool/blob/77abede22166eaea4af7335096bdcedd043f5b19/annotation/annotation.go#L20-L22
}
// Configure registry.CertsDir() when running in rootless-mode
if os.Getenv("ROOTLESSKIT_STATE_DIR") != "" {
if configHome, err := homedir.GetConfigHome(); err == nil {
registry.SetCertsDir(filepath.Join(configHome, "docker/certs.d"))
}
}
return opts, helpCommand
}
@ -92,12 +82,8 @@ func FlagErrorFunc(cmd *cobra.Command, err error) error {
return nil
}
usage := ""
if cmd.HasSubCommands() {
usage = "\n\n" + cmd.UsageString()
}
return StatusError{
Status: fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage),
Status: fmt.Sprintf("%s\n\nUsage: %s\n\nRun '%s --help' for more information", err, cmd.UseLine(), cmd.CommandPath()),
StatusCode: 125,
}
}
@ -256,7 +242,7 @@ func hasAdditionalHelp(cmd *cobra.Command) bool {
}
func isPlugin(cmd *cobra.Command) bool {
return pluginmanager.IsPluginCommand(cmd)
return cmd.Annotations[metadata.CommandAnnotationPlugin] == "true"
}
func hasAliases(cmd *cobra.Command) bool {
@ -341,8 +327,10 @@ func operationSubCommands(cmd *cobra.Command) []*cobra.Command {
return cmds
}
const defaultTermWidth = 80
func wrappedFlagUsages(cmd *cobra.Command) string {
width := 80
width := defaultTermWidth
if ws, err := term.GetWinsize(0); err == nil {
width = int(ws.Width)
}
@ -358,9 +346,9 @@ func decoratedName(cmd *cobra.Command) string {
}
func vendorAndVersion(cmd *cobra.Command) string {
if vendor, ok := cmd.Annotations[pluginmanager.CommandAnnotationPluginVendor]; ok && isPlugin(cmd) {
if vendor, ok := cmd.Annotations[metadata.CommandAnnotationPluginVendor]; ok && isPlugin(cmd) {
version := ""
if v, ok := cmd.Annotations[pluginmanager.CommandAnnotationPluginVersion]; ok && v != "" {
if v, ok := cmd.Annotations[metadata.CommandAnnotationPluginVersion]; ok && v != "" {
version = ", " + v
}
return fmt.Sprintf("(%s%s)", vendor, version)
@ -419,7 +407,7 @@ func invalidPlugins(cmd *cobra.Command) []*cobra.Command {
}
func invalidPluginReason(cmd *cobra.Command) string {
return cmd.Annotations[pluginmanager.CommandAnnotationPluginInvalid]
return cmd.Annotations[metadata.CommandAnnotationPluginInvalid]
}
const usageTemplate = `Usage:
@ -522,4 +510,4 @@ Run '{{.CommandPath}} COMMAND --help' for more information on a command.
`
const helpTemplate = `
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
{{- if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`

View File

@ -3,7 +3,7 @@ package cli
import (
"testing"
pluginmanager "github.com/docker/cli/cli-plugins/manager"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
@ -49,9 +49,9 @@ func TestVendorAndVersion(t *testing.T) {
cmd := &cobra.Command{
Use: "test",
Annotations: map[string]string{
pluginmanager.CommandAnnotationPlugin: "true",
pluginmanager.CommandAnnotationPluginVendor: tc.vendor,
pluginmanager.CommandAnnotationPluginVersion: tc.version,
metadata.CommandAnnotationPlugin: "true",
metadata.CommandAnnotationPluginVendor: tc.vendor,
metadata.CommandAnnotationPluginVersion: tc.version,
},
}
assert.Equal(t, vendorAndVersion(cmd), tc.expected)
@ -69,8 +69,8 @@ func TestInvalidPlugin(t *testing.T) {
assert.Assert(t, is.Len(invalidPlugins(root), 0))
sub1.Annotations = map[string]string{
pluginmanager.CommandAnnotationPlugin: "true",
pluginmanager.CommandAnnotationPluginInvalid: "foo",
metadata.CommandAnnotationPlugin: "true",
metadata.CommandAnnotationPluginInvalid: "foo",
}
root.AddCommand(sub1, sub2)
sub1.AddCommand(sub1sub1, sub1sub2)
@ -100,6 +100,6 @@ func TestDecoratedName(t *testing.T) {
topLevelCommand := &cobra.Command{Use: "pluginTopLevelCommand"}
root.AddCommand(topLevelCommand)
assert.Equal(t, decoratedName(topLevelCommand), "pluginTopLevelCommand ")
topLevelCommand.Annotations = map[string]string{pluginmanager.CommandAnnotationPlugin: "true"}
topLevelCommand.Annotations = map[string]string{metadata.CommandAnnotationPlugin: "true"}
assert.Equal(t, decoratedName(topLevelCommand), "pluginTopLevelCommand*")
}

View File

@ -3,16 +3,16 @@ package builder
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/build"
"github.com/moby/moby/client"
)
type fakeClient struct {
client.Client
builderPruneFunc func(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error)
builderPruneFunc func(ctx context.Context, opts build.CachePruneOptions) (*build.CachePruneReport, error)
}
func (c *fakeClient) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) {
func (c *fakeClient) BuildCachePrune(ctx context.Context, opts build.CachePruneOptions) (*build.CachePruneReport, error) {
if c.builderPruneFunc != nil {
return c.builderPruneFunc(ctx, opts)
}

View File

@ -23,3 +23,22 @@ func NewBuilderCommand(dockerCli command.Cli) *cobra.Command {
)
return cmd
}
// NewBakeStubCommand returns a cobra command "stub" for the "bake" subcommand.
// This command is a placeholder / stub that is dynamically replaced by an
// alias for "docker buildx bake" if BuildKit is enabled (and the buildx plugin
// installed).
func NewBakeStubCommand(dockerCLI command.Streams) *cobra.Command {
return &cobra.Command{
Use: "bake [OPTIONS] [TARGET...]",
Short: "Build from a file",
RunE: command.ShowHelp(dockerCLI.Err()),
Annotations: map[string]string{
// We want to show this command in the "top" category in --help
// output, and not to be grouped under "management commands".
"category-top": "5",
"aliases": "docker buildx bake",
"version": "1.31",
},
}
}

View File

@ -9,10 +9,10 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/internal/prompt"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types"
"github.com/docker/docker/errdefs"
units "github.com/docker/go-units"
"github.com/docker/go-units"
"github.com/moby/moby/api/types/build"
"github.com/spf13/cobra"
)
@ -69,18 +69,18 @@ func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions)
warning = allCacheWarning
}
if !options.force {
r, err := command.PromptForConfirmation(ctx, dockerCli.In(), dockerCli.Out(), warning)
r, err := prompt.Confirm(ctx, dockerCli.In(), dockerCli.Out(), warning)
if err != nil {
return 0, "", err
}
if !r {
return 0, "", errdefs.Cancelled(errors.New("builder prune has been cancelled"))
return 0, "", cancelledErr{errors.New("builder prune has been cancelled")}
}
}
report, err := dockerCli.Client().BuildCachePrune(ctx, types.BuildCachePruneOptions{
report, err := dockerCli.Client().BuildCachePrune(ctx, build.CachePruneOptions{
All: options.all,
KeepStorage: options.keepStorage.Value(),
KeepStorage: options.keepStorage.Value(), // FIXME(thaJeztah): rewrite to use new options; see https://github.com/moby/moby/pull/48720
Filters: pruneFilters,
})
if err != nil {
@ -100,6 +100,10 @@ func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions)
return report.SpaceReclaimed, output, nil
}
type cancelledErr struct{ error }
func (cancelledErr) Cancelled() {}
// CachePrune executes a prune command for build cache
func CachePrune(ctx context.Context, dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
return runPrune(ctx, dockerCli, pruneOptions{force: true, all: all, filter: filter})

View File

@ -3,10 +3,11 @@ package builder
import (
"context"
"errors"
"io"
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types"
"github.com/moby/moby/api/types/build"
)
func TestBuilderPromptTermination(t *testing.T) {
@ -14,10 +15,12 @@ func TestBuilderPromptTermination(t *testing.T) {
t.Cleanup(cancel)
cli := test.NewFakeCli(&fakeClient{
builderPruneFunc: func(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) {
builderPruneFunc: func(ctx context.Context, opts build.CachePruneOptions) (*build.CachePruneReport, error) {
return nil, errors.New("fakeClient builderPruneFunc should not be called")
},
})
cmd := NewPruneCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
test.TerminatePrompt(ctx, t, cmd, cli)
}

View File

@ -3,8 +3,8 @@ package checkpoint
import (
"context"
"github.com/docker/docker/api/types/checkpoint"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/checkpoint"
"github.com/moby/moby/client"
)
type fakeClient struct {

View File

@ -7,7 +7,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/docker/api/types/checkpoint"
"github.com/moby/moby/api/types/checkpoint"
"github.com/spf13/cobra"
)
@ -40,8 +40,8 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd
}
func runCreate(ctx context.Context, dockerCli command.Cli, opts createOptions) error {
err := dockerCli.Client().CheckpointCreate(ctx, opts.container, checkpoint.CreateOptions{
func runCreate(ctx context.Context, dockerCLI command.Cli, opts createOptions) error {
err := dockerCLI.Client().CheckpointCreate(ctx, opts.container, checkpoint.CreateOptions{
CheckpointID: opts.checkpoint,
CheckpointDir: opts.checkpointDir,
Exit: !opts.leaveRunning,
@ -50,6 +50,6 @@ func runCreate(ctx context.Context, dockerCli command.Cli, opts createOptions) e
return err
}
fmt.Fprintf(dockerCli.Out(), "%s\n", opts.checkpoint)
_, _ = fmt.Fprintln(dockerCLI.Out(), opts.checkpoint)
return nil
}

View File

@ -1,13 +1,14 @@
package checkpoint
import (
"errors"
"io"
"strconv"
"strings"
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types/checkpoint"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/checkpoint"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
@ -20,16 +21,16 @@ func TestCheckpointCreateErrors(t *testing.T) {
}{
{
args: []string{"too-few-arguments"},
expectedError: "requires exactly 2 arguments",
expectedError: "requires 2 arguments",
},
{
args: []string{"too", "many", "arguments"},
expectedError: "requires exactly 2 arguments",
expectedError: "requires 2 arguments",
},
{
args: []string{"foo", "bar"},
checkpointCreateFunc: func(container string, options checkpoint.CreateOptions) error {
return errors.Errorf("error creating checkpoint for container foo")
return errors.New("error creating checkpoint for container foo")
},
expectedError: "error creating checkpoint for container foo",
},
@ -42,31 +43,45 @@ func TestCheckpointCreateErrors(t *testing.T) {
cmd := newCreateCommand(cli)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}
}
func TestCheckpointCreateWithOptions(t *testing.T) {
var containerID, checkpointID, checkpointDir string
var exit bool
cli := test.NewFakeCli(&fakeClient{
checkpointCreateFunc: func(container string, options checkpoint.CreateOptions) error {
containerID = container
checkpointID = options.CheckpointID
checkpointDir = options.CheckpointDir
exit = options.Exit
return nil
},
})
cmd := newCreateCommand(cli)
cp := "checkpoint-bar"
cmd.SetArgs([]string{"container-foo", cp})
cmd.Flags().Set("leave-running", "true")
cmd.Flags().Set("checkpoint-dir", "/dir/foo")
assert.NilError(t, cmd.Execute())
assert.Check(t, is.Equal("container-foo", containerID))
assert.Check(t, is.Equal(cp, checkpointID))
assert.Check(t, is.Equal("/dir/foo", checkpointDir))
assert.Check(t, is.Equal(false, exit))
assert.Check(t, is.Equal(cp, strings.TrimSpace(cli.OutBuffer().String())))
const (
containerName = "container-foo"
checkpointName = "checkpoint-bar"
checkpointDir = "/dir/foo"
)
for _, tc := range []bool{true, false} {
leaveRunning := strconv.FormatBool(tc)
t.Run("leave-running="+leaveRunning, func(t *testing.T) {
var actualContainerName string
var actualOptions checkpoint.CreateOptions
cli := test.NewFakeCli(&fakeClient{
checkpointCreateFunc: func(container string, options checkpoint.CreateOptions) error {
actualContainerName = container
actualOptions = options
return nil
},
})
cmd := newCreateCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{containerName, checkpointName})
assert.Check(t, cmd.Flags().Set("leave-running", leaveRunning))
assert.Check(t, cmd.Flags().Set("checkpoint-dir", checkpointDir))
assert.NilError(t, cmd.Execute())
assert.Check(t, is.Equal(actualContainerName, containerName))
expected := checkpoint.CreateOptions{
CheckpointID: checkpointName,
CheckpointDir: checkpointDir,
Exit: !tc,
}
assert.Check(t, is.Equal(actualOptions, expected))
assert.Check(t, is.Equal(strings.TrimSpace(cli.OutBuffer().String()), checkpointName))
})
}
}

View File

@ -2,7 +2,7 @@ package checkpoint
import (
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types/checkpoint"
"github.com/moby/moby/api/types/checkpoint"
)
const (

View File

@ -5,7 +5,7 @@ import (
"testing"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types/checkpoint"
"github.com/moby/moby/api/types/checkpoint"
"gotest.tools/v3/assert"
)

View File

@ -7,7 +7,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types/checkpoint"
"github.com/moby/moby/api/types/checkpoint"
"github.com/spf13/cobra"
)

View File

@ -1,12 +1,12 @@
package checkpoint
import (
"errors"
"io"
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types/checkpoint"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/checkpoint"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/golden"
@ -20,16 +20,16 @@ func TestCheckpointListErrors(t *testing.T) {
}{
{
args: []string{},
expectedError: "requires exactly 1 argument",
expectedError: "requires 1 argument",
},
{
args: []string{"too", "many", "arguments"},
expectedError: "requires exactly 1 argument",
expectedError: "requires 1 argument",
},
{
args: []string{"foo"},
checkpointListFunc: func(container string, options checkpoint.ListOptions) ([]checkpoint.Summary, error) {
return []checkpoint.Summary{}, errors.Errorf("error getting checkpoints for container foo")
return []checkpoint.Summary{}, errors.New("error getting checkpoints for container foo")
},
expectedError: "error getting checkpoints for container foo",
},
@ -42,6 +42,7 @@ func TestCheckpointListErrors(t *testing.T) {
cmd := newListCommand(cli)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}
}

View File

@ -5,7 +5,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/docker/api/types/checkpoint"
"github.com/moby/moby/api/types/checkpoint"
"github.com/spf13/cobra"
)

View File

@ -1,12 +1,12 @@
package checkpoint
import (
"errors"
"io"
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types/checkpoint"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/checkpoint"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
@ -19,16 +19,16 @@ func TestCheckpointRemoveErrors(t *testing.T) {
}{
{
args: []string{"too-few-arguments"},
expectedError: "requires exactly 2 arguments",
expectedError: "requires 2 arguments",
},
{
args: []string{"too", "many", "arguments"},
expectedError: "requires exactly 2 arguments",
expectedError: "requires 2 arguments",
},
{
args: []string{"foo", "bar"},
checkpointDeleteFunc: func(container string, options checkpoint.DeleteOptions) error {
return errors.Errorf("error deleting checkpoint")
return errors.New("error deleting checkpoint")
},
expectedError: "error deleting checkpoint",
},
@ -41,6 +41,7 @@ func TestCheckpointRemoveErrors(t *testing.T) {
cmd := newRemoveCommand(cli)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}
}

View File

@ -1,5 +1,5 @@
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
//go:build go1.23
package command
@ -8,7 +8,6 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
@ -21,21 +20,14 @@ import (
"github.com/docker/cli/cli/context/store"
"github.com/docker/cli/cli/debug"
cliflags "github.com/docker/cli/cli/flags"
manifeststore "github.com/docker/cli/cli/manifest/store"
registryclient "github.com/docker/cli/cli/registry/client"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/cli/trust"
"github.com/docker/cli/cli/version"
dopts "github.com/docker/cli/opts"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
"github.com/moby/moby/api/types/build"
"github.com/moby/moby/api/types/swarm"
"github.com/moby/moby/client"
"github.com/pkg/errors"
"github.com/spf13/cobra"
notaryclient "github.com/theupdateframework/notary/client"
)
const defaultInitTimeout = 2 * time.Second
@ -53,13 +45,10 @@ type Cli interface {
Streams
SetIn(in *streams.In)
Apply(ops ...CLIOption) error
ConfigFile() *configfile.ConfigFile
config.Provider
ServerInfo() ServerInfo
NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error)
DefaultVersion() string
CurrentVersion() string
ManifestStore() manifeststore.Store
RegistryClient(bool) registryclient.RegistryClient
ContentTrustEnabled() bool
BuildKitEnabled() (bool, error)
ContextStore() store.Store
@ -69,7 +58,9 @@ type Cli interface {
}
// DockerCli is an instance the docker command line client.
// Instances of the client can be returned from NewDockerCli.
// Instances of the client should be created using the [NewDockerCli]
// constructor to make sure they are properly initialized with defaults
// set.
type DockerCli struct {
configFile *configfile.ConfigFile
options *cliflags.ClientOptions
@ -84,7 +75,7 @@ type DockerCli struct {
init sync.Once
initErr error
dockerEndpoint docker.Endpoint
contextStoreConfig store.Config
contextStoreConfig *store.Config
initTimeout time.Duration
res telemetryResource
@ -96,9 +87,9 @@ type DockerCli struct {
enableGlobalMeter, enableGlobalTracer bool
}
// DefaultVersion returns api.defaultVersion.
func (cli *DockerCli) DefaultVersion() string {
return api.DefaultVersion
// DefaultVersion returns [client.DefaultAPIVersion].
func (*DockerCli) DefaultVersion() string {
return client.DefaultAPIVersion
}
// CurrentVersion returns the API version currently negotiated, or the default
@ -106,7 +97,7 @@ func (cli *DockerCli) DefaultVersion() string {
func (cli *DockerCli) CurrentVersion() string {
_ = cli.initialize()
if cli.client == nil {
return api.DefaultVersion
return client.DefaultAPIVersion
}
return cli.client.ClientVersion()
}
@ -114,7 +105,7 @@ func (cli *DockerCli) CurrentVersion() string {
// Client returns the APIClient
func (cli *DockerCli) Client() client.APIClient {
if err := cli.initialize(); err != nil {
_, _ = fmt.Fprintf(cli.Err(), "Failed to initialize: %s\n", err)
_, _ = fmt.Fprintln(cli.Err(), "Failed to initialize:", err)
os.Exit(1)
}
return cli.client
@ -188,7 +179,7 @@ func (cli *DockerCli) BuildKitEnabled() (bool, error) {
}
si := cli.ServerInfo()
if si.BuildkitVersion == types.BuilderBuildKit {
if si.BuildkitVersion == build.BuilderBuildKit {
// The daemon advertised BuildKit as the preferred builder; this may
// be either a Linux daemon or a Windows daemon with experimental
// BuildKit support enabled.
@ -202,16 +193,16 @@ func (cli *DockerCli) BuildKitEnabled() (bool, error) {
// HooksEnabled returns whether plugin hooks are enabled.
func (cli *DockerCli) HooksEnabled() bool {
// legacy support DOCKER_CLI_HINTS env var
if v := os.Getenv("DOCKER_CLI_HINTS"); v != "" {
// use DOCKER_CLI_HOOKS env var value if set and not empty
if v := os.Getenv("DOCKER_CLI_HOOKS"); v != "" {
enabled, err := strconv.ParseBool(v)
if err != nil {
return false
}
return enabled
}
// use DOCKER_CLI_HOOKS env var value if set and not empty
if v := os.Getenv("DOCKER_CLI_HOOKS"); v != "" {
// legacy support DOCKER_CLI_HINTS env var
if v := os.Getenv("DOCKER_CLI_HINTS"); v != "" {
enabled, err := strconv.ParseBool(v)
if err != nil {
return false
@ -230,30 +221,6 @@ func (cli *DockerCli) HooksEnabled() bool {
return false
}
// ManifestStore returns a store for local manifests
func (cli *DockerCli) ManifestStore() manifeststore.Store {
// TODO: support override default location from config file
return manifeststore.NewStore(filepath.Join(config.Dir(), "manifests"))
}
// RegistryClient returns a client for communicating with a Docker distribution
// registry
func (cli *DockerCli) RegistryClient(allowInsecure bool) registryclient.RegistryClient {
resolver := func(ctx context.Context, index *registry.IndexInfo) registry.AuthConfig {
return ResolveAuthConfig(cli.ConfigFile(), index)
}
return registryclient.NewRegistryClient(resolver, UserAgent(), allowInsecure)
}
// WithInitializeClient is passed to DockerCli.Initialize by callers who wish to set a particular API Client for use by the CLI.
func WithInitializeClient(makeClient func(dockerCli *DockerCli) (client.APIClient, error)) CLIOption {
return func(dockerCli *DockerCli) error {
var err error
dockerCli.client, err = makeClient(dockerCli)
return err
}
}
// Initialize the dockerCli runs initialization that must happen after command
// line flags are parsed.
func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption) error {
@ -272,16 +239,36 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption)
debug.Enable()
}
if opts.Context != "" && len(opts.Hosts) > 0 {
return errors.New("conflicting options: either specify --host or --context, not both")
return errors.New("conflicting options: cannot specify both --host and --context")
}
if cli.contextStoreConfig == nil {
// This path can be hit when calling Initialize on a DockerCli that's
// not constructed through [NewDockerCli]. Using the default context
// store without a config set will result in Endpoints from contexts
// not being type-mapped correctly, and used as a generic "map[string]any",
// instead of a [docker.EndpointMeta].
//
// When looking up the API endpoint (using [EndpointFromContext]), no
// endpoint will be found, and a default, empty endpoint will be used
// instead which in its turn, causes newAPIClientFromEndpoint to
// be initialized with the default config instead of settings for
// the current context (which may mean; connecting with the wrong
// endpoint and/or TLS Config to be missing).
//
// [EndpointFromContext]: https://github.com/docker/cli/blob/33494921b80fd0b5a06acc3a34fa288de4bb2e6b/cli/context/docker/load.go#L139-L149
if err := WithDefaultContextStoreConfig()(cli); err != nil {
return err
}
}
cli.options = opts
cli.configFile = config.LoadDefaultConfigFile(cli.err)
cli.currentContext = resolveContextName(cli.options, cli.configFile)
cli.contextStore = &ContextStoreWithDefault{
Store: store.New(config.ContextStoreDir(), cli.contextStoreConfig),
Store: store.New(config.ContextStoreDir(), *cli.contextStoreConfig),
Resolver: func() (*DefaultContext, error) {
return ResolveDefaultContext(cli.options, cli.contextStoreConfig)
return ResolveDefaultContext(cli.options, *cli.contextStoreConfig)
},
}
@ -292,6 +279,7 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption)
if cli.enableGlobalTracer {
cli.createGlobalTracerProvider(cli.baseCtx)
}
filterResourceAttributesEnvvar()
return nil
}
@ -299,7 +287,7 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption)
// NewAPIClientFromFlags creates a new APIClient from command line flags
func NewAPIClientFromFlags(opts *cliflags.ClientOptions, configFile *configfile.ConfigFile) (client.APIClient, error) {
if opts.Context != "" && len(opts.Hosts) > 0 {
return nil, errors.New("conflicting options: either specify --host or --context, not both")
return nil, errors.New("conflicting options: cannot specify both --host and --context")
}
storeConfig := DefaultContextStoreConfig()
@ -324,7 +312,7 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF
if len(configFile.HTTPHeaders) > 0 {
opts = append(opts, client.WithHTTPHeaders(configFile.HTTPHeaders))
}
opts = append(opts, client.WithUserAgent(UserAgent()))
opts = append(opts, withCustomHeadersFromEnv(), client.WithUserAgent(UserAgent()))
return client.NewClientWithOpts(opts...)
}
@ -345,7 +333,10 @@ func resolveDockerEndpoint(s store.Reader, contextName string) (docker.Endpoint,
// Resolve the Docker endpoint for the default context (based on config, env vars and CLI flags)
func resolveDefaultDockerEndpoint(opts *cliflags.ClientOptions) (docker.Endpoint, error) {
host, err := getServerHost(opts.Hosts, opts.TLSOptions)
// defaultToTLS determines whether we should use a TLS host as default
// if nothing was configured by the user.
defaultToTLS := opts.TLSOptions != nil
host, err := getServerHost(opts.Hosts, defaultToTLS)
if err != nil {
return docker.Endpoint{}, err
}
@ -403,11 +394,6 @@ func (cli *DockerCli) initializeFromClient() {
cli.client.NegotiateAPIVersionPing(ping)
}
// NotaryClient provides a Notary Repository to interact with signed metadata for an image
func (cli *DockerCli) NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error) {
return trust.GetNotaryRepository(cli.In(), cli.Out(), UserAgent(), imgRefAndAuth.RepoInfo(), imgRefAndAuth.AuthConfig(), actions...)
}
// ContextStore returns the ContextStore
func (cli *DockerCli) ContextStore() store.Store {
return cli.contextStore
@ -475,7 +461,7 @@ func (cli *DockerCli) DockerEndpoint() docker.Endpoint {
if err := cli.initialize(); err != nil {
// Note that we're not terminating here, as this function may be used
// in cases where we're able to continue.
_, _ = fmt.Fprintf(cli.Err(), "%v\n", cli.initErr)
_, _ = fmt.Fprintln(cli.Err(), cli.initErr)
}
return cli.dockerEndpoint
}
@ -523,7 +509,7 @@ func (cli *DockerCli) Apply(ops ...CLIOption) error {
type ServerInfo struct {
HasExperimental bool
OSType string
BuildkitVersion types.BuilderVersion
BuildkitVersion build.BuilderVersion
// SwarmStatus provides information about the current swarm status of the
// engine, obtained from the "Swarm" header in the API response.
@ -553,18 +539,15 @@ func NewDockerCli(ops ...CLIOption) (*DockerCli, error) {
return cli, nil
}
func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (string, error) {
var host string
func getServerHost(hosts []string, defaultToTLS bool) (string, error) {
switch len(hosts) {
case 0:
host = os.Getenv(client.EnvOverrideHost)
return dopts.ParseHost(defaultToTLS, os.Getenv(client.EnvOverrideHost))
case 1:
host = hosts[0]
return dopts.ParseHost(defaultToTLS, hosts[0])
default:
return "", errors.New("Specify only one -H")
}
return dopts.ParseHost(tlsOptions != nil, host)
}
// UserAgent returns the user agent string used for making API requests

View File

@ -2,13 +2,17 @@ package command
import (
"context"
"encoding/csv"
"io"
"net/http"
"os"
"strconv"
"strings"
"github.com/docker/cli/cli/streams"
"github.com/docker/docker/client"
"github.com/moby/moby/client"
"github.com/moby/term"
"github.com/pkg/errors"
)
// CLIOption is a functional argument to apply options to a [DockerCli]. These
@ -96,7 +100,8 @@ func WithContentTrust(enabled bool) CLIOption {
// WithDefaultContextStoreConfig configures the cli to use the default context store configuration.
func WithDefaultContextStoreConfig() CLIOption {
return func(cli *DockerCli) error {
cli.contextStoreConfig = DefaultContextStoreConfig()
cfg := DefaultContextStoreConfig()
cli.contextStoreConfig = &cfg
return nil
}
}
@ -108,3 +113,128 @@ func WithAPIClient(c client.APIClient) CLIOption {
return nil
}
}
// WithInitializeClient is passed to [DockerCli.Initialize] to initialize
// an API Client for use by the CLI.
func WithInitializeClient(makeClient func(*DockerCli) (client.APIClient, error)) CLIOption {
return func(cli *DockerCli) error {
c, err := makeClient(cli)
if err != nil {
return err
}
return WithAPIClient(c)(cli)
}
}
// envOverrideHTTPHeaders is the name of the environment-variable that can be
// used to set custom HTTP headers to be sent by the client. This environment
// variable is the equivalent to the HttpHeaders field in the configuration
// file.
//
// WARNING: If both config and environment-variable are set, the environment
// variable currently overrides all headers set in the configuration file.
// This behavior may change in a future update, as we are considering the
// environment variable to be appending to existing headers (and to only
// override headers with the same name).
//
// While this env-var allows for custom headers to be set, it does not allow
// for built-in headers (such as "User-Agent", if set) to be overridden.
// Also see [client.WithHTTPHeaders] and [client.WithUserAgent].
//
// This environment variable can be used in situations where headers must be
// set for a specific invocation of the CLI, but should not be set by default,
// and therefore cannot be set in the config-file.
//
// envOverrideHTTPHeaders accepts a comma-separated (CSV) list of key=value pairs,
// where key must be a non-empty, valid MIME header format. Whitespaces surrounding
// the key are trimmed, and the key is normalised. Whitespaces in values are
// preserved, but "key=value" pairs with an empty value (e.g. "key=") are ignored.
// Tuples without a "=" produce an error.
//
// It follows CSV rules for escaping, allowing "key=value" pairs to be quoted
// if they must contain commas, which allows for multiple values for a single
// header to be set. If a key is repeated in the list, later values override
// prior values.
//
// For example, the following value:
//
// one=one-value,"two=two,value","three= a value with whitespace ",four=,five=five=one,five=five-two
//
// Produces four headers (four is omitted as it has an empty value set):
//
// - one (value is "one-value")
// - two (value is "two,value")
// - three (value is " a value with whitespace ")
// - five (value is "five-two", the later value has overridden the prior value)
const envOverrideHTTPHeaders = "DOCKER_CUSTOM_HEADERS"
// withCustomHeadersFromEnv overriding custom HTTP headers to be sent by the
// client through the [envOverrideHTTPHeaders] environment-variable. This
// environment variable is the equivalent to the HttpHeaders field in the
// configuration file.
//
// WARNING: If both config and environment-variable are set, the environment-
// variable currently overrides all headers set in the configuration file.
// This behavior may change in a future update, as we are considering the
// environment-variable to be appending to existing headers (and to only
// override headers with the same name).
//
// TODO(thaJeztah): this is a client Option, and should be moved to the client. It is non-exported for that reason.
func withCustomHeadersFromEnv() client.Opt {
return func(apiClient *client.Client) error {
value := os.Getenv(envOverrideHTTPHeaders)
if value == "" {
return nil
}
csvReader := csv.NewReader(strings.NewReader(value))
fields, err := csvReader.Read()
if err != nil {
return invalidParameter(errors.Errorf(
"failed to parse custom headers from %s environment variable: value must be formatted as comma-separated key=value pairs",
envOverrideHTTPHeaders,
))
}
if len(fields) == 0 {
return nil
}
env := map[string]string{}
for _, kv := range fields {
k, v, hasValue := strings.Cut(kv, "=")
// Only strip whitespace in keys; preserve whitespace in values.
k = strings.TrimSpace(k)
if k == "" {
return invalidParameter(errors.Errorf(
`failed to set custom headers from %s environment variable: value contains a key=value pair with an empty key: '%s'`,
envOverrideHTTPHeaders, kv,
))
}
// We don't currently allow empty key=value pairs, and produce an error.
// This is something we could allow in future (e.g. to read value
// from an environment variable with the same name). In the meantime,
// produce an error to prevent users from depending on this.
if !hasValue {
return invalidParameter(errors.Errorf(
`failed to set custom headers from %s environment variable: missing "=" in key=value pair: '%s'`,
envOverrideHTTPHeaders, kv,
))
}
env[http.CanonicalHeaderKey(k)] = v
}
if len(env) == 0 {
// We should probably not hit this case, as we don't skip values
// (only return errors), but we don't want to discard existing
// headers with an empty set.
return nil
}
// TODO(thaJeztah): add a client.WithExtraHTTPHeaders() function to allow these headers to be _added_ to existing ones, instead of _replacing_
// see https://github.com/docker/cli/pull/5098#issuecomment-2147403871 (when updating, also update the WARNING in the function and env-var GoDoc)
return client.WithHTTPHeaders(env)(apiClient)
}
}

View File

@ -3,6 +3,7 @@ package command
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
@ -18,13 +19,9 @@ import (
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/flags"
"github.com/docker/cli/cli/streams"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/moby/moby/api/types"
"github.com/moby/moby/client"
"gotest.tools/v3/assert"
"gotest.tools/v3/fs"
)
func TestNewAPIClientFromFlags(t *testing.T) {
@ -36,7 +33,7 @@ func TestNewAPIClientFromFlags(t *testing.T) {
apiClient, err := NewAPIClientFromFlags(opts, &configfile.ConfigFile{})
assert.NilError(t, err)
assert.Equal(t, apiClient.DaemonHost(), host)
assert.Equal(t, apiClient.ClientVersion(), api.DefaultVersion)
assert.Equal(t, apiClient.ClientVersion(), client.DefaultAPIVersion)
}
func TestNewAPIClientFromFlagsForDefaultSchema(t *testing.T) {
@ -49,7 +46,7 @@ func TestNewAPIClientFromFlagsForDefaultSchema(t *testing.T) {
apiClient, err := NewAPIClientFromFlags(opts, &configfile.ConfigFile{})
assert.NilError(t, err)
assert.Equal(t, apiClient.DaemonHost(), slug+host)
assert.Equal(t, apiClient.ClientVersion(), api.DefaultVersion)
assert.Equal(t, apiClient.ClientVersion(), client.DefaultAPIVersion)
}
func TestNewAPIClientFromFlagsWithCustomHeaders(t *testing.T) {
@ -73,7 +70,7 @@ func TestNewAPIClientFromFlagsWithCustomHeaders(t *testing.T) {
apiClient, err := NewAPIClientFromFlags(opts, configFile)
assert.NilError(t, err)
assert.Equal(t, apiClient.DaemonHost(), host)
assert.Equal(t, apiClient.ClientVersion(), api.DefaultVersion)
assert.Equal(t, apiClient.ClientVersion(), client.DefaultAPIVersion)
// verify User-Agent is not appended to the configfile. see https://github.com/docker/cli/pull/2756
assert.DeepEqual(t, configFile.HTTPHeaders, map[string]string{"My-Header": "Custom-Value"})
@ -87,8 +84,44 @@ func TestNewAPIClientFromFlagsWithCustomHeaders(t *testing.T) {
assert.DeepEqual(t, received, expectedHeaders)
}
func TestNewAPIClientFromFlagsWithCustomHeadersFromEnv(t *testing.T) {
var received http.Header
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received = r.Header.Clone()
_, _ = w.Write([]byte("OK"))
}))
defer ts.Close()
host := strings.Replace(ts.URL, "http://", "tcp://", 1)
opts := &flags.ClientOptions{Hosts: []string{host}}
configFile := &configfile.ConfigFile{
HTTPHeaders: map[string]string{
"My-Header": "Custom-Value from config-file",
},
}
// envOverrideHTTPHeaders should override the HTTPHeaders from the config-file,
// so "My-Header" should not be present.
t.Setenv(envOverrideHTTPHeaders, `one=one-value,"two=two,value",three=,four=four-value,four=four-value-override`)
apiClient, err := NewAPIClientFromFlags(opts, configFile)
assert.NilError(t, err)
assert.Equal(t, apiClient.DaemonHost(), host)
assert.Equal(t, apiClient.ClientVersion(), client.DefaultAPIVersion)
expectedHeaders := http.Header{
"One": []string{"one-value"},
"Two": []string{"two,value"},
"Three": []string{""},
"Four": []string{"four-value-override"},
"User-Agent": []string{UserAgent()},
}
_, err = apiClient.Ping(context.Background())
assert.NilError(t, err)
assert.DeepEqual(t, received, expectedHeaders)
}
func TestNewAPIClientFromFlagsWithAPIVersionFromEnv(t *testing.T) {
customVersion := "v3.3.3"
const customVersion = "v3.3.3"
const expectedVersion = "3.3.3"
t.Setenv("DOCKER_API_VERSION", customVersion)
t.Setenv("DOCKER_HOST", ":2375")
@ -96,7 +129,7 @@ func TestNewAPIClientFromFlagsWithAPIVersionFromEnv(t *testing.T) {
configFile := &configfile.ConfigFile{}
apiclient, err := NewAPIClientFromFlags(opts, configFile)
assert.NilError(t, err)
assert.Equal(t, apiclient.ClientVersion(), customVersion)
assert.Equal(t, apiclient.ClientVersion(), expectedVersion)
}
type fakeClient struct {
@ -152,19 +185,18 @@ func TestInitializeFromClient(t *testing.T) {
},
}
for _, testcase := range testcases {
testcase := testcase
t.Run(testcase.doc, func(t *testing.T) {
for _, tc := range testcases {
t.Run(tc.doc, func(t *testing.T) {
apiclient := &fakeClient{
pingFunc: testcase.pingFunc,
pingFunc: tc.pingFunc,
version: defaultVersion,
}
cli := &DockerCli{client: apiclient}
err := cli.Initialize(flags.NewClientOptions())
assert.NilError(t, err)
assert.DeepEqual(t, cli.ServerInfo(), testcase.expectedServer)
assert.Equal(t, apiclient.negotiated, testcase.negotiated)
assert.DeepEqual(t, cli.ServerInfo(), tc.expectedServer)
assert.Equal(t, apiclient.negotiated, tc.negotiated)
})
}
}
@ -172,8 +204,8 @@ func TestInitializeFromClient(t *testing.T) {
// Makes sure we don't hang forever on the initial connection.
// https://github.com/docker/cli/issues/3652
func TestInitializeFromClientHangs(t *testing.T) {
dir := t.TempDir()
socket := filepath.Join(dir, "my.sock")
tmpDir := t.TempDir()
socket := filepath.Join(tmpDir, "my.sock")
l, err := net.Listen("unix", socket)
assert.NilError(t, err)
@ -221,80 +253,40 @@ func TestInitializeFromClientHangs(t *testing.T) {
}
}
// The CLI no longer disables/hides experimental CLI features, however, we need
// to verify that existing configuration files do not break
func TestExperimentalCLI(t *testing.T) {
defaultVersion := "v1.55"
testcases := []struct {
doc string
configfile string
}{
{
doc: "default",
configfile: `{}`,
},
{
doc: "experimental",
configfile: `{
"experimental": "enabled"
}`,
},
}
for _, testcase := range testcases {
testcase := testcase
t.Run(testcase.doc, func(t *testing.T) {
dir := fs.NewDir(t, testcase.doc, fs.WithFile("config.json", testcase.configfile))
defer dir.Remove()
apiclient := &fakeClient{
version: defaultVersion,
pingFunc: func() (types.Ping, error) {
return types.Ping{Experimental: true, OSType: "linux", APIVersion: defaultVersion}, nil
},
}
cli := &DockerCli{client: apiclient, err: streams.NewOut(os.Stderr)}
config.SetDir(dir.Path())
err := cli.Initialize(flags.NewClientOptions())
assert.NilError(t, err)
})
}
}
func TestNewDockerCliAndOperators(t *testing.T) {
// Test default operations and also overriding default ones
cli, err := NewDockerCli(
WithContentTrust(true),
)
cli, err := NewDockerCli(WithInputStream(io.NopCloser(strings.NewReader("some input"))))
assert.NilError(t, err)
// Check streams are initialized
assert.Check(t, cli.In() != nil)
assert.Check(t, cli.Out() != nil)
assert.Check(t, cli.Err() != nil)
assert.Equal(t, cli.ContentTrustEnabled(), true)
inputStream, err := io.ReadAll(cli.In())
assert.NilError(t, err)
assert.Equal(t, string(inputStream), "some input")
// Apply can modify a dockerCli after construction
inbuf := bytes.NewBuffer([]byte("input"))
outbuf := bytes.NewBuffer(nil)
errbuf := bytes.NewBuffer(nil)
err = cli.Apply(
WithInputStream(io.NopCloser(inbuf)),
WithInputStream(io.NopCloser(strings.NewReader("input"))),
WithOutputStream(outbuf),
WithErrorStream(errbuf),
)
assert.NilError(t, err)
// Check input stream
inputStream, err := io.ReadAll(cli.In())
inputStream, err = io.ReadAll(cli.In())
assert.NilError(t, err)
assert.Equal(t, string(inputStream), "input")
// Check output stream
fmt.Fprintf(cli.Out(), "output")
_, err = fmt.Fprint(cli.Out(), "output")
assert.NilError(t, err)
outputStream, err := io.ReadAll(outbuf)
assert.NilError(t, err)
assert.Equal(t, string(outputStream), "output")
// Check error stream
fmt.Fprintf(cli.Err(), "error")
_, err = fmt.Fprint(cli.Err(), "error")
assert.NilError(t, err)
errStream, err := io.ReadAll(errbuf)
assert.NilError(t, err)
assert.Equal(t, string(errStream), "error")
@ -311,6 +303,8 @@ func TestInitializeShouldAlwaysCreateTheContextStore(t *testing.T) {
func TestHooksEnabled(t *testing.T) {
t.Run("disabled by default", func(t *testing.T) {
// Make sure we don't depend on any existing ~/.docker/config.json
config.SetDir(t.TempDir())
cli, err := NewDockerCli()
assert.NilError(t, err)
@ -322,12 +316,11 @@ func TestHooksEnabled(t *testing.T) {
"features": {
"hooks": "true"
}}`
dir := fs.NewDir(t, "", fs.WithFile("config.json", configFile))
defer dir.Remove()
config.SetDir(t.TempDir())
err := os.WriteFile(filepath.Join(config.Dir(), "config.json"), []byte(configFile), 0o600)
assert.NilError(t, err)
cli, err := NewDockerCli()
assert.NilError(t, err)
config.SetDir(dir.Path())
assert.Check(t, cli.HooksEnabled())
})
@ -337,12 +330,11 @@ func TestHooksEnabled(t *testing.T) {
"hooks": "true"
}}`
t.Setenv("DOCKER_CLI_HOOKS", "false")
dir := fs.NewDir(t, "", fs.WithFile("config.json", configFile))
defer dir.Remove()
config.SetDir(t.TempDir())
err := os.WriteFile(filepath.Join(config.Dir(), "config.json"), []byte(configFile), 0o600)
assert.NilError(t, err)
cli, err := NewDockerCli()
assert.NilError(t, err)
config.SetDir(dir.Path())
assert.Check(t, !cli.HooksEnabled())
})
@ -352,12 +344,11 @@ func TestHooksEnabled(t *testing.T) {
"hooks": "true"
}}`
t.Setenv("DOCKER_CLI_HINTS", "false")
dir := fs.NewDir(t, "", fs.WithFile("config.json", configFile))
defer dir.Remove()
config.SetDir(t.TempDir())
err := os.WriteFile(filepath.Join(config.Dir(), "config.json"), []byte(configFile), 0o600)
assert.NilError(t, err)
cli, err := NewDockerCli()
assert.NilError(t, err)
config.SetDir(dir.Path())
assert.Check(t, !cli.HooksEnabled())
})
}

View File

@ -43,6 +43,7 @@ func AddCommands(cmd *cobra.Command, dockerCli command.Cli) {
system.NewInfoCommand(dockerCli),
// management commands
builder.NewBakeStubCommand(dockerCli),
builder.NewBuilderCommand(dockerCli),
checkpoint.NewCheckpointCommand(dockerCli),
container.NewContainerCommand(dockerCli),

View File

@ -2,19 +2,21 @@ package completion
import (
"os"
"strings"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
"github.com/spf13/cobra"
)
// ValidArgsFn a function to be used by cobra command as `ValidArgsFunction` to offer command line completion
type ValidArgsFn func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)
// ValidArgsFn a function to be used by cobra command as `ValidArgsFunction` to offer command line completion.
//
// Deprecated: use [cobra.CompletionFunc].
type ValidArgsFn = cobra.CompletionFunc
// APIClientProvider provides a method to get an [client.APIClient], initializing
// it if needed.
@ -27,8 +29,11 @@ type APIClientProvider interface {
}
// ImageNames offers completion for images present within the local store
func ImageNames(dockerCLI APIClientProvider) ValidArgsFn {
func ImageNames(dockerCLI APIClientProvider, limit int) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if limit > 0 && len(args) >= limit {
return nil, cobra.ShellCompDirectiveNoFileComp
}
list, err := dockerCLI.Client().ImageList(cmd.Context(), image.ListOptions{})
if err != nil {
return nil, cobra.ShellCompDirectiveError
@ -44,7 +49,7 @@ func ImageNames(dockerCLI APIClientProvider) ValidArgsFn {
// ContainerNames offers completion for container names and IDs
// By default, only names are returned.
// Set DOCKER_COMPLETION_SHOW_CONTAINER_IDS=yes to also complete IDs.
func ContainerNames(dockerCLI APIClientProvider, all bool, filters ...func(types.Container) bool) ValidArgsFn {
func ContainerNames(dockerCLI APIClientProvider, all bool, filters ...func(container.Summary) bool) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
list, err := dockerCLI.Client().ContainerList(cmd.Context(), container.ListOptions{
All: all,
@ -59,7 +64,7 @@ func ContainerNames(dockerCLI APIClientProvider, all bool, filters ...func(types
for _, ctr := range list {
skip := false
for _, fn := range filters {
if !fn(ctr) {
if fn != nil && !fn(ctr) {
skip = true
break
}
@ -77,7 +82,7 @@ func ContainerNames(dockerCLI APIClientProvider, all bool, filters ...func(types
}
// VolumeNames offers completion for volumes
func VolumeNames(dockerCLI APIClientProvider) ValidArgsFn {
func VolumeNames(dockerCLI APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
list, err := dockerCLI.Client().VolumeList(cmd.Context(), volume.ListOptions{})
if err != nil {
@ -92,7 +97,7 @@ func VolumeNames(dockerCLI APIClientProvider) ValidArgsFn {
}
// NetworkNames offers completion for networks
func NetworkNames(dockerCLI APIClientProvider) ValidArgsFn {
func NetworkNames(dockerCLI APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
list, err := dockerCLI.Client().NetworkList(cmd.Context(), network.ListOptions{})
if err != nil {
@ -106,7 +111,83 @@ func NetworkNames(dockerCLI APIClientProvider) ValidArgsFn {
}
}
// EnvVarNames offers completion for environment-variable names. This
// completion can be used for "--env" and "--build-arg" flags, which
// allow obtaining the value of the given environment-variable if present
// in the local environment, so we only should complete the names of the
// environment variables, and not their value. This also prevents the
// completion script from printing values of environment variables
// containing sensitive values.
//
// For example;
//
// export MY_VAR=hello
// docker run --rm --env MY_VAR alpine printenv MY_VAR
// hello
func EnvVarNames(_ *cobra.Command, _ []string, _ string) (names []string, _ cobra.ShellCompDirective) {
envs := os.Environ()
names = make([]string, 0, len(envs))
for _, env := range envs {
name, _, _ := strings.Cut(env, "=")
names = append(names, name)
}
return names, cobra.ShellCompDirectiveNoFileComp
}
// FromList offers completion for the given list of options.
func FromList(options ...string) cobra.CompletionFunc {
return cobra.FixedCompletions(options, cobra.ShellCompDirectiveNoFileComp)
}
// FileNames is a convenience function to use [cobra.ShellCompDirectiveDefault],
// which indicates to let the shell perform its default behavior after
// completions have been provided.
func FileNames(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveDefault
}
// NoComplete is used for commands where there's no relevant completion
func NoComplete(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
}
var commonPlatforms = []string{
"linux/386",
"linux/amd64",
"linux/arm",
"linux/arm/v5",
"linux/arm/v6",
"linux/arm/v7",
"linux/arm64",
"linux/arm64/v8",
// IBM power and z platforms
"linux/ppc64le",
"linux/s390x",
// Not yet supported
"linux/riscv64",
"windows/amd64",
"wasip1/wasm",
}
// Platforms offers completion for platform-strings. It provides a non-exhaustive
// list of platforms to be used for completion. Platform-strings are based on
// [runtime.GOOS] and [runtime.GOARCH], but with (optional) variants added. A
// list of recognised os/arch combinations from the Go runtime can be obtained
// through "go tool dist list".
//
// Some noteworthy exclusions from this list:
//
// - arm64 images ("windows/arm64", "windows/arm64/v8") do not yet exist for windows.
// - we don't (yet) include `os-variant` for completion (as can be used for Windows images)
// - we don't (yet) include platforms for which we don't build binaries, such as
// BSD platforms (freebsd, netbsd, openbsd), android, macOS (darwin).
// - we currently exclude architectures that may have unofficial builds,
// but don't have wide adoption (and no support), such as loong64, mipsXXX,
// ppc64 (non-le) to prevent confusion.
func Platforms(_ *cobra.Command, _ []string, _ string) (platforms []string, _ cobra.ShellCompDirective) {
return commonPlatforms, cobra.ShellCompDirectiveNoFileComp
}

View File

@ -0,0 +1,346 @@
package completion
import (
"context"
"errors"
"sort"
"testing"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/filters"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/env"
)
type fakeCLI struct {
*fakeClient
}
// Client implements [APIClientProvider].
func (c fakeCLI) Client() client.APIClient {
return c.fakeClient
}
type fakeClient struct {
client.Client
containerListFunc func(options container.ListOptions) ([]container.Summary, error)
imageListFunc func(options image.ListOptions) ([]image.Summary, error)
networkListFunc func(ctx context.Context, options network.ListOptions) ([]network.Summary, error)
volumeListFunc func(filter filters.Args) (volume.ListResponse, error)
}
func (c *fakeClient) ContainerList(_ context.Context, options container.ListOptions) ([]container.Summary, error) {
if c.containerListFunc != nil {
return c.containerListFunc(options)
}
return []container.Summary{}, nil
}
func (c *fakeClient) ImageList(_ context.Context, options image.ListOptions) ([]image.Summary, error) {
if c.imageListFunc != nil {
return c.imageListFunc(options)
}
return []image.Summary{}, nil
}
func (c *fakeClient) NetworkList(ctx context.Context, options network.ListOptions) ([]network.Summary, error) {
if c.networkListFunc != nil {
return c.networkListFunc(ctx, options)
}
return []network.Inspect{}, nil
}
func (c *fakeClient) VolumeList(_ context.Context, options volume.ListOptions) (volume.ListResponse, error) {
if c.volumeListFunc != nil {
return c.volumeListFunc(options.Filters)
}
return volume.ListResponse{}, nil
}
func TestCompleteContainerNames(t *testing.T) {
tests := []struct {
doc string
showAll, showIDs bool
filters []func(container.Summary) bool
containers []container.Summary
expOut []string
expOpts container.ListOptions
expDirective cobra.ShellCompDirective
}{
{
doc: "no results",
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "all containers",
showAll: true,
containers: []container.Summary{
{ID: "id-c", State: container.StateRunning, Names: []string{"/container-c", "/container-c/link-b"}},
{ID: "id-b", State: container.StateCreated, Names: []string{"/container-b"}},
{ID: "id-a", State: container.StateExited, Names: []string{"/container-a"}},
},
expOut: []string{"container-c", "container-c/link-b", "container-b", "container-a"},
expOpts: container.ListOptions{All: true},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "all containers with ids",
showAll: true,
showIDs: true,
containers: []container.Summary{
{ID: "id-c", State: container.StateRunning, Names: []string{"/container-c", "/container-c/link-b"}},
{ID: "id-b", State: container.StateCreated, Names: []string{"/container-b"}},
{ID: "id-a", State: container.StateExited, Names: []string{"/container-a"}},
},
expOut: []string{"id-c", "container-c", "container-c/link-b", "id-b", "container-b", "id-a", "container-a"},
expOpts: container.ListOptions{All: true},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "only running containers",
showAll: false,
containers: []container.Summary{
{ID: "id-c", State: container.StateRunning, Names: []string{"/container-c", "/container-c/link-b"}},
},
expOut: []string{"container-c", "container-c/link-b"},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with filter",
showAll: true,
filters: []func(container.Summary) bool{
func(ctr container.Summary) bool { return ctr.State == container.StateCreated },
},
containers: []container.Summary{
{ID: "id-c", State: container.StateRunning, Names: []string{"/container-c", "/container-c/link-b"}},
{ID: "id-b", State: container.StateCreated, Names: []string{"/container-b"}},
{ID: "id-a", State: container.StateExited, Names: []string{"/container-a"}},
},
expOut: []string{"container-b"},
expOpts: container.ListOptions{All: true},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "multiple filters",
showAll: true,
filters: []func(container.Summary) bool{
func(ctr container.Summary) bool { return ctr.ID == "id-a" },
func(ctr container.Summary) bool { return ctr.State == container.StateCreated },
},
containers: []container.Summary{
{ID: "id-c", State: container.StateRunning, Names: []string{"/container-c", "/container-c/link-b"}},
{ID: "id-b", State: container.StateCreated, Names: []string{"/container-b"}},
{ID: "id-a", State: container.StateCreated, Names: []string{"/container-a"}},
},
expOut: []string{"container-a"},
expOpts: container.ListOptions{All: true},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with error",
expDirective: cobra.ShellCompDirectiveError,
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
if tc.showIDs {
t.Setenv("DOCKER_COMPLETION_SHOW_CONTAINER_IDS", "yes")
}
comp := ContainerNames(fakeCLI{&fakeClient{
containerListFunc: func(opts container.ListOptions) ([]container.Summary, error) {
assert.Check(t, is.DeepEqual(opts, tc.expOpts, cmpopts.IgnoreUnexported(container.ListOptions{}, filters.Args{})))
if tc.expDirective == cobra.ShellCompDirectiveError {
return nil, errors.New("some error occurred")
}
return tc.containers, nil
},
}}, tc.showAll, tc.filters...)
containers, directives := comp(&cobra.Command{}, nil, "")
assert.Check(t, is.Equal(directives&tc.expDirective, tc.expDirective))
assert.Check(t, is.DeepEqual(containers, tc.expOut))
})
}
}
func TestCompleteEnvVarNames(t *testing.T) {
env.PatchAll(t, map[string]string{
"ENV_A": "hello-a",
"ENV_B": "hello-b",
})
values, directives := EnvVarNames(nil, nil, "")
assert.Check(t, is.Equal(directives&cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveNoFileComp), "Should not perform file completion")
sort.Strings(values)
expected := []string{"ENV_A", "ENV_B"}
assert.Check(t, is.DeepEqual(values, expected))
}
func TestCompleteFileNames(t *testing.T) {
values, directives := FileNames(nil, nil, "")
assert.Check(t, is.Equal(directives, cobra.ShellCompDirectiveDefault))
assert.Check(t, is.Len(values, 0))
}
func TestCompleteFromList(t *testing.T) {
expected := []string{"one", "two", "three"}
values, directives := FromList(expected...)(nil, nil, "")
assert.Check(t, is.Equal(directives&cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveNoFileComp), "Should not perform file completion")
assert.Check(t, is.DeepEqual(values, expected))
}
func TestCompleteImageNames(t *testing.T) {
tests := []struct {
doc string
images []image.Summary
expOut []string
expDirective cobra.ShellCompDirective
}{
{
doc: "no results",
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with results",
images: []image.Summary{
{RepoTags: []string{"image-c:latest", "image-c:other"}},
{RepoTags: []string{"image-b:latest", "image-b:other"}},
{RepoTags: []string{"image-a:latest", "image-a:other"}},
},
expOut: []string{"image-c:latest", "image-c:other", "image-b:latest", "image-b:other", "image-a:latest", "image-a:other"},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with error",
expDirective: cobra.ShellCompDirectiveError,
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
comp := ImageNames(fakeCLI{&fakeClient{
imageListFunc: func(options image.ListOptions) ([]image.Summary, error) {
if tc.expDirective == cobra.ShellCompDirectiveError {
return nil, errors.New("some error occurred")
}
return tc.images, nil
},
}}, -1)
volumes, directives := comp(&cobra.Command{}, nil, "")
assert.Check(t, is.Equal(directives&tc.expDirective, tc.expDirective))
assert.Check(t, is.DeepEqual(volumes, tc.expOut))
})
}
}
func TestCompleteNetworkNames(t *testing.T) {
tests := []struct {
doc string
networks []network.Summary
expOut []string
expDirective cobra.ShellCompDirective
}{
{
doc: "no results",
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with results",
networks: []network.Summary{
{ID: "nw-c", Name: "network-c"},
{ID: "nw-b", Name: "network-b"},
{ID: "nw-a", Name: "network-a"},
},
expOut: []string{"network-c", "network-b", "network-a"},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with error",
expDirective: cobra.ShellCompDirectiveError,
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
comp := NetworkNames(fakeCLI{&fakeClient{
networkListFunc: func(ctx context.Context, options network.ListOptions) ([]network.Summary, error) {
if tc.expDirective == cobra.ShellCompDirectiveError {
return nil, errors.New("some error occurred")
}
return tc.networks, nil
},
}})
volumes, directives := comp(&cobra.Command{}, nil, "")
assert.Check(t, is.Equal(directives&tc.expDirective, tc.expDirective))
assert.Check(t, is.DeepEqual(volumes, tc.expOut))
})
}
}
func TestCompleteNoComplete(t *testing.T) {
values, directives := NoComplete(nil, nil, "")
assert.Check(t, is.Equal(directives, cobra.ShellCompDirectiveNoFileComp))
assert.Check(t, is.Len(values, 0))
}
func TestCompletePlatforms(t *testing.T) {
values, directives := Platforms(nil, nil, "")
assert.Check(t, is.Equal(directives&cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveNoFileComp), "Should not perform file completion")
assert.Check(t, is.DeepEqual(values, commonPlatforms))
}
func TestCompleteVolumeNames(t *testing.T) {
tests := []struct {
doc string
volumes []*volume.Volume
expOut []string
expDirective cobra.ShellCompDirective
}{
{
doc: "no results",
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with results",
volumes: []*volume.Volume{
{Name: "volume-c"},
{Name: "volume-b"},
{Name: "volume-a"},
},
expOut: []string{"volume-c", "volume-b", "volume-a"},
expDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
doc: "with error",
expDirective: cobra.ShellCompDirectiveError,
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
comp := VolumeNames(fakeCLI{&fakeClient{
volumeListFunc: func(filter filters.Args) (volume.ListResponse, error) {
if tc.expDirective == cobra.ShellCompDirectiveError {
return volume.ListResponse{}, errors.New("some error occurred")
}
return volume.ListResponse{Volumes: tc.volumes}, nil
},
}})
volumes, directives := comp(&cobra.Command{}, nil, "")
assert.Check(t, is.Equal(directives&tc.expDirective, tc.expDirective))
assert.Check(t, is.DeepEqual(volumes, tc.expOut))
})
}
}

View File

@ -3,24 +3,23 @@ package config
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/swarm"
"github.com/moby/moby/client"
)
type fakeClient struct {
client.Client
configCreateFunc func(context.Context, swarm.ConfigSpec) (types.ConfigCreateResponse, error)
configCreateFunc func(context.Context, swarm.ConfigSpec) (swarm.ConfigCreateResponse, error)
configInspectFunc func(context.Context, string) (swarm.Config, []byte, error)
configListFunc func(context.Context, types.ConfigListOptions) ([]swarm.Config, error)
configListFunc func(context.Context, swarm.ConfigListOptions) ([]swarm.Config, error)
configRemoveFunc func(string) error
}
func (c *fakeClient) ConfigCreate(ctx context.Context, spec swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
func (c *fakeClient) ConfigCreate(ctx context.Context, spec swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) {
if c.configCreateFunc != nil {
return c.configCreateFunc(ctx, spec)
}
return types.ConfigCreateResponse{}, nil
return swarm.ConfigCreateResponse{}, nil
}
func (c *fakeClient) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) {
@ -30,7 +29,7 @@ func (c *fakeClient) ConfigInspectWithRaw(ctx context.Context, id string) (swarm
return swarm.Config{}, nil, nil
}
func (c *fakeClient) ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
func (c *fakeClient) ConfigList(ctx context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
if c.configListFunc != nil {
return c.configListFunc(ctx, options)
}

View File

@ -4,7 +4,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/docker/api/types"
"github.com/moby/moby/api/types/swarm"
"github.com/spf13/cobra"
)
@ -30,9 +30,9 @@ func NewConfigCommand(dockerCli command.Cli) *cobra.Command {
}
// completeNames offers completion for swarm configs
func completeNames(dockerCLI completion.APIClientProvider) completion.ValidArgsFn {
func completeNames(dockerCLI completion.APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
list, err := dockerCLI.Client().ConfigList(cmd.Context(), types.ConfigListOptions{})
list, err := dockerCLI.Client().ConfigList(cmd.Context(), swarm.ConfigListOptions{})
if err != nil {
return nil, cobra.ShellCompDirectiveError
}

View File

@ -9,7 +9,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/swarm"
"github.com/moby/moby/api/types/swarm"
"github.com/moby/sys/sequential"
"github.com/pkg/errors"
"github.com/spf13/cobra"
@ -48,20 +48,10 @@ func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command {
}
// RunConfigCreate creates a config with the given options.
func RunConfigCreate(ctx context.Context, dockerCli command.Cli, options CreateOptions) error {
client := dockerCli.Client()
func RunConfigCreate(ctx context.Context, dockerCLI command.Cli, options CreateOptions) error {
apiClient := dockerCLI.Client()
var in io.Reader = dockerCli.In()
if options.File != "-" {
file, err := sequential.Open(options.File)
if err != nil {
return err
}
in = file
defer file.Close()
}
configData, err := io.ReadAll(in)
configData, err := readConfigData(dockerCLI.In(), options.File)
if err != nil {
return errors.Errorf("Error reading content from %q: %v", options.File, err)
}
@ -69,7 +59,7 @@ func RunConfigCreate(ctx context.Context, dockerCli command.Cli, options CreateO
spec := swarm.ConfigSpec{
Annotations: swarm.Annotations{
Name: options.Name,
Labels: opts.ConvertKVStringsToMap(options.Labels.GetAll()),
Labels: opts.ConvertKVStringsToMap(options.Labels.GetSlice()),
},
Data: configData,
}
@ -78,11 +68,59 @@ func RunConfigCreate(ctx context.Context, dockerCli command.Cli, options CreateO
Name: options.TemplateDriver,
}
}
r, err := client.ConfigCreate(ctx, spec)
r, err := apiClient.ConfigCreate(ctx, spec)
if err != nil {
return err
}
fmt.Fprintln(dockerCli.Out(), r.ID)
_, _ = fmt.Fprintln(dockerCLI.Out(), r.ID)
return nil
}
// maxConfigSize is the maximum byte length of the [swarm.ConfigSpec.Data] field,
// as defined by [MaxConfigSize] in SwarmKit.
//
// [MaxConfigSize]: https://pkg.go.dev/github.com/moby/swarmkit/v2@v2.0.0-20250103191802-8c1959736554/manager/controlapi#MaxConfigSize
const maxConfigSize = 1000 * 1024 // 1000KB
// readConfigData reads the config from either stdin or the given fileName.
//
// It reads up to twice the maximum size of the config ([maxConfigSize]),
// just in case swarm's limit changes; this is only a safeguard to prevent
// reading arbitrary files into memory.
func readConfigData(in io.Reader, fileName string) ([]byte, error) {
switch fileName {
case "-":
data, err := io.ReadAll(io.LimitReader(in, 2*maxConfigSize))
if err != nil {
return nil, fmt.Errorf("error reading from STDIN: %w", err)
}
if len(data) == 0 {
return nil, errors.New("error reading from STDIN: data is empty")
}
return data, nil
case "":
return nil, errors.New("config file is required")
default:
// Open file with [FILE_FLAG_SEQUENTIAL_SCAN] on Windows, which
// prevents Windows from aggressively caching it. We expect this
// file to be only read once. Given that this is expected to be
// a small file, this may not be a significant optimization, so
// we could choose to omit this, and use a regular [os.Open].
//
// [FILE_FLAG_SEQUENTIAL_SCAN]: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#FILE_FLAG_SEQUENTIAL_SCAN
f, err := sequential.Open(fileName)
if err != nil {
return nil, fmt.Errorf("error reading from %s: %w", fileName, err)
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, 2*maxConfigSize))
if err != nil {
return nil, fmt.Errorf("error reading from %s: %w", fileName, err)
}
if len(data) == 0 {
return nil, fmt.Errorf("error reading from %s: data is empty", fileName)
}
return data, nil
}
}

View File

@ -2,6 +2,8 @@ package config
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
@ -10,9 +12,7 @@ import (
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/swarm"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/golden"
@ -23,49 +23,52 @@ const configDataFile = "config-create-with-name.golden"
func TestConfigCreateErrors(t *testing.T) {
testCases := []struct {
args []string
configCreateFunc func(context.Context, swarm.ConfigSpec) (types.ConfigCreateResponse, error)
configCreateFunc func(context.Context, swarm.ConfigSpec) (swarm.ConfigCreateResponse, error)
expectedError string
}{
{
args: []string{"too_few"},
expectedError: "requires exactly 2 arguments",
expectedError: "requires 2 arguments",
},
{
args: []string{"too", "many", "arguments"},
expectedError: "requires exactly 2 arguments",
expectedError: "requires 2 arguments",
},
{
args: []string{"name", filepath.Join("testdata", configDataFile)},
configCreateFunc: func(_ context.Context, configSpec swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
return types.ConfigCreateResponse{}, errors.Errorf("error creating config")
configCreateFunc: func(_ context.Context, configSpec swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) {
return swarm.ConfigCreateResponse{}, errors.New("error creating config")
},
expectedError: "error creating config",
},
}
for _, tc := range testCases {
cmd := newConfigCreateCommand(
test.NewFakeCli(&fakeClient{
configCreateFunc: tc.configCreateFunc,
}),
)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
t.Run(tc.expectedError, func(t *testing.T) {
cmd := newConfigCreateCommand(
test.NewFakeCli(&fakeClient{
configCreateFunc: tc.configCreateFunc,
}),
)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
})
}
}
func TestConfigCreateWithName(t *testing.T) {
name := "foo"
const name = "config-with-name"
var actual []byte
cli := test.NewFakeCli(&fakeClient{
configCreateFunc: func(_ context.Context, spec swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
configCreateFunc: func(_ context.Context, spec swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) {
if spec.Name != name {
return types.ConfigCreateResponse{}, errors.Errorf("expected name %q, got %q", name, spec.Name)
return swarm.ConfigCreateResponse{}, fmt.Errorf("expected name %q, got %q", name, spec.Name)
}
actual = spec.Data
return types.ConfigCreateResponse{
return swarm.ConfigCreateResponse{
ID: "ID-" + spec.Name,
}, nil
},
@ -83,7 +86,7 @@ func TestConfigCreateWithLabels(t *testing.T) {
"lbl1": "Label-foo",
"lbl2": "Label-bar",
}
name := "foo"
const name = "config-with-labels"
data, err := os.ReadFile(filepath.Join("testdata", configDataFile))
assert.NilError(t, err)
@ -97,12 +100,12 @@ func TestConfigCreateWithLabels(t *testing.T) {
}
cli := test.NewFakeCli(&fakeClient{
configCreateFunc: func(_ context.Context, spec swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
configCreateFunc: func(_ context.Context, spec swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) {
if !reflect.DeepEqual(spec, expected) {
return types.ConfigCreateResponse{}, errors.Errorf("expected %+v, got %+v", expected, spec)
return swarm.ConfigCreateResponse{}, fmt.Errorf("expected %+v, got %+v", expected, spec)
}
return types.ConfigCreateResponse{
return swarm.ConfigCreateResponse{
ID: "ID-" + spec.Name,
}, nil
},
@ -120,19 +123,19 @@ func TestConfigCreateWithTemplatingDriver(t *testing.T) {
expectedDriver := &swarm.Driver{
Name: "template-driver",
}
name := "foo"
const name = "config-with-template-driver"
cli := test.NewFakeCli(&fakeClient{
configCreateFunc: func(_ context.Context, spec swarm.ConfigSpec) (types.ConfigCreateResponse, error) {
configCreateFunc: func(_ context.Context, spec swarm.ConfigSpec) (swarm.ConfigCreateResponse, error) {
if spec.Name != name {
return types.ConfigCreateResponse{}, errors.Errorf("expected name %q, got %q", name, spec.Name)
return swarm.ConfigCreateResponse{}, fmt.Errorf("expected name %q, got %q", name, spec.Name)
}
if spec.Templating.Name != expectedDriver.Name {
return types.ConfigCreateResponse{}, errors.Errorf("expected driver %v, got %v", expectedDriver, spec.Labels)
return swarm.ConfigCreateResponse{}, fmt.Errorf("expected driver %v, got %v", expectedDriver, spec.Labels)
}
return types.ConfigCreateResponse{
return swarm.ConfigCreateResponse{
ID: "ID-" + spec.Name,
}, nil
},

View File

@ -5,11 +5,10 @@ import (
"strings"
"time"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/cli/cli/command/inspect"
"github.com/docker/docker/api/types/swarm"
units "github.com/docker/go-units"
"github.com/docker/go-units"
"github.com/moby/moby/api/types/swarm"
)
const (
@ -157,11 +156,11 @@ func (ctx *configInspectContext) Labels() map[string]string {
}
func (ctx *configInspectContext) CreatedAt() string {
return command.PrettyPrint(ctx.Config.CreatedAt)
return formatter.PrettyPrint(ctx.Config.CreatedAt)
}
func (ctx *configInspectContext) UpdatedAt() string {
return command.PrettyPrint(ctx.Config.UpdatedAt)
return formatter.PrettyPrint(ctx.Config.UpdatedAt)
}
func (ctx *configInspectContext) Data() string {

View File

@ -6,7 +6,7 @@ import (
"time"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types/swarm"
"github.com/moby/moby/api/types/swarm"
"gotest.tools/v3/assert"
)
@ -61,7 +61,6 @@ id_rsa
},
}
for _, tc := range cases {
tc := tc
t.Run(string(tc.context.Format), func(t *testing.T) {
var out bytes.Buffer
tc.context.Output = &out

View File

@ -1,5 +1,5 @@
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
//go:build go1.23
package config
@ -43,15 +43,15 @@ func newConfigInspectCommand(dockerCli command.Cli) *cobra.Command {
}
// RunConfigInspect inspects the given Swarm config.
func RunConfigInspect(ctx context.Context, dockerCli command.Cli, opts InspectOptions) error {
client := dockerCli.Client()
func RunConfigInspect(ctx context.Context, dockerCLI command.Cli, opts InspectOptions) error {
apiClient := dockerCLI.Client()
if opts.Pretty {
opts.Format = "pretty"
}
getRef := func(id string) (any, []byte, error) {
return client.ConfigInspectWithRaw(ctx, id)
return apiClient.ConfigInspectWithRaw(ctx, id)
}
f := opts.Format
@ -62,7 +62,7 @@ func RunConfigInspect(ctx context.Context, dockerCli command.Cli, opts InspectOp
}
configCtx := formatter.Context{
Output: dockerCli.Out(),
Output: dockerCLI.Out(),
Format: NewFormat(f, false),
}

View File

@ -2,6 +2,7 @@ package config
import (
"context"
"errors"
"fmt"
"io"
"testing"
@ -9,8 +10,7 @@ import (
"github.com/docker/cli/internal/test"
"github.com/docker/cli/internal/test/builders"
"github.com/docker/docker/api/types/swarm"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/swarm"
"gotest.tools/v3/assert"
"gotest.tools/v3/golden"
)
@ -28,7 +28,7 @@ func TestConfigInspectErrors(t *testing.T) {
{
args: []string{"foo"},
configInspectFunc: func(_ context.Context, configID string) (swarm.Config, []byte, error) {
return swarm.Config{}, nil, errors.Errorf("error while inspecting the config")
return swarm.Config{}, nil, errors.New("error while inspecting the config")
},
expectedError: "error while inspecting the config",
},
@ -45,7 +45,7 @@ func TestConfigInspectErrors(t *testing.T) {
if configID == "foo" {
return *builders.Config(builders.ConfigName("foo")), nil, nil
}
return swarm.Config{}, nil, errors.Errorf("error while inspecting the config")
return swarm.Config{}, nil, errors.New("error while inspecting the config")
},
expectedError: "error while inspecting the config",
},
@ -61,6 +61,7 @@ func TestConfigInspectErrors(t *testing.T) {
assert.Check(t, cmd.Flags().Set(key, value))
}
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}
}
@ -76,7 +77,7 @@ func TestConfigInspectWithoutFormat(t *testing.T) {
args: []string{"foo"},
configInspectFunc: func(_ context.Context, name string) (swarm.Config, []byte, error) {
if name != "foo" {
return swarm.Config{}, nil, errors.Errorf("Invalid name, expected %s, got %s", "foo", name)
return swarm.Config{}, nil, fmt.Errorf("invalid name, expected %s, got %s", "foo", name)
}
return *builders.Config(builders.ConfigID("ID-foo"), builders.ConfigName("foo")), nil, nil
},

View File

@ -10,8 +10,8 @@ import (
"github.com/docker/cli/cli/command/formatter"
flagsHelper "github.com/docker/cli/cli/flags"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types"
"github.com/fvbommel/sortorder"
"github.com/moby/moby/api/types/swarm"
"github.com/spf13/cobra"
)
@ -45,18 +45,18 @@ func newConfigListCommand(dockerCli command.Cli) *cobra.Command {
}
// RunConfigList lists Swarm configs.
func RunConfigList(ctx context.Context, dockerCli command.Cli, options ListOptions) error {
client := dockerCli.Client()
func RunConfigList(ctx context.Context, dockerCLI command.Cli, options ListOptions) error {
apiClient := dockerCLI.Client()
configs, err := client.ConfigList(ctx, types.ConfigListOptions{Filters: options.Filter.Value()})
configs, err := apiClient.ConfigList(ctx, swarm.ConfigListOptions{Filters: options.Filter.Value()})
if err != nil {
return err
}
format := options.Format
if len(format) == 0 {
if len(dockerCli.ConfigFile().ConfigFormat) > 0 && !options.Quiet {
format = dockerCli.ConfigFile().ConfigFormat
if len(dockerCLI.ConfigFile().ConfigFormat) > 0 && !options.Quiet {
format = dockerCLI.ConfigFile().ConfigFormat
} else {
format = formatter.TableFormatKey
}
@ -67,7 +67,7 @@ func RunConfigList(ctx context.Context, dockerCli command.Cli, options ListOptio
})
configCtx := formatter.Context{
Output: dockerCli.Out(),
Output: dockerCLI.Out(),
Format: NewFormat(format, options.Quiet),
}
return FormatWrite(configCtx, configs)

View File

@ -2,6 +2,7 @@ package config
import (
"context"
"errors"
"io"
"testing"
"time"
@ -9,9 +10,7 @@ import (
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/internal/test/builders"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/swarm"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/golden"
@ -20,7 +19,7 @@ import (
func TestConfigListErrors(t *testing.T) {
testCases := []struct {
args []string
configListFunc func(context.Context, types.ConfigListOptions) ([]swarm.Config, error)
configListFunc func(context.Context, swarm.ConfigListOptions) ([]swarm.Config, error)
expectedError string
}{
{
@ -28,8 +27,8 @@ func TestConfigListErrors(t *testing.T) {
expectedError: "accepts no argument",
},
{
configListFunc: func(_ context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
return []swarm.Config{}, errors.Errorf("error listing configs")
configListFunc: func(_ context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
return []swarm.Config{}, errors.New("error listing configs")
},
expectedError: "error listing configs",
},
@ -42,13 +41,14 @@ func TestConfigListErrors(t *testing.T) {
)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}
}
func TestConfigList(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
configListFunc: func(_ context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
configListFunc: func(_ context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
return []swarm.Config{
*builders.Config(builders.ConfigID("ID-1-foo"),
builders.ConfigName("1-foo"),
@ -78,7 +78,7 @@ func TestConfigList(t *testing.T) {
func TestConfigListWithQuietOption(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
configListFunc: func(_ context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
configListFunc: func(_ context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
return []swarm.Config{
*builders.Config(builders.ConfigID("ID-foo"), builders.ConfigName("foo")),
*builders.Config(builders.ConfigID("ID-bar"), builders.ConfigName("bar"), builders.ConfigLabels(map[string]string{
@ -95,7 +95,7 @@ func TestConfigListWithQuietOption(t *testing.T) {
func TestConfigListWithConfigFormat(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
configListFunc: func(_ context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
configListFunc: func(_ context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
return []swarm.Config{
*builders.Config(builders.ConfigID("ID-foo"), builders.ConfigName("foo")),
*builders.Config(builders.ConfigID("ID-bar"), builders.ConfigName("bar"), builders.ConfigLabels(map[string]string{
@ -114,7 +114,7 @@ func TestConfigListWithConfigFormat(t *testing.T) {
func TestConfigListWithFormat(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
configListFunc: func(_ context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
configListFunc: func(_ context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
return []swarm.Config{
*builders.Config(builders.ConfigID("ID-foo"), builders.ConfigName("foo")),
*builders.Config(builders.ConfigID("ID-bar"), builders.ConfigName("bar"), builders.ConfigLabels(map[string]string{
@ -131,7 +131,7 @@ func TestConfigListWithFormat(t *testing.T) {
func TestConfigListWithFilter(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
configListFunc: func(_ context.Context, options types.ConfigListOptions) ([]swarm.Config, error) {
configListFunc: func(_ context.Context, options swarm.ConfigListOptions) ([]swarm.Config, error) {
assert.Check(t, is.Equal("foo", options.Filters.Get("name")[0]))
assert.Check(t, is.Equal("lbl1=Label-bar", options.Filters.Get("label")[0]))
return []swarm.Config{

View File

@ -2,12 +2,11 @@ package config
import (
"context"
"errors"
"fmt"
"strings"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
@ -35,23 +34,17 @@ func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command {
}
// RunConfigRemove removes the given Swarm configs.
func RunConfigRemove(ctx context.Context, dockerCli command.Cli, opts RemoveOptions) error {
client := dockerCli.Client()
var errs []string
func RunConfigRemove(ctx context.Context, dockerCLI command.Cli, opts RemoveOptions) error {
apiClient := dockerCLI.Client()
var errs []error
for _, name := range opts.Names {
if err := client.ConfigRemove(ctx, name); err != nil {
errs = append(errs, err.Error())
if err := apiClient.ConfigRemove(ctx, name); err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintln(dockerCli.Out(), name)
_, _ = fmt.Fprintln(dockerCLI.Out(), name)
}
if len(errs) > 0 {
return errors.Errorf("%s", strings.Join(errs, "\n"))
}
return nil
return errors.Join(errs...)
}

View File

@ -1,12 +1,12 @@
package config
import (
"errors"
"io"
"strings"
"testing"
"github.com/docker/cli/internal/test"
"github.com/pkg/errors"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
@ -19,12 +19,12 @@ func TestConfigRemoveErrors(t *testing.T) {
}{
{
args: []string{},
expectedError: "requires at least 1 argument.",
expectedError: "requires at least 1 argument",
},
{
args: []string{"foo"},
configRemoveFunc: func(name string) error {
return errors.Errorf("error removing config")
return errors.New("error removing config")
},
expectedError: "error removing config",
},
@ -37,6 +37,7 @@ func TestConfigRemoveErrors(t *testing.T) {
)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
}
}
@ -65,7 +66,7 @@ func TestConfigRemoveContinueAfterError(t *testing.T) {
configRemoveFunc: func(name string) error {
removedConfigs = append(removedConfigs, name)
if name == "foo" {
return errors.Errorf("error removing config: %s", name)
return errors.New("error removing config: " + name)
}
return nil
},
@ -74,6 +75,7 @@ func TestConfigRemoveContinueAfterError(t *testing.T) {
cmd := newConfigRemoveCommand(cli)
cmd.SetArgs(names)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Error(t, cmd.Execute(), "error removing config: foo")
assert.Check(t, is.DeepEqual(names, removedConfigs))
}

View File

@ -7,9 +7,8 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"github.com/moby/sys/signal"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
@ -23,7 +22,7 @@ type AttachOptions struct {
DetachKeys string
}
func inspectContainerAndCheckState(ctx context.Context, apiClient client.APIClient, args string) (*types.ContainerJSON, error) {
func inspectContainerAndCheckState(ctx context.Context, apiClient client.APIClient, args string) (*container.InspectResponse, error) {
c, err := apiClient.ContainerInspect(ctx, args)
if err != nil {
return nil, err
@ -56,8 +55,8 @@ func NewAttachCommand(dockerCLI command.Cli) *cobra.Command {
Annotations: map[string]string{
"aliases": "docker container attach, docker attach",
},
ValidArgsFunction: completion.ContainerNames(dockerCLI, false, func(ctr types.Container) bool {
return ctr.State != "paused"
ValidArgsFunction: completion.ContainerNames(dockerCLI, false, func(ctr container.Summary) bool {
return ctr.State != container.StatePaused
}),
}
@ -73,7 +72,8 @@ func RunAttach(ctx context.Context, dockerCLI command.Cli, containerID string, o
apiClient := dockerCLI.Client()
// request channel to wait for client
resultC, errC := apiClient.ContainerWait(ctx, containerID, "")
waitCtx := context.WithoutCancel(ctx)
resultC, errC := apiClient.ContainerWait(waitCtx, containerID, "")
c, err := inspectContainerAndCheckState(ctx, apiClient, containerID)
if err != nil {
@ -146,7 +146,8 @@ func RunAttach(ctx context.Context, dockerCLI command.Cli, containerID string, o
detachKeys: options.DetachKeys,
}
if err := streamer.stream(ctx); err != nil {
// if the context was canceled, this was likely intentional and we shouldn't return an error
if err := streamer.stream(ctx); err != nil && !errors.Is(err, context.Canceled) {
return err
}

View File

@ -1,14 +1,13 @@
package container
import (
"errors"
"io"
"testing"
"github.com/docker/cli/cli"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
)
@ -17,71 +16,75 @@ func TestNewAttachCommandErrors(t *testing.T) {
name string
args []string
expectedError string
containerInspectFunc func(img string) (types.ContainerJSON, error)
containerInspectFunc func(img string) (container.InspectResponse, error)
}{
{
name: "client-error",
args: []string{"5cb5bb5e4a3b"},
expectedError: "something went wrong",
containerInspectFunc: func(containerID string) (types.ContainerJSON, error) {
return types.ContainerJSON{}, errors.Errorf("something went wrong")
containerInspectFunc: func(containerID string) (container.InspectResponse, error) {
return container.InspectResponse{}, errors.New("something went wrong")
},
},
{
name: "client-stopped",
args: []string{"5cb5bb5e4a3b"},
expectedError: "You cannot attach to a stopped container",
containerInspectFunc: func(containerID string) (types.ContainerJSON, error) {
c := types.ContainerJSON{}
c.ContainerJSONBase = &types.ContainerJSONBase{}
c.ContainerJSONBase.State = &types.ContainerState{Running: false}
return c, nil
containerInspectFunc: func(containerID string) (container.InspectResponse, error) {
return container.InspectResponse{
ContainerJSONBase: &container.ContainerJSONBase{
State: &container.State{
Running: false,
},
},
}, nil
},
},
{
name: "client-paused",
args: []string{"5cb5bb5e4a3b"},
expectedError: "You cannot attach to a paused container",
containerInspectFunc: func(containerID string) (types.ContainerJSON, error) {
c := types.ContainerJSON{}
c.ContainerJSONBase = &types.ContainerJSONBase{}
c.ContainerJSONBase.State = &types.ContainerState{
Running: true,
Paused: true,
}
return c, nil
containerInspectFunc: func(containerID string) (container.InspectResponse, error) {
return container.InspectResponse{
ContainerJSONBase: &container.ContainerJSONBase{
State: &container.State{
Running: true,
Paused: true,
},
},
}, nil
},
},
{
name: "client-restarting",
args: []string{"5cb5bb5e4a3b"},
expectedError: "You cannot attach to a restarting container",
containerInspectFunc: func(containerID string) (types.ContainerJSON, error) {
c := types.ContainerJSON{}
c.ContainerJSONBase = &types.ContainerJSONBase{}
c.ContainerJSONBase.State = &types.ContainerState{
Running: true,
Paused: false,
Restarting: true,
}
return c, nil
containerInspectFunc: func(containerID string) (container.InspectResponse, error) {
return container.InspectResponse{
ContainerJSONBase: &container.ContainerJSONBase{
State: &container.State{
Running: true,
Paused: false,
Restarting: true,
},
},
}, nil
},
},
}
for _, tc := range testCases {
cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}))
cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
t.Run(tc.name, func(t *testing.T) {
cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}))
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
})
}
}
func TestGetExitStatus(t *testing.T) {
var (
expectedErr = errors.New("unexpected error")
errC = make(chan error, 1)
resultC = make(chan container.WaitResponse, 1)
)
expectedErr := errors.New("unexpected error")
testcases := []struct {
result *container.WaitResponse
@ -112,13 +115,17 @@ func TestGetExitStatus(t *testing.T) {
}
for _, testcase := range testcases {
errC := make(chan error, 1)
resultC := make(chan container.WaitResponse, 1)
if testcase.err != nil {
errC <- testcase.err
}
if testcase.result != nil {
resultC <- *testcase.result
}
err := getExitStatus(errC, resultC)
if testcase.expectedError == nil {
assert.NilError(t, err)
} else {

View File

@ -0,0 +1,46 @@
package container
import (
"fmt"
"os"
"strings"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/types"
)
// readCredentials resolves auth-config from the current environment to be
// applied to the container if the `--use-api-socket` flag is set.
//
// - If a valid "DOCKER_AUTH_CONFIG" env-var is found, and it contains
// credentials, it's value is used.
// - If no "DOCKER_AUTH_CONFIG" env-var is found, or it does not contain
// credentials, it attempts to read from the CLI's credentials store.
//
// It returns an error if either the "DOCKER_AUTH_CONFIG" is incorrectly
// formatted, or when failing to read from the credentials store.
//
// A nil value is returned if neither option contained any credentials.
func readCredentials(dockerCLI config.Provider) (creds map[string]types.AuthConfig, _ error) {
if v, ok := os.LookupEnv("DOCKER_AUTH_CONFIG"); ok && v != "" {
// The results are expected to have been unmarshaled the same as
// when reading from a config-file, which includes decoding the
// base64-encoded "username:password" into the "UserName" and
// "Password" fields.
ac := &configfile.ConfigFile{}
if err := ac.LoadFromReader(strings.NewReader(v)); err != nil {
return nil, fmt.Errorf("failed to read credentials from DOCKER_AUTH_CONFIG: %w", err)
}
if len(ac.AuthConfigs) > 0 {
return ac.AuthConfigs, nil
}
}
// Resolve this here for later, ensuring we error our before we create the container.
creds, err := dockerCLI.ConfigFile().GetAllCredentials()
if err != nil {
return nil, fmt.Errorf("resolving credentials failed: %w", err)
}
return creds, nil
}

View File

@ -4,62 +4,68 @@ import (
"context"
"io"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/system"
"github.com/docker/docker/client"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/moby/moby/api/types"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/filters"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/system"
"github.com/moby/moby/client"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
type fakeClient struct {
client.Client
inspectFunc func(string) (types.ContainerJSON, error)
inspectFunc func(string) (container.InspectResponse, error)
execInspectFunc func(execID string) (container.ExecInspect, error)
execCreateFunc func(containerID string, options container.ExecOptions) (types.IDResponse, error)
execCreateFunc func(containerID string, options container.ExecOptions) (container.ExecCreateResponse, error)
createContainerFunc func(config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *specs.Platform,
platform *ocispec.Platform,
containerName string) (container.CreateResponse, error)
containerStartFunc func(containerID string, options container.StartOptions) error
imageCreateFunc func(parentReference string, options image.CreateOptions) (io.ReadCloser, error)
imageCreateFunc func(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error)
infoFunc func() (system.Info, error)
containerStatPathFunc func(containerID, path string) (container.PathStat, error)
containerCopyFromFunc func(containerID, srcPath string) (io.ReadCloser, container.PathStat, error)
logFunc func(string, container.LogsOptions) (io.ReadCloser, error)
waitFunc func(string) (<-chan container.WaitResponse, <-chan error)
containerListFunc func(container.ListOptions) ([]types.Container, error)
containerListFunc func(container.ListOptions) ([]container.Summary, error)
containerExportFunc func(string) (io.ReadCloser, error)
containerExecResizeFunc func(id string, options container.ResizeOptions) error
containerRemoveFunc func(ctx context.Context, containerID string, options container.RemoveOptions) error
containerRestartFunc func(ctx context.Context, containerID string, options container.StopOptions) error
containerStopFunc func(ctx context.Context, containerID string, options container.StopOptions) error
containerKillFunc func(ctx context.Context, containerID, signal string) error
containerPruneFunc func(ctx context.Context, pruneFilters filters.Args) (container.PruneReport, error)
containerAttachFunc func(ctx context.Context, containerID string, options container.AttachOptions) (types.HijackedResponse, error)
containerDiffFunc func(ctx context.Context, containerID string) ([]container.FilesystemChange, error)
containerRenameFunc func(ctx context.Context, oldName, newName string) error
containerCommitFunc func(ctx context.Context, container string, options container.CommitOptions) (container.CommitResponse, error)
containerPauseFunc func(ctx context.Context, container string) error
Version string
}
func (f *fakeClient) ContainerList(_ context.Context, options container.ListOptions) ([]types.Container, error) {
func (f *fakeClient) ContainerList(_ context.Context, options container.ListOptions) ([]container.Summary, error) {
if f.containerListFunc != nil {
return f.containerListFunc(options)
}
return []types.Container{}, nil
return []container.Summary{}, nil
}
func (f *fakeClient) ContainerInspect(_ context.Context, containerID string) (types.ContainerJSON, error) {
func (f *fakeClient) ContainerInspect(_ context.Context, containerID string) (container.InspectResponse, error) {
if f.inspectFunc != nil {
return f.inspectFunc(containerID)
}
return types.ContainerJSON{}, nil
return container.InspectResponse{}, nil
}
func (f *fakeClient) ContainerExecCreate(_ context.Context, containerID string, config container.ExecOptions) (types.IDResponse, error) {
func (f *fakeClient) ContainerExecCreate(_ context.Context, containerID string, config container.ExecOptions) (container.ExecCreateResponse, error) {
if f.execCreateFunc != nil {
return f.execCreateFunc(containerID, config)
}
return types.IDResponse{}, nil
return container.ExecCreateResponse{}, nil
}
func (f *fakeClient) ContainerExecInspect(_ context.Context, execID string) (container.ExecInspect, error) {
@ -69,7 +75,7 @@ func (f *fakeClient) ContainerExecInspect(_ context.Context, execID string) (con
return container.ExecInspect{}, nil
}
func (f *fakeClient) ContainerExecStart(context.Context, string, container.ExecStartOptions) error {
func (*fakeClient) ContainerExecStart(context.Context, string, container.ExecStartOptions) error {
return nil
}
@ -78,7 +84,7 @@ func (f *fakeClient) ContainerCreate(
config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *specs.Platform,
platform *ocispec.Platform,
containerName string,
) (container.CreateResponse, error) {
if f.createContainerFunc != nil {
@ -94,9 +100,9 @@ func (f *fakeClient) ContainerRemove(ctx context.Context, containerID string, op
return nil
}
func (f *fakeClient) ImageCreate(_ context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error) {
func (f *fakeClient) ImageCreate(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error) {
if f.imageCreateFunc != nil {
return f.imageCreateFunc(parentReference, options)
return f.imageCreateFunc(ctx, parentReference, options)
}
return nil, nil
}
@ -175,9 +181,54 @@ func (f *fakeClient) ContainersPrune(ctx context.Context, pruneFilters filters.A
return container.PruneReport{}, nil
}
func (f *fakeClient) ContainerRestart(ctx context.Context, containerID string, options container.StopOptions) error {
if f.containerRestartFunc != nil {
return f.containerRestartFunc(ctx, containerID, options)
}
return nil
}
func (f *fakeClient) ContainerStop(ctx context.Context, containerID string, options container.StopOptions) error {
if f.containerStopFunc != nil {
return f.containerStopFunc(ctx, containerID, options)
}
return nil
}
func (f *fakeClient) ContainerAttach(ctx context.Context, containerID string, options container.AttachOptions) (types.HijackedResponse, error) {
if f.containerAttachFunc != nil {
return f.containerAttachFunc(ctx, containerID, options)
}
return types.HijackedResponse{}, nil
}
func (f *fakeClient) ContainerDiff(ctx context.Context, containerID string) ([]container.FilesystemChange, error) {
if f.containerDiffFunc != nil {
return f.containerDiffFunc(ctx, containerID)
}
return []container.FilesystemChange{}, nil
}
func (f *fakeClient) ContainerRename(ctx context.Context, oldName, newName string) error {
if f.containerRenameFunc != nil {
return f.containerRenameFunc(ctx, oldName, newName)
}
return nil
}
func (f *fakeClient) ContainerCommit(ctx context.Context, containerID string, options container.CommitOptions) (container.CommitResponse, error) {
if f.containerCommitFunc != nil {
return f.containerCommitFunc(ctx, containerID, options)
}
return container.CommitResponse{}, nil
}
func (f *fakeClient) ContainerPause(ctx context.Context, containerID string) error {
if f.containerPauseFunc != nil {
return f.containerPauseFunc(ctx, containerID)
}
return nil
}

View File

@ -28,7 +28,7 @@ func NewContainerCommand(dockerCli command.Cli) *cobra.Command {
NewPortCommand(dockerCli),
NewRenameCommand(dockerCli),
NewRestartCommand(dockerCli),
NewRmCommand(dockerCli),
newRemoveCommand(dockerCli),
NewRunCommand(dockerCli),
NewStartCommand(dockerCli),
NewStatsCommand(dockerCli),

View File

@ -8,7 +8,7 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
"github.com/moby/moby/api/types/container"
"github.com/spf13/cobra"
)
@ -61,7 +61,7 @@ func runCommit(ctx context.Context, dockerCli command.Cli, options *commitOption
Reference: options.reference,
Comment: options.comment,
Author: options.author,
Changes: options.changes.GetAll(),
Changes: options.changes.GetSlice(),
Pause: options.pause,
})
if err != nil {

View File

@ -0,0 +1,70 @@
package container
import (
"context"
"errors"
"io"
"testing"
"github.com/docker/cli/internal/test"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestRunCommit(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
containerCommitFunc: func(
ctx context.Context,
ctr string,
options container.CommitOptions,
) (container.CommitResponse, error) {
assert.Check(t, is.Equal(options.Author, "Author Name <author@name.com>"))
assert.Check(t, is.DeepEqual(options.Changes, []string{"EXPOSE 80"}))
assert.Check(t, is.Equal(options.Comment, "commit message"))
assert.Check(t, is.Equal(options.Pause, false))
assert.Check(t, is.Equal(ctr, "container-id"))
return container.CommitResponse{ID: "image-id"}, nil
},
})
cmd := NewCommitCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs(
[]string{
"--author", "Author Name <author@name.com>",
"--change", "EXPOSE 80",
"--message", "commit message",
"--pause=false",
"container-id",
},
)
err := cmd.Execute()
assert.NilError(t, err)
assert.Assert(t, is.Equal(cli.OutBuffer().String(), "image-id\n"))
}
func TestRunCommitClientError(t *testing.T) {
clientError := errors.New("client error")
cli := test.NewFakeCli(&fakeClient{
containerCommitFunc: func(
ctx context.Context,
ctr string,
options container.CommitOptions,
) (container.CommitResponse, error) {
return container.CommitResponse{}, clientError
},
})
cmd := NewCommitCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"container-id"})
err := cmd.Execute()
assert.ErrorIs(t, err, clientError)
}

View File

@ -0,0 +1,335 @@
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.23
package container
import (
"strings"
"sync"
"github.com/docker/cli/cli/command/completion"
"github.com/moby/moby/api/types/container"
"github.com/moby/sys/capability"
"github.com/moby/sys/signal"
"github.com/spf13/cobra"
)
// allCaps is the magic value for "all capabilities".
const allCaps = "ALL"
// allLinuxCapabilities is a list of all known Linux capabilities.
//
// TODO(thaJeztah): add descriptions, and enable descriptions for our completion scripts (cobra.CompletionOptions.DisableDescriptions is currently set to "true")
// TODO(thaJeztah): consider what casing we want to use for completion (see below);
//
// We need to consider what format is most convenient; currently we use the
// canonical name (uppercase and "CAP_" prefix), however, tab-completion is
// case-sensitive by default, so requires the user to type uppercase letters
// to filter the list of options.
//
// Bash completion provides a `completion-ignore-case on` option to make completion
// case-insensitive (https://askubuntu.com/a/87066), but it looks to be a global
// option; the current cobra.CompletionOptions also don't provide this as an option
// to be used in the generated completion-script.
//
// Fish completion has `smartcase` (by default?) which matches any case if
// all of the input is lowercase.
//
// Zsh does not appear have a dedicated option, but allows setting matching-rules
// (see https://superuser.com/a/1092328).
var allLinuxCapabilities = sync.OnceValue(func() []string {
caps := capability.ListKnown()
out := make([]string, 0, len(caps)+1)
out = append(out, allCaps)
for _, c := range caps {
out = append(out, "CAP_"+strings.ToUpper(c.String()))
}
return out
})
// logDriverOptions provides the options for each built-in logging driver.
var logDriverOptions = map[string][]string{
"awslogs": {
"max-buffer-size", "mode", "awslogs-create-group", "awslogs-credentials-endpoint", "awslogs-datetime-format",
"awslogs-group", "awslogs-multiline-pattern", "awslogs-region", "awslogs-stream", "tag",
},
"fluentd": {
"max-buffer-size", "mode", "env", "env-regex", "labels", "fluentd-address", "fluentd-async",
"fluentd-buffer-limit", "fluentd-request-ack", "fluentd-retry-wait", "fluentd-max-retries",
"fluentd-sub-second-precision", "fluentd-write-timeout", "tag",
},
"gcplogs": {
"max-buffer-size", "mode", "env", "env-regex", "labels", "gcp-log-cmd", "gcp-meta-id", "gcp-meta-name",
"gcp-meta-zone", "gcp-project",
},
"gelf": {
"max-buffer-size", "mode", "env", "env-regex", "labels", "gelf-address", "gelf-compression-level",
"gelf-compression-type", "gelf-tcp-max-reconnect", "gelf-tcp-reconnect-delay", "tag",
},
"journald": {"max-buffer-size", "mode", "env", "env-regex", "labels", "tag"},
"json-file": {"max-buffer-size", "mode", "env", "env-regex", "labels", "compress", "max-file", "max-size"},
"local": {"max-buffer-size", "mode", "compress", "max-file", "max-size"},
"none": {},
"splunk": {
"max-buffer-size", "mode", "env", "env-regex", "labels", "splunk-caname", "splunk-capath", "splunk-format",
"splunk-gzip", "splunk-gzip-level", "splunk-index", "splunk-insecureskipverify", "splunk-source",
"splunk-sourcetype", "splunk-token", "splunk-url", "splunk-verify-connection", "tag",
},
"syslog": {
"max-buffer-size", "mode", "env", "env-regex", "labels", "syslog-address", "syslog-facility", "syslog-format",
"syslog-tls-ca-cert", "syslog-tls-cert", "syslog-tls-key", "syslog-tls-skip-verify", "tag",
},
}
// builtInLogDrivers provides a list of the built-in logging drivers.
var builtInLogDrivers = sync.OnceValue(func() []string {
drivers := make([]string, 0, len(logDriverOptions))
for driver := range logDriverOptions {
drivers = append(drivers, driver)
}
return drivers
})
// allLogDriverOptions provides all options of the built-in logging drivers.
// The list does not contain duplicates.
var allLogDriverOptions = sync.OnceValue(func() []string {
var result []string
seen := make(map[string]bool)
for driver := range logDriverOptions {
for _, opt := range logDriverOptions[driver] {
if !seen[opt] {
seen[opt] = true
result = append(result, opt)
}
}
}
return result
})
// restartPolicies is a list of all valid restart-policies..
//
// TODO(thaJeztah): add descriptions, and enable descriptions for our completion scripts (cobra.CompletionOptions.DisableDescriptions is currently set to "true")
var restartPolicies = []string{
string(container.RestartPolicyDisabled),
string(container.RestartPolicyAlways),
string(container.RestartPolicyOnFailure),
string(container.RestartPolicyUnlessStopped),
}
// addCompletions adds the completions that `run` and `create` have in common.
func addCompletions(cmd *cobra.Command, dockerCLI completion.APIClientProvider) {
_ = cmd.RegisterFlagCompletionFunc("attach", completion.FromList("stderr", "stdin", "stdout"))
_ = cmd.RegisterFlagCompletionFunc("cap-add", completeLinuxCapabilityNames)
_ = cmd.RegisterFlagCompletionFunc("cap-drop", completeLinuxCapabilityNames)
_ = cmd.RegisterFlagCompletionFunc("cgroupns", completeCgroupns())
_ = cmd.RegisterFlagCompletionFunc("env", completion.EnvVarNames)
_ = cmd.RegisterFlagCompletionFunc("env-file", completion.FileNames)
_ = cmd.RegisterFlagCompletionFunc("ipc", completeIpc(dockerCLI))
_ = cmd.RegisterFlagCompletionFunc("link", completeLink(dockerCLI))
_ = cmd.RegisterFlagCompletionFunc("log-driver", completeLogDriver(dockerCLI))
_ = cmd.RegisterFlagCompletionFunc("log-opt", completeLogOpt)
_ = cmd.RegisterFlagCompletionFunc("network", completion.NetworkNames(dockerCLI))
_ = cmd.RegisterFlagCompletionFunc("pid", completePid(dockerCLI))
_ = cmd.RegisterFlagCompletionFunc("platform", completion.Platforms)
_ = cmd.RegisterFlagCompletionFunc("pull", completion.FromList(PullImageAlways, PullImageMissing, PullImageNever))
_ = cmd.RegisterFlagCompletionFunc("restart", completeRestartPolicies)
_ = cmd.RegisterFlagCompletionFunc("security-opt", completeSecurityOpt)
_ = cmd.RegisterFlagCompletionFunc("stop-signal", completeSignals)
_ = cmd.RegisterFlagCompletionFunc("storage-opt", completeStorageOpt)
_ = cmd.RegisterFlagCompletionFunc("ulimit", completeUlimit)
_ = cmd.RegisterFlagCompletionFunc("userns", completion.FromList("host"))
_ = cmd.RegisterFlagCompletionFunc("uts", completion.FromList("host"))
_ = cmd.RegisterFlagCompletionFunc("volume-driver", completeVolumeDriver(dockerCLI))
_ = cmd.RegisterFlagCompletionFunc("volumes-from", completion.ContainerNames(dockerCLI, true))
}
// completeCgroupns implements shell completion for the `--cgroupns` option of `run` and `create`.
func completeCgroupns() cobra.CompletionFunc {
return completion.FromList(string(container.CgroupnsModeHost), string(container.CgroupnsModePrivate))
}
// completeDetachKeys implements shell completion for the `--detach-keys` option of `run` and `create`.
func completeDetachKeys(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"ctrl-"}, cobra.ShellCompDirectiveNoSpace
}
// completeIpc implements shell completion for the `--ipc` option of `run` and `create`.
// The completion is partly composite.
func completeIpc(dockerCLI completion.APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(toComplete) > 0 && strings.HasPrefix("container", toComplete) { //nolint:gocritic // not swapped, matches partly typed "container"
return []string{"container:"}, cobra.ShellCompDirectiveNoSpace
}
if strings.HasPrefix(toComplete, "container:") {
names, _ := completion.ContainerNames(dockerCLI, true)(cmd, args, toComplete)
return prefixWith("container:", names), cobra.ShellCompDirectiveNoFileComp
}
return []string{
string(container.IPCModeContainer + ":"),
string(container.IPCModeHost),
string(container.IPCModeNone),
string(container.IPCModePrivate),
string(container.IPCModeShareable),
}, cobra.ShellCompDirectiveNoFileComp
}
}
// completeLink implements shell completion for the `--link` option of `run` and `create`.
func completeLink(dockerCLI completion.APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return postfixWith(":", containerNames(dockerCLI, cmd, args, toComplete)), cobra.ShellCompDirectiveNoSpace
}
}
// completeLogDriver implements shell completion for the `--log-driver` option of `run` and `create`.
// The log drivers are collected from a call to the Info endpoint with a fallback to a hard-coded list
// of the build-in log drivers.
func completeLogDriver(dockerCLI completion.APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
info, err := dockerCLI.Client().Info(cmd.Context())
if err != nil {
return builtInLogDrivers(), cobra.ShellCompDirectiveNoFileComp
}
drivers := info.Plugins.Log
return drivers, cobra.ShellCompDirectiveNoFileComp
}
}
// completeLogOpt implements shell completion for the `--log-opt` option of `run` and `create`.
// If the user supplied a log-driver, only options for that driver are returned.
func completeLogOpt(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
driver, _ := cmd.Flags().GetString("log-driver")
if options, exists := logDriverOptions[driver]; exists {
return postfixWith("=", options), cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp
}
return postfixWith("=", allLogDriverOptions()), cobra.ShellCompDirectiveNoSpace
}
// completePid implements shell completion for the `--pid` option of `run` and `create`.
func completePid(dockerCLI completion.APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(toComplete) > 0 && strings.HasPrefix("container", toComplete) { //nolint:gocritic // not swapped, matches partly typed "container"
return []string{"container:"}, cobra.ShellCompDirectiveNoSpace
}
if strings.HasPrefix(toComplete, "container:") {
names, _ := completion.ContainerNames(dockerCLI, true)(cmd, args, toComplete)
return prefixWith("container:", names), cobra.ShellCompDirectiveNoFileComp
}
return []string{"container:", "host"}, cobra.ShellCompDirectiveNoFileComp
}
}
// completeSecurityOpt implements shell completion for the `--security-opt` option of `run` and `create`.
// The completion is partly composite.
func completeSecurityOpt(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(toComplete) > 0 && strings.HasPrefix("apparmor=", toComplete) { //nolint:gocritic // not swapped, matches partly typed "apparmor="
return []string{"apparmor="}, cobra.ShellCompDirectiveNoSpace
}
if len(toComplete) > 0 && strings.HasPrefix("label", toComplete) { //nolint:gocritic // not swapped, matches partly typed "label"
return []string{"label="}, cobra.ShellCompDirectiveNoSpace
}
if strings.HasPrefix(toComplete, "label=") {
if strings.HasPrefix(toComplete, "label=d") {
return []string{"label=disable"}, cobra.ShellCompDirectiveNoFileComp
}
labels := []string{"disable", "level:", "role:", "type:", "user:"}
return prefixWith("label=", labels), cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp
}
// length must be > 1 here so that completion of "s" falls through.
if len(toComplete) > 1 && strings.HasPrefix("seccomp", toComplete) { //nolint:gocritic // not swapped, matches partly typed "seccomp"
return []string{"seccomp="}, cobra.ShellCompDirectiveNoSpace
}
if strings.HasPrefix(toComplete, "seccomp=") {
return []string{"seccomp=unconfined"}, cobra.ShellCompDirectiveNoFileComp
}
return []string{"apparmor=", "label=", "no-new-privileges", "seccomp=", "systempaths=unconfined"}, cobra.ShellCompDirectiveNoFileComp
}
// completeStorageOpt implements shell completion for the `--storage-opt` option of `run` and `create`.
func completeStorageOpt(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"size="}, cobra.ShellCompDirectiveNoSpace
}
// completeUlimit implements shell completion for the `--ulimit` option of `run` and `create`.
func completeUlimit(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
limits := []string{
"as",
"chroot",
"core",
"cpu",
"data",
"fsize",
"locks",
"maxlogins",
"maxsyslogins",
"memlock",
"msgqueue",
"nice",
"nofile",
"nproc",
"priority",
"rss",
"rtprio",
"sigpending",
"stack",
}
return postfixWith("=", limits), cobra.ShellCompDirectiveNoSpace
}
// completeVolumeDriver contacts the API to get the built-in and installed volume drivers.
func completeVolumeDriver(dockerCLI completion.APIClientProvider) cobra.CompletionFunc {
return func(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
info, err := dockerCLI.Client().Info(cmd.Context())
if err != nil {
// fallback: the built-in drivers
return []string{"local"}, cobra.ShellCompDirectiveNoFileComp
}
drivers := info.Plugins.Volume
return drivers, cobra.ShellCompDirectiveNoFileComp
}
}
// containerNames contacts the API to get names and optionally IDs of containers.
// In case of an error, an empty list is returned.
func containerNames(dockerCLI completion.APIClientProvider, cmd *cobra.Command, args []string, toComplete string) []string {
names, _ := completion.ContainerNames(dockerCLI, true)(cmd, args, toComplete)
if names == nil {
return []string{}
}
return names
}
// prefixWith prefixes every element in the slice with the given prefix.
func prefixWith(prefix string, values []string) []string {
result := make([]string, len(values))
for i, v := range values {
result[i] = prefix + v
}
return result
}
// postfixWith appends postfix to every element in the slice.
func postfixWith(postfix string, values []string) []string {
result := make([]string, len(values))
for i, v := range values {
result[i] = v + postfix
}
return result
}
func completeLinuxCapabilityNames(cmd *cobra.Command, args []string, toComplete string) (names []string, _ cobra.ShellCompDirective) {
return completion.FromList(allLinuxCapabilities()...)(cmd, args, toComplete)
}
func completeRestartPolicies(cmd *cobra.Command, args []string, toComplete string) (names []string, _ cobra.ShellCompDirective) {
return completion.FromList(restartPolicies...)(cmd, args, toComplete)
}
func completeSignals(cmd *cobra.Command, args []string, toComplete string) (names []string, _ cobra.ShellCompDirective) {
// TODO(thaJeztah): do we want to provide the full list here, or a subset?
signalNames := make([]string, 0, len(signal.SignalMap))
for k := range signal.SignalMap {
signalNames = append(signalNames, k)
}
return completion.FromList(signalNames...)(cmd, args, toComplete)
}

View File

@ -0,0 +1,134 @@
package container
import (
"strings"
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/internal/test/builders"
"github.com/moby/moby/api/types/container"
"github.com/moby/sys/signal"
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestCompleteLinuxCapabilityNames(t *testing.T) {
names, directives := completeLinuxCapabilityNames(nil, nil, "")
assert.Check(t, is.Equal(directives&cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveNoFileComp), "Should not perform file completion")
assert.Assert(t, len(names) > 1)
assert.Check(t, names[0] == allCaps)
for _, name := range names[1:] {
assert.Check(t, strings.HasPrefix(name, "CAP_"))
assert.Check(t, is.Equal(name, strings.ToUpper(name)), "Should be formatted uppercase")
}
}
func TestCompletePid(t *testing.T) {
tests := []struct {
containerListFunc func(container.ListOptions) ([]container.Summary, error)
toComplete string
expectedCompletions []string
expectedDirective cobra.ShellCompDirective
}{
{
toComplete: "",
expectedCompletions: []string{"container:", "host"},
expectedDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
toComplete: "c",
expectedCompletions: []string{"container:"},
expectedDirective: cobra.ShellCompDirectiveNoSpace,
},
{
containerListFunc: func(container.ListOptions) ([]container.Summary, error) {
return []container.Summary{
*builders.Container("c1"),
*builders.Container("c2"),
}, nil
},
toComplete: "container:",
expectedCompletions: []string{"container:c1", "container:c2"},
expectedDirective: cobra.ShellCompDirectiveNoFileComp,
},
}
for _, tc := range tests {
t.Run(tc.toComplete, func(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
containerListFunc: tc.containerListFunc,
})
completions, directive := completePid(cli)(NewRunCommand(cli), nil, tc.toComplete)
assert.Check(t, is.DeepEqual(completions, tc.expectedCompletions))
assert.Check(t, is.Equal(directive, tc.expectedDirective))
})
}
}
func TestCompleteRestartPolicies(t *testing.T) {
values, directives := completeRestartPolicies(nil, nil, "")
assert.Check(t, is.Equal(directives&cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveNoFileComp), "Should not perform file completion")
expected := restartPolicies
assert.Check(t, is.DeepEqual(values, expected))
}
func TestCompleteSecurityOpt(t *testing.T) {
tests := []struct {
toComplete string
expectedCompletions []string
expectedDirective cobra.ShellCompDirective
}{
{
toComplete: "",
expectedCompletions: []string{"apparmor=", "label=", "no-new-privileges", "seccomp=", "systempaths=unconfined"},
expectedDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
toComplete: "apparmor=",
expectedCompletions: []string{"apparmor="},
expectedDirective: cobra.ShellCompDirectiveNoSpace,
},
{
toComplete: "label=",
expectedCompletions: []string{"label=disable", "label=level:", "label=role:", "label=type:", "label=user:"},
expectedDirective: cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp,
},
{
toComplete: "s",
// We do not filter matching completions but delegate this task to the shell script.
expectedCompletions: []string{"apparmor=", "label=", "no-new-privileges", "seccomp=", "systempaths=unconfined"},
expectedDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
toComplete: "se",
expectedCompletions: []string{"seccomp="},
expectedDirective: cobra.ShellCompDirectiveNoSpace,
},
{
toComplete: "seccomp=",
expectedCompletions: []string{"seccomp=unconfined"},
expectedDirective: cobra.ShellCompDirectiveNoFileComp,
},
{
toComplete: "sy",
expectedCompletions: []string{"apparmor=", "label=", "no-new-privileges", "seccomp=", "systempaths=unconfined"},
expectedDirective: cobra.ShellCompDirectiveNoFileComp,
},
}
for _, tc := range tests {
t.Run(tc.toComplete, func(t *testing.T) {
completions, directive := completeSecurityOpt(nil, nil, tc.toComplete)
assert.Check(t, is.DeepEqual(completions, tc.expectedCompletions))
assert.Check(t, is.Equal(directive, tc.expectedDirective))
})
}
}
func TestCompleteSignals(t *testing.T) {
values, directives := completeSignals(nil, nil, "")
assert.Check(t, is.Equal(directives&cobra.ShellCompDirectiveNoFileComp, cobra.ShellCompDirectiveNoFileComp), "Should not perform file completion")
assert.Check(t, len(values) > 1)
assert.Check(t, is.Len(values, len(signal.SignalMap)))
}

View File

@ -15,10 +15,9 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/streams"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/system"
units "github.com/docker/go-units"
"github.com/docker/go-units"
"github.com/moby/go-archive"
"github.com/moby/moby/api/types/container"
"github.com/morikuni/aec"
"github.com/pkg/errors"
"github.com/spf13/cobra"
@ -130,13 +129,12 @@ func NewCopyCommand(dockerCli command.Cli) *cobra.Command {
Use: `cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH`,
Short: "Copy files/folders between a container and the local filesystem",
Long: strings.Join([]string{
"Copy files/folders between a container and the local filesystem\n",
"\nUse '-' as the source to read a tar archive from stdin\n",
"and extract it to a directory destination in a container.\n",
"Use '-' as the destination to stream a tar archive of a\n",
"container source to stdout.",
}, ""),
Long: `Copy files/folders between a container and the local filesystem
Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.`,
Args: cli.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
if args[0] == "" {
@ -203,14 +201,15 @@ func runCopy(ctx context.Context, dockerCli command.Cli, opts copyOptions) error
}
}
func resolveLocalPath(localPath string) (absPath string, err error) {
if absPath, err = filepath.Abs(localPath); err != nil {
return
func resolveLocalPath(localPath string) (absPath string, _ error) {
absPath, err := filepath.Abs(localPath)
if err != nil {
return "", err
}
return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
}
func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpConfig) (err error) {
func copyFromContainer(ctx context.Context, dockerCLI command.Cli, copyConfig cpConfig) (err error) {
dstPath := copyConfig.destPath
srcPath := copyConfig.sourcePath
@ -226,16 +225,16 @@ func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cp
return err
}
client := dockerCli.Client()
apiClient := dockerCLI.Client()
// if client requests to follow symbol link, then must decide target file to be copied
var rebaseName string
if copyConfig.followLink {
srcStat, err := client.ContainerStatPath(ctx, copyConfig.container, srcPath)
srcStat, err := apiClient.ContainerStatPath(ctx, copyConfig.container, srcPath)
// If the destination is a symbolic link, we should follow it.
if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
linkTarget := srcStat.LinkTarget
if !system.IsAbs(linkTarget) {
if !isAbs(linkTarget) {
// Join with the parent directory.
srcParent, _ := archive.SplitPathDirEntry(srcPath)
linkTarget = filepath.Join(srcParent, linkTarget)
@ -249,14 +248,14 @@ func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cp
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
content, stat, err := client.CopyFromContainer(ctx, copyConfig.container, srcPath)
content, stat, err := apiClient.CopyFromContainer(ctx, copyConfig.container, srcPath)
if err != nil {
return err
}
defer content.Close()
if dstPath == "-" {
_, err = io.Copy(dockerCli.Out(), content)
_, err = io.Copy(dockerCLI.Out(), content)
return err
}
@ -285,12 +284,12 @@ func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cp
return archive.CopyTo(preArchive, srcInfo, dstPath)
}
restore, done := copyProgress(ctx, dockerCli.Err(), copyFromContainerHeader, &copiedSize)
restore, done := copyProgress(ctx, dockerCLI.Err(), copyFromContainerHeader, &copiedSize)
res := archive.CopyTo(preArchive, srcInfo, dstPath)
cancel()
<-done
restore()
fmt.Fprintln(dockerCli.Err(), "Successfully copied", progressHumanSize(copiedSize), "to", dstPath)
_, _ = fmt.Fprintln(dockerCLI.Err(), "Successfully copied", progressHumanSize(copiedSize), "to", dstPath)
return res
}
@ -299,7 +298,7 @@ func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cp
// about both the source and destination. The API is a simple tar
// archive/extract API but we can use the stat info header about the
// destination to be more informed about exactly what the destination is.
func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpConfig) (err error) {
func copyToContainer(ctx context.Context, dockerCLI command.Cli, copyConfig cpConfig) (err error) {
srcPath := copyConfig.sourcePath
dstPath := copyConfig.destPath
@ -311,22 +310,23 @@ func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpCo
}
}
client := dockerCli.Client()
apiClient := dockerCLI.Client()
// Prepare destination copy info by stat-ing the container path.
dstInfo := archive.CopyInfo{Path: dstPath}
dstStat, err := client.ContainerStatPath(ctx, copyConfig.container, dstPath)
dstStat, err := apiClient.ContainerStatPath(ctx, copyConfig.container, dstPath)
// If the destination is a symbolic link, we should evaluate it.
if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
linkTarget := dstStat.LinkTarget
if !system.IsAbs(linkTarget) {
if !isAbs(linkTarget) {
// Join with the parent directory.
dstParent, _ := archive.SplitPathDirEntry(dstPath)
linkTarget = filepath.Join(dstParent, linkTarget)
}
dstInfo.Path = linkTarget
dstStat, err = client.ContainerStatPath(ctx, copyConfig.container, linkTarget)
dstStat, err = apiClient.ContainerStatPath(ctx, copyConfig.container, linkTarget)
// FIXME(thaJeztah): unhandled error (should this return?)
}
// Validate the destination path
@ -398,21 +398,20 @@ func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpCo
}
options := container.CopyToContainerOptions{
AllowOverwriteDirWithFile: false,
CopyUIDGID: copyConfig.copyUIDGID,
CopyUIDGID: copyConfig.copyUIDGID,
}
if copyConfig.quiet {
return client.CopyToContainer(ctx, copyConfig.container, resolvedDstPath, content, options)
return apiClient.CopyToContainer(ctx, copyConfig.container, resolvedDstPath, content, options)
}
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
restore, done := copyProgress(ctx, dockerCli.Err(), copyToContainerHeader, &copiedSize)
res := client.CopyToContainer(ctx, copyConfig.container, resolvedDstPath, content, options)
restore, done := copyProgress(ctx, dockerCLI.Err(), copyToContainerHeader, &copiedSize)
res := apiClient.CopyToContainer(ctx, copyConfig.container, resolvedDstPath, content, options)
cancel()
<-done
restore()
fmt.Fprintln(dockerCli.Err(), "Successfully copied", progressHumanSize(copiedSize), "to", copyConfig.container+":"+dstInfo.Path)
fmt.Fprintln(dockerCLI.Err(), "Successfully copied", progressHumanSize(copiedSize), "to", copyConfig.container+":"+dstInfo.Path)
return res
}
@ -434,7 +433,7 @@ func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpCo
// client, a `:` could be part of an absolute Windows path, in which case it
// is immediately proceeded by a backslash.
func splitCpArg(arg string) (ctr, path string) {
if system.IsAbs(arg) {
if isAbs(arg) {
// Explicit local absolute path, e.g., `C:\foo` or `/foo`.
return "", arg
}
@ -448,3 +447,15 @@ func splitCpArg(arg string) (ctr, path string) {
return ctr, path
}
// IsAbs is a platform-agnostic wrapper for filepath.IsAbs.
//
// On Windows, golang filepath.IsAbs does not consider a path \windows\system32
// as absolute as it doesn't start with a drive-letter/colon combination. However,
// in docker we need to verify things such as WORKDIR /windows/system32 in
// a Dockerfile (which gets translated to \windows\system32 when being processed
// by the daemon). This SHOULD be treated as absolute from a docker processing
// perspective.
func isAbs(path string) bool {
return filepath.IsAbs(path) || strings.HasPrefix(path, string(os.PathSeparator))
}

View File

@ -9,12 +9,12 @@ import (
"testing"
"github.com/docker/cli/internal/test"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/pkg/archive"
"github.com/moby/go-archive"
"github.com/moby/go-archive/compression"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/fs"
"gotest.tools/v3/skip"
)
func TestRunCopyWithInvalidArguments(t *testing.T) {
@ -67,14 +67,15 @@ func TestRunCopyFromContainerToStdout(t *testing.T) {
}
func TestRunCopyFromContainerToFilesystem(t *testing.T) {
destDir := fs.NewDir(t, "cp-test",
srcDir := fs.NewDir(t, "cp-test",
fs.WithFile("file1", "content\n"))
defer destDir.Remove()
destDir := fs.NewDir(t, "cp-test")
cli := test.NewFakeCli(&fakeClient{
containerCopyFromFunc: func(ctr, srcPath string) (io.ReadCloser, container.PathStat, error) {
assert.Check(t, is.Equal("container", ctr))
readCloser, err := archive.TarWithOptions(destDir.Path(), &archive.TarOptions{})
readCloser, err := archive.Tar(srcDir.Path(), compression.None)
return readCloser, container.PathStat{}, err
},
})
@ -151,7 +152,7 @@ func TestSplitCpArg(t *testing.T) {
}{
{
doc: "absolute path with colon",
os: "linux",
os: "unix",
path: "/abs/path:withcolon",
expectedPath: "/abs/path:withcolon",
},
@ -178,13 +179,18 @@ func TestSplitCpArg(t *testing.T) {
expectedContainer: "container",
},
}
for _, testcase := range testcases {
t.Run(testcase.doc, func(t *testing.T) {
skip.If(t, testcase.os != "" && testcase.os != runtime.GOOS)
for _, tc := range testcases {
t.Run(tc.doc, func(t *testing.T) {
if tc.os == "windows" && runtime.GOOS != "windows" {
t.Skip("skipping windows test on non-windows platform")
}
if tc.os == "unix" && runtime.GOOS == "windows" {
t.Skip("skipping unix test on windows")
}
ctr, path := splitCpArg(testcase.path)
assert.Check(t, is.Equal(testcase.expectedContainer, ctr))
assert.Check(t, is.Equal(testcase.expectedPath, path))
ctr, path := splitCpArg(tc.path)
assert.Check(t, is.Equal(tc.expectedContainer, ctr))
assert.Check(t, is.Equal(tc.expectedPath, path))
})
}
}

View File

@ -1,26 +1,35 @@
package container
import (
"archive/tar"
"bytes"
"context"
"fmt"
"io"
"net/netip"
"os"
"regexp"
"path"
"strings"
cerrdefs "github.com/containerd/errdefs"
"github.com/containerd/platforms"
"github.com/distribution/reference"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/image"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/types"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/cli/trust"
"github.com/docker/cli/internal/jsonstream"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
imagetypes "github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/versions"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/pkg/jsonmessage"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/moby/moby/api/types/container"
imagetypes "github.com/moby/moby/api/types/image"
"github.com/moby/moby/api/types/mount"
"github.com/moby/moby/api/types/versions"
"github.com/moby/moby/client"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@ -34,11 +43,12 @@ const (
)
type createOptions struct {
name string
platform string
untrusted bool
pull string // always, missing, never
quiet bool
name string
platform string
untrusted bool
pull string // always, missing, never
quiet bool
useAPISocket bool
}
// NewCreateCommand creates a new cobra.Command for `docker create`
@ -60,7 +70,7 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
Annotations: map[string]string{
"aliases": "docker container create, docker create",
},
ValidArgsFunction: completion.ImageNames(dockerCli),
ValidArgsFunction: completion.ImageNames(dockerCli, -1),
}
flags := cmd.Flags()
@ -69,6 +79,8 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
flags.StringVar(&options.name, "name", "", "Assign a name to the container")
flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before creating ("`+PullImageAlways+`", "|`+PullImageMissing+`", "`+PullImageNever+`")`)
flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the pull output")
flags.BoolVarP(&options.useAPISocket, "use-api-socket", "", false, "Bind mount Docker API socket and required auth")
flags.SetAnnotation("use-api-socket", "experimentalCLI", nil) // Marks flag as experimental for now.
// Add an explicit help that doesn't have a `-h` to prevent the conflict
// with hostname
@ -77,15 +89,27 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
command.AddPlatformFlag(flags, &options.platform)
command.AddTrustVerificationFlags(flags, &options.untrusted, dockerCli.ContentTrustEnabled())
copts = addFlags(flags)
addCompletions(cmd, dockerCli)
flags.VisitAll(func(flag *pflag.Flag) {
// Set a default completion function if none was set. We don't look
// up if it does already have one set, because Cobra does this for
// us, and returns an error (which we ignore for this reason).
_ = cmd.RegisterFlagCompletionFunc(flag.Name, completion.NoComplete)
})
return cmd
}
func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error {
if err := validatePullOpt(options.pull); err != nil {
reportError(dockerCli.Err(), "create", err.Error(), true)
return cli.StatusError{StatusCode: 125}
return cli.StatusError{
Status: withHelp(err, "create").Error(),
StatusCode: 125,
}
}
proxyConfig := dockerCli.ConfigFile().ParseProxyConfig(dockerCli.Client().DaemonHost(), opts.ConvertKVStringsToMapWithNil(copts.env.GetAll()))
proxyConfig := dockerCli.ConfigFile().ParseProxyConfig(dockerCli.Client().DaemonHost(), opts.ConvertKVStringsToMapWithNil(copts.env.GetSlice()))
newEnv := []string{}
for k, v := range proxyConfig {
if v == nil {
@ -97,12 +121,10 @@ func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet,
copts.env = *opts.NewListOptsRef(&newEnv, nil)
containerCfg, err := parse(flags, copts, dockerCli.ServerInfo().OSType)
if err != nil {
reportError(dockerCli.Err(), "create", err.Error(), true)
return cli.StatusError{StatusCode: 125}
}
if err = validateAPIVersion(containerCfg, dockerCli.Client().ClientVersion()); err != nil {
reportError(dockerCli.Err(), "create", err.Error(), true)
return cli.StatusError{StatusCode: 125}
return cli.StatusError{
Status: withHelp(err, "create").Error(),
StatusCode: 125,
}
}
id, err := createContainer(ctx, dockerCli, containerCfg, options)
if err != nil {
@ -132,7 +154,7 @@ func pullImage(ctx context.Context, dockerCli command.Cli, img string, options *
if options.quiet {
out = streams.NewOut(io.Discard)
}
return jsonmessage.DisplayJSONMessagesToStream(responseBody, out, nil)
return jsonstream.Display(ctx, responseBody, out)
}
type cidFile struct {
@ -168,20 +190,20 @@ func (cid *cidFile) Write(id string) error {
return nil
}
func newCIDFile(path string) (*cidFile, error) {
if path == "" {
func newCIDFile(cidPath string) (*cidFile, error) {
if cidPath == "" {
return &cidFile{}, nil
}
if _, err := os.Stat(path); err == nil {
return nil, errors.Errorf("container ID file found, make sure the other container isn't running or delete %s", path)
if _, err := os.Stat(cidPath); err == nil {
return nil, errors.Errorf("container ID file found, make sure the other container isn't running or delete %s", cidPath)
}
f, err := os.Create(path)
f, err := os.Create(cidPath)
if err != nil {
return nil, errors.Wrap(err, "failed to create the container ID file")
}
return &cidFile{path: path, file: f}, nil
return &cidFile{path: cidPath, file: f}, nil
}
//nolint:gocyclo
@ -190,9 +212,6 @@ func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *c
hostConfig := containerCfg.HostConfig
networkingConfig := containerCfg.NetworkingConfig
warnOnOomKillDisable(*hostConfig, dockerCli.Err())
warnOnLocalhostDNS(*hostConfig, dockerCli.Err())
var (
trustedRef reference.Canonical
namedRef reference.Named
@ -221,17 +240,74 @@ func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *c
}
}
pullAndTagImage := func() error {
if err := pullImage(ctx, dockerCli, config.Image, options); err != nil {
return err
const dockerConfigPathInContainer = "/run/secrets/docker/config.json"
var apiSocketCreds map[string]types.AuthConfig
if options.useAPISocket {
// We'll create two new mounts to handle this flag:
// 1. Mount the actual docker socket.
// 2. A synthezised ~/.docker/config.json with resolved tokens.
if dockerCli.ServerInfo().OSType == "windows" {
return "", errors.New("flag --use-api-socket can't be used with a Windows Docker Engine")
}
if taggedRef, ok := namedRef.(reference.NamedTagged); ok && trustedRef != nil {
return image.TagTrusted(ctx, dockerCli, trustedRef, taggedRef)
// hard-code engine socket path until https://github.com/moby/moby/pull/43459 gives us a discovery mechanism
containerCfg.HostConfig.Mounts = append(containerCfg.HostConfig.Mounts, mount.Mount{
Type: mount.TypeBind,
Source: "/var/run/docker.sock",
Target: "/var/run/docker.sock",
BindOptions: &mount.BindOptions{},
})
/*
Ideally, we'd like to copy the config into a tmpfs but unfortunately,
the mounts won't be in place until we start the container. This can
leave around the config if the container doesn't get deleted.
We are using the most compose-secret-compatible approach,
which is implemented at
https://github.com/docker/compose/blob/main/pkg/compose/convergence.go#L737
// Prepare a tmpfs mount for our credentials so they go away after the
// container exits. We'll copy into this mount after the container is
// created.
containerCfg.HostConfig.Mounts = append(containerCfg.HostConfig.Mounts, mount.Mount{
Type: mount.TypeTmpfs,
Target: "/docker/",
TmpfsOptions: &mount.TmpfsOptions{
SizeBytes: 1 << 20, // only need a small partition
Mode: 0o600,
},
})
*/
var envvarPresent bool
for _, envvar := range containerCfg.Config.Env {
if strings.HasPrefix(envvar, "DOCKER_CONFIG=") {
envvarPresent = true
}
}
// If the DOCKER_CONFIG env var is already present, we assume the client knows
// what they're doing and don't inject the creds.
if !envvarPresent {
// Resolve this here for later, ensuring we error our before we create the container.
creds, err := readCredentials(dockerCli)
if err != nil {
return "", fmt.Errorf("resolving credentials failed: %w", err)
}
if len(creds) > 0 {
// Set our special little location for the config file.
containerCfg.Config.Env = append(containerCfg.Config.Env, "DOCKER_CONFIG="+path.Dir(dockerConfigPathInContainer))
apiSocketCreds = creds // inject these after container creation.
}
}
return nil
}
var platform *specs.Platform
var platform *ocispec.Platform
// Engine API version 1.41 first introduced the option to specify platform on
// create. It will produce an error if you try to set a platform on older API
// versions, so check the API version here to maintain backwards
@ -239,11 +315,21 @@ func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *c
if options.platform != "" && versions.GreaterThanOrEqualTo(dockerCli.Client().ClientVersion(), "1.41") {
p, err := platforms.Parse(options.platform)
if err != nil {
return "", errors.Wrap(errdefs.InvalidParameter(err), "error parsing specified platform")
return "", errors.Wrap(invalidParameter(err), "error parsing specified platform")
}
platform = &p
}
pullAndTagImage := func() error {
if err := pullImage(ctx, dockerCli, config.Image, options); err != nil {
return err
}
if taggedRef, ok := namedRef.(reference.NamedTagged); ok && trustedRef != nil {
return trust.TagTrusted(ctx, dockerCli.Client(), dockerCli.Err(), trustedRef, taggedRef)
}
return nil
}
if options.pull == PullImageAlways {
if err := pullAndTagImage(); err != nil {
return "", err
@ -255,10 +341,10 @@ func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *c
response, err := dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, platform, options.name)
if err != nil {
// Pull image if it does not exist locally and we have the PullImageMissing option. Default behavior.
if errdefs.IsNotFound(err) && namedRef != nil && options.pull == PullImageMissing {
if cerrdefs.IsNotFound(err) && namedRef != nil && options.pull == PullImageMissing {
if !options.quiet {
// we don't want to write to stdout anything apart from container.ID
fmt.Fprintf(dockerCli.Err(), "Unable to find image '%s' locally\n", reference.FamiliarString(namedRef))
_, _ = fmt.Fprintf(dockerCli.Err(), "Unable to find image '%s' locally\n", reference.FamiliarString(namedRef))
}
if err := pullAndTagImage(); err != nil {
@ -275,40 +361,41 @@ func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *c
}
}
for _, w := range response.Warnings {
_, _ = fmt.Fprintf(dockerCli.Err(), "WARNING: %s\n", w)
if warn := localhostDNSWarning(*hostConfig); warn != "" {
response.Warnings = append(response.Warnings, warn)
}
err = containerIDFile.Write(response.ID)
return response.ID, err
}
func warnOnOomKillDisable(hostConfig container.HostConfig, stderr io.Writer) {
if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
fmt.Fprintln(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.")
containerID = response.ID
for _, w := range response.Warnings {
_, _ = fmt.Fprintln(dockerCli.Err(), "WARNING:", w)
}
err = containerIDFile.Write(containerID)
if options.useAPISocket && len(apiSocketCreds) > 0 {
// Create a new config file with just the auth.
newConfig := &configfile.ConfigFile{
AuthConfigs: apiSocketCreds,
}
if err := copyDockerConfigIntoContainer(ctx, dockerCli.Client(), containerID, dockerConfigPathInContainer, newConfig); err != nil {
return "", fmt.Errorf("injecting docker config.json into container failed: %w", err)
}
}
return containerID, err
}
// check the DNS settings passed via --dns against localhost regexp to warn if
// they are trying to set a DNS to a localhost address
func warnOnLocalhostDNS(hostConfig container.HostConfig, stderr io.Writer) {
// they are trying to set a DNS to a localhost address.
//
// TODO(thaJeztah): move this to the daemon, which can make a better call if it will work or not (depending on networking mode).
func localhostDNSWarning(hostConfig container.HostConfig) string {
for _, dnsIP := range hostConfig.DNS {
if isLocalhost(dnsIP) {
fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
return
if addr, err := netip.ParseAddr(dnsIP); err == nil && addr.IsLoopback() {
return fmt.Sprintf("Localhost DNS (%s) may fail in containers.", addr)
}
}
}
// IPLocalhost is a regex pattern for IPv4 or IPv6 loopback range.
const ipLocalhost = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1)$)`
var localhostIPRegexp = regexp.MustCompile(ipLocalhost)
// IsLocalhost returns true if ip matches the localhost IP regular expression.
// Used for determining if nameserver settings are being passed which are
// localhost addresses
func isLocalhost(ip string) bool {
return localhostIPRegexp.MatchString(ip)
return ""
}
func validatePullOpt(val string) error {
@ -326,3 +413,39 @@ func validatePullOpt(val string) error {
)
}
}
// copyDockerConfigIntoContainer takes the client configuration and copies it
// into the container.
//
// The path should be an absolute path in the container, commonly
// /root/.docker/config.json.
func copyDockerConfigIntoContainer(ctx context.Context, dockerAPI client.APIClient, containerID string, configPath string, config *configfile.ConfigFile) error {
var configBuf bytes.Buffer
if err := config.SaveToWriter(&configBuf); err != nil {
return fmt.Errorf("saving creds: %w", err)
}
// We don't need to get super fancy with the tar creation.
var tarBuf bytes.Buffer
tarWriter := tar.NewWriter(&tarBuf)
tarWriter.WriteHeader(&tar.Header{
Name: configPath,
Size: int64(configBuf.Len()),
Mode: 0o600,
})
if _, err := io.Copy(tarWriter, &configBuf); err != nil {
return fmt.Errorf("writing config to tar file for config copy: %w", err)
}
if err := tarWriter.Close(); err != nil {
return fmt.Errorf("closing tar for config copy failed: %w", err)
}
if err := dockerAPI.CopyToContainer(ctx, containerID, "/",
&tarBuf, container.CopyToContainerOptions{}); err != nil {
return fmt.Errorf("copying config.json into container failed: %w", err)
}
return nil
}

View File

@ -14,12 +14,12 @@ import (
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/internal/test/notary"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/system"
"github.com/google/go-cmp/cmp"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/system"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/spf13/pflag"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
@ -113,7 +113,6 @@ func TestCreateContainerImagePullPolicy(t *testing.T) {
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.PullPolicy, func(t *testing.T) {
pullCounter := 0
@ -122,7 +121,7 @@ func TestCreateContainerImagePullPolicy(t *testing.T) {
config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *specs.Platform,
platform *ocispec.Platform,
containerName string,
) (container.CreateResponse, error) {
defer func() { tc.ResponseCounter++ }()
@ -133,7 +132,7 @@ func TestCreateContainerImagePullPolicy(t *testing.T) {
return container.CreateResponse{ID: containerID}, nil
}
},
imageCreateFunc: func(parentReference string, options image.CreateOptions) (io.ReadCloser, error) {
imageCreateFunc: func(ctx context.Context, parentReference string, options image.CreateOptions) (io.ReadCloser, error) {
defer func() { pullCounter++ }()
return io.NopCloser(strings.NewReader("")), nil
},
@ -176,7 +175,6 @@ func TestCreateContainerImagePullPolicyInvalid(t *testing.T) {
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.PullPolicy, func(t *testing.T) {
dockerCli := test.NewFakeCli(&fakeClient{})
err := runCreate(
@ -189,8 +187,36 @@ func TestCreateContainerImagePullPolicyInvalid(t *testing.T) {
statusErr := cli.StatusError{}
assert.Check(t, errors.As(err, &statusErr))
assert.Equal(t, statusErr.StatusCode, 125)
assert.Check(t, is.Contains(dockerCli.ErrBuffer().String(), tc.ExpectedErrMsg))
assert.Check(t, is.Equal(statusErr.StatusCode, 125))
assert.Check(t, is.ErrorContains(err, tc.ExpectedErrMsg))
})
}
}
func TestCreateContainerValidateFlags(t *testing.T) {
for _, tc := range []struct {
name string
args []string
expectedErr string
}{
{
name: "with invalid --attach value",
args: []string{"--attach", "STDINFO", "myimage"},
expectedErr: `invalid argument "STDINFO" for "-a, --attach" flag: valid streams are STDIN, STDOUT and STDERR`,
},
} {
t.Run(tc.name, func(t *testing.T) {
cmd := NewCreateCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)
err := cmd.Execute()
if tc.expectedErr != "" {
assert.Check(t, is.ErrorContains(err, tc.expectedErr))
} else {
assert.Check(t, is.Nil(err))
}
})
}
}
@ -222,53 +248,48 @@ func TestNewCreateCommandWithContentTrustErrors(t *testing.T) {
},
}
for _, tc := range testCases {
tc := tc
fakeCLI := test.NewFakeCli(&fakeClient{
createContainerFunc: func(config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *specs.Platform,
containerName string,
) (container.CreateResponse, error) {
return container.CreateResponse{}, errors.New("shouldn't try to pull image")
},
}, test.EnableContentTrust)
fakeCLI.SetNotaryClient(tc.notaryFunc)
cmd := NewCreateCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args)
err := cmd.Execute()
assert.ErrorContains(t, err, tc.expectedError)
t.Run(tc.name, func(t *testing.T) {
fakeCLI := test.NewFakeCli(&fakeClient{
createContainerFunc: func(config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *ocispec.Platform,
containerName string,
) (container.CreateResponse, error) {
return container.CreateResponse{}, errors.New("shouldn't try to pull image")
},
}, test.EnableContentTrust)
fakeCLI.SetNotaryClient(tc.notaryFunc)
cmd := NewCreateCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)
err := cmd.Execute()
assert.ErrorContains(t, err, tc.expectedError)
})
}
}
func TestNewCreateCommandWithWarnings(t *testing.T) {
testCases := []struct {
name string
args []string
warning bool
name string
args []string
warnings []string
warning bool
}{
{
name: "container-create-without-oom-kill-disable",
name: "container-create-no-warnings",
args: []string{"image:tag"},
},
{
name: "container-create-oom-kill-disable-false",
args: []string{"--oom-kill-disable=false", "image:tag"},
name: "container-create-daemon-single-warning",
args: []string{"image:tag"},
warnings: []string{"warning from daemon"},
},
{
name: "container-create-oom-kill-without-memory-limit",
args: []string{"--oom-kill-disable", "image:tag"},
warning: true,
},
{
name: "container-create-oom-kill-true-without-memory-limit",
args: []string{"--oom-kill-disable=true", "image:tag"},
warning: true,
},
{
name: "container-create-oom-kill-true-with-memory-limit",
args: []string{"--oom-kill-disable=true", "--memory=100M", "image:tag"},
name: "container-create-daemon-multiple-warnings",
args: []string{"image:tag"},
warnings: []string{"warning from daemon", "another warning from daemon"},
},
{
name: "container-create-localhost-dns",
@ -282,27 +303,26 @@ func TestNewCreateCommandWithWarnings(t *testing.T) {
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
fakeCLI := test.NewFakeCli(&fakeClient{
createContainerFunc: func(config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *specs.Platform,
platform *ocispec.Platform,
containerName string,
) (container.CreateResponse, error) {
return container.CreateResponse{}, nil
return container.CreateResponse{Warnings: tc.warnings}, nil
},
})
cmd := NewCreateCommand(cli)
cmd := NewCreateCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args)
err := cmd.Execute()
assert.NilError(t, err)
if tc.warning {
golden.Assert(t, cli.ErrBuffer().String(), tc.name+".golden")
if tc.warning || len(tc.warnings) > 0 {
golden.Assert(t, fakeCLI.ErrBuffer().String(), tc.name+".golden")
} else {
assert.Equal(t, cli.ErrBuffer().String(), "")
assert.Equal(t, fakeCLI.ErrBuffer().String(), "")
}
})
}
@ -327,7 +347,7 @@ func TestCreateContainerWithProxyConfig(t *testing.T) {
createContainerFunc: func(config *container.Config,
hostConfig *container.HostConfig,
networkingConfig *network.NetworkingConfig,
platform *specs.Platform,
platform *ocispec.Platform,
containerName string,
) (container.CreateResponse, error) {
sort.Strings(config.Env)
@ -355,5 +375,5 @@ func TestCreateContainerWithProxyConfig(t *testing.T) {
type fakeNotFound struct{}
func (f fakeNotFound) NotFound() {}
func (f fakeNotFound) Error() string { return "error fake not found" }
func (fakeNotFound) NotFound() {}
func (fakeNotFound) Error() string { return "error fake not found" }

View File

@ -7,25 +7,17 @@ import (
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/formatter"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
type diffOptions struct {
container string
}
// NewDiffCommand creates a new cobra.Command for `docker diff`
func NewDiffCommand(dockerCli command.Cli) *cobra.Command {
var opts diffOptions
return &cobra.Command{
Use: "diff CONTAINER",
Short: "Inspect changes to files or directories on a container's filesystem",
Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0]
return runDiff(cmd.Context(), dockerCli, &opts)
return runDiff(cmd.Context(), dockerCli, args[0])
},
Annotations: map[string]string{
"aliases": "docker container diff, docker diff",
@ -34,17 +26,14 @@ func NewDiffCommand(dockerCli command.Cli) *cobra.Command {
}
}
func runDiff(ctx context.Context, dockerCli command.Cli, opts *diffOptions) error {
if opts.container == "" {
return errors.New("Container name cannot be empty")
}
changes, err := dockerCli.Client().ContainerDiff(ctx, opts.container)
func runDiff(ctx context.Context, dockerCLI command.Cli, containerID string) error {
changes, err := dockerCLI.Client().ContainerDiff(ctx, containerID)
if err != nil {
return err
}
diffCtx := formatter.Context{
Output: dockerCli.Out(),
Format: NewDiffFormat("{{.Type}} {{.Path}}"),
Output: dockerCLI.Out(),
Format: newDiffFormat("{{.Type}} {{.Path}}"),
}
return DiffFormatWrite(diffCtx, changes)
return diffFormatWrite(diffCtx, changes)
}

View File

@ -0,0 +1,79 @@
package container
import (
"context"
"errors"
"io"
"strings"
"testing"
"github.com/docker/cli/internal/test"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestRunDiff(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
containerDiffFunc: func(
ctx context.Context,
containerID string,
) ([]container.FilesystemChange, error) {
return []container.FilesystemChange{
{
Kind: container.ChangeModify,
Path: "/path/to/file0",
},
{
Kind: container.ChangeAdd,
Path: "/path/to/file1",
},
{
Kind: container.ChangeDelete,
Path: "/path/to/file2",
},
}, nil
},
})
cmd := NewDiffCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"container-id"})
err := cmd.Execute()
assert.NilError(t, err)
diff := strings.SplitN(cli.OutBuffer().String(), "\n", 3)
assert.Assert(t, is.Len(diff, 3))
file0 := strings.TrimSpace(diff[0])
file1 := strings.TrimSpace(diff[1])
file2 := strings.TrimSpace(diff[2])
assert.Check(t, is.Equal(file0, "C /path/to/file0"))
assert.Check(t, is.Equal(file1, "A /path/to/file1"))
assert.Check(t, is.Equal(file2, "D /path/to/file2"))
}
func TestRunDiffClientError(t *testing.T) {
clientError := errors.New("client error")
cli := test.NewFakeCli(&fakeClient{
containerDiffFunc: func(
ctx context.Context,
containerID string,
) ([]container.FilesystemChange, error) {
return nil, clientError
},
})
cmd := NewDiffCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"container-id"})
err := cmd.Execute()
assert.ErrorIs(t, err, clientError)
}

View File

@ -0,0 +1,31 @@
package container
import cerrdefs "github.com/containerd/errdefs"
func invalidParameter(err error) error {
if err == nil || cerrdefs.IsInvalidArgument(err) {
return err
}
return invalidParameterErr{err}
}
type invalidParameterErr struct{ error }
func (invalidParameterErr) InvalidParameter() {}
func (e invalidParameterErr) Unwrap() error {
return e.error
}
func notFound(err error) error {
if err == nil || cerrdefs.IsNotFound(err) {
return err
}
return notFoundErr{err}
}
type notFoundErr struct{ error }
func (notFoundErr) NotFound() {}
func (e notFoundErr) Unwrap() error {
return e.error
}

View File

@ -4,16 +4,14 @@ import (
"context"
"fmt"
"io"
"os"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@ -54,8 +52,8 @@ func NewExecCommand(dockerCli command.Cli) *cobra.Command {
options.Command = args[1:]
return RunExec(cmd.Context(), dockerCli, containerIDorName, options)
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(ctr types.Container) bool {
return ctr.State != "paused"
ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(ctr container.Summary) bool {
return ctr.State != container.StatePaused
}),
Annotations: map[string]string{
"category-top": "2",
@ -79,24 +77,20 @@ func NewExecCommand(dockerCli command.Cli) *cobra.Command {
flags.StringVarP(&options.Workdir, "workdir", "w", "", "Working directory inside the container")
flags.SetAnnotation("workdir", "version", []string{"1.35"})
_ = cmd.RegisterFlagCompletionFunc("env", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
return os.Environ(), cobra.ShellCompDirectiveNoFileComp
})
_ = cmd.RegisterFlagCompletionFunc("env-file", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveDefault // _filedir
})
_ = cmd.RegisterFlagCompletionFunc("env", completion.EnvVarNames)
_ = cmd.RegisterFlagCompletionFunc("env-file", completion.FileNames)
return cmd
}
// RunExec executes an `exec` command
func RunExec(ctx context.Context, dockerCli command.Cli, containerIDorName string, options ExecOptions) error {
execOptions, err := parseExec(options, dockerCli.ConfigFile())
func RunExec(ctx context.Context, dockerCLI command.Cli, containerIDorName string, options ExecOptions) error {
execOptions, err := parseExec(options, dockerCLI.ConfigFile())
if err != nil {
return err
}
apiClient := dockerCli.Client()
apiClient := dockerCLI.Client()
// We need to check the tty _before_ we do the ContainerExecCreate, because
// otherwise if we error out we will leak execIDs on the server (and
@ -105,13 +99,13 @@ func RunExec(ctx context.Context, dockerCli command.Cli, containerIDorName strin
if _, err := apiClient.ContainerInspect(ctx, containerIDorName); err != nil {
return err
}
if !execOptions.Detach {
if err := dockerCli.In().CheckTty(execOptions.AttachStdin, execOptions.Tty); err != nil {
if !options.Detach {
if err := dockerCLI.In().CheckTty(execOptions.AttachStdin, execOptions.Tty); err != nil {
return err
}
}
fillConsoleSize(execOptions, dockerCli)
fillConsoleSize(execOptions, dockerCLI)
response, err := apiClient.ContainerExecCreate(ctx, containerIDorName, *execOptions)
if err != nil {
@ -123,14 +117,14 @@ func RunExec(ctx context.Context, dockerCli command.Cli, containerIDorName strin
return errors.New("exec ID empty")
}
if execOptions.Detach {
if options.Detach {
return apiClient.ContainerExecStart(ctx, execID, container.ExecStartOptions{
Detach: execOptions.Detach,
Detach: options.Detach,
Tty: execOptions.Tty,
ConsoleSize: execOptions.ConsoleSize,
})
}
return interactiveExec(ctx, dockerCli, execOptions, execID)
return interactiveExec(ctx, dockerCLI, execOptions, execID)
}
func fillConsoleSize(execOptions *container.ExecOptions, dockerCli command.Cli) {
@ -229,13 +223,12 @@ func parseExec(execOpts ExecOptions, configFile *configfile.ConfigFile) (*contai
Privileged: execOpts.Privileged,
Tty: execOpts.TTY,
Cmd: execOpts.Command,
Detach: execOpts.Detach,
WorkingDir: execOpts.Workdir,
}
// collect all the environment variables for the container
var err error
if execOptions.Env, err = opts.ReadKVEnvStrings(execOpts.EnvFile.GetAll(), execOpts.Env.GetAll()); err != nil {
if execOptions.Env, err = opts.ReadKVEnvStrings(execOpts.EnvFile.GetSlice(), execOpts.Env.GetSlice()); err != nil {
return nil, err
}

View File

@ -2,17 +2,17 @@ package container
import (
"context"
"errors"
"io"
"os"
"strconv"
"testing"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal/test"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/pkg/errors"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/fs"
@ -76,8 +76,7 @@ TWO=2
{
options: withDefaultOpts(ExecOptions{Detach: true}),
expected: container.ExecOptions{
Detach: true,
Cmd: []string{"command"},
Cmd: []string{"command"},
},
},
{
@ -87,9 +86,8 @@ TWO=2
Detach: true,
}),
expected: container.ExecOptions{
Detach: true,
Tty: true,
Cmd: []string{"command"},
Tty: true,
Cmd: []string{"command"},
},
},
{
@ -98,7 +96,6 @@ TWO=2
expected: container.ExecOptions{
Cmd: []string{"command"},
DetachKeys: "de",
Detach: true,
},
},
{
@ -110,7 +107,6 @@ TWO=2
expected: container.ExecOptions{
Cmd: []string{"command"},
DetachKeys: "ab",
Detach: true,
},
},
{
@ -142,10 +138,12 @@ TWO=2
},
}
for _, testcase := range testcases {
execConfig, err := parseExec(testcase.options, &testcase.configFile)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(testcase.expected, *execConfig))
for i, testcase := range testcases {
t.Run("test "+strconv.Itoa(i+1), func(t *testing.T) {
execConfig, err := parseExec(testcase.options, &testcase.configFile)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(testcase.expected, *execConfig))
})
}
}
@ -178,8 +176,8 @@ func TestRunExec(t *testing.T) {
doc: "inspect error",
options: NewExecOptions(),
client: &fakeClient{
inspectFunc: func(string) (types.ContainerJSON, error) {
return types.ContainerJSON{}, errors.New("failed inspect")
inspectFunc: func(string) (container.InspectResponse, error) {
return container.InspectResponse{}, errors.New("failed inspect")
},
},
expectedError: "failed inspect",
@ -208,8 +206,8 @@ func TestRunExec(t *testing.T) {
}
}
func execCreateWithID(_ string, _ container.ExecOptions) (types.IDResponse, error) {
return types.IDResponse{ID: "execid"}, nil
func execCreateWithID(_ string, _ container.ExecOptions) (container.ExecCreateResponse, error) {
return container.ExecCreateResponse{ID: "execid"}, nil
}
func TestGetExecExitStatus(t *testing.T) {
@ -252,14 +250,14 @@ func TestNewExecCommandErrors(t *testing.T) {
name string
args []string
expectedError string
containerInspectFunc func(img string) (types.ContainerJSON, error)
containerInspectFunc func(img string) (container.InspectResponse, error)
}{
{
name: "client-error",
args: []string{"5cb5bb5e4a3b", "-t", "-i", "bash"},
expectedError: "something went wrong",
containerInspectFunc: func(containerID string) (types.ContainerJSON, error) {
return types.ContainerJSON{}, errors.Errorf("something went wrong")
containerInspectFunc: func(containerID string) (container.InspectResponse, error) {
return container.InspectResponse{}, errors.New("something went wrong")
},
},
}

View File

@ -7,6 +7,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/moby/sys/atomicwriter"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
@ -41,27 +42,28 @@ func NewExportCommand(dockerCli command.Cli) *cobra.Command {
return cmd
}
func runExport(ctx context.Context, dockerCli command.Cli, opts exportOptions) error {
if opts.output == "" && dockerCli.Out().IsTerminal() {
return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect")
func runExport(ctx context.Context, dockerCLI command.Cli, opts exportOptions) error {
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")
}
output = dockerCLI.Out()
} else {
writer, err := atomicwriter.New(opts.output, 0o600)
if err != nil {
return errors.Wrap(err, "failed to export container")
}
defer writer.Close()
output = writer
}
if err := command.ValidateOutputPath(opts.output); err != nil {
return errors.Wrap(err, "failed to export container")
}
clnt := dockerCli.Client()
responseBody, err := clnt.ContainerExport(ctx, opts.container)
responseBody, err := dockerCLI.Client().ContainerExport(ctx, opts.container)
if err != nil {
return err
}
defer responseBody.Close()
if opts.output == "" {
_, err := io.Copy(dockerCli.Out(), responseBody)
return err
}
return command.CopyToFile(opts.output, responseBody)
_, err = io.Copy(output, responseBody)
return err
}

View File

@ -39,10 +39,9 @@ func TestContainerExportOutputToIrregularFile(t *testing.T) {
})
cmd := NewExportCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"-o", "/dev/random", "container"})
err := cmd.Execute()
assert.Assert(t, err != nil)
expected := `"/dev/random" must be a directory or a regular file`
assert.ErrorContains(t, err, expected)
const expected = `failed to export container: cannot write to a character device file`
assert.Error(t, cmd.Execute(), expected)
}

View File

@ -2,7 +2,7 @@ package container
import (
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types/container"
"github.com/moby/moby/api/types/container"
)
const (
@ -13,7 +13,14 @@ const (
)
// NewDiffFormat returns a format for use with a diff Context
//
// Deprecated: this function was only used internally and will be removed in the next release.
func NewDiffFormat(source string) formatter.Format {
return newDiffFormat(source)
}
// newDiffFormat returns a format for use with a diff [formatter.Context].
func newDiffFormat(source string) formatter.Format {
if source == formatter.TableFormatKey {
return defaultDiffTableFormat
}
@ -21,16 +28,22 @@ func NewDiffFormat(source string) formatter.Format {
}
// DiffFormatWrite writes formatted diff using the Context
func DiffFormatWrite(ctx formatter.Context, changes []container.FilesystemChange) error {
render := func(format func(subContext formatter.SubContext) error) error {
//
// Deprecated: this function was only used internally and will be removed in the next release.
func DiffFormatWrite(fmtCtx formatter.Context, changes []container.FilesystemChange) error {
return diffFormatWrite(fmtCtx, changes)
}
// diffFormatWrite writes formatted diff using the [formatter.Context].
func diffFormatWrite(fmtCtx formatter.Context, changes []container.FilesystemChange) error {
return fmtCtx.Write(newDiffContext(), func(format func(subContext formatter.SubContext) error) error {
for _, change := range changes {
if err := format(&diffContext{c: change}); err != nil {
return err
}
}
return nil
}
return ctx.Write(newDiffContext(), render)
})
}
type diffContext struct {
@ -39,12 +52,14 @@ type diffContext struct {
}
func newDiffContext() *diffContext {
diffCtx := diffContext{}
diffCtx.Header = formatter.SubHeaderContext{
"Type": changeTypeHeader,
"Path": pathHeader,
return &diffContext{
HeaderContext: formatter.HeaderContext{
Header: formatter.SubHeaderContext{
"Type": changeTypeHeader,
"Path": pathHeader,
},
},
}
return &diffCtx
}
func (d *diffContext) MarshalJSON() ([]byte, error) {

View File

@ -5,7 +5,7 @@ import (
"testing"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/api/types/container"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
)
@ -16,7 +16,7 @@ func TestDiffContextFormatWrite(t *testing.T) {
expected string
}{
{
formatter.Context{Format: NewDiffFormat("table")},
formatter.Context{Format: newDiffFormat("table")},
`CHANGE TYPE PATH
C /var/log/app.log
A /usr/app/app.js
@ -24,7 +24,7 @@ D /usr/app/old_app.js
`,
},
{
formatter.Context{Format: NewDiffFormat("table {{.Path}}")},
formatter.Context{Format: newDiffFormat("table {{.Path}}")},
`PATH
/var/log/app.log
/usr/app/app.js
@ -32,7 +32,7 @@ D /usr/app/old_app.js
`,
},
{
formatter.Context{Format: NewDiffFormat("{{.Type}}: {{.Path}}")},
formatter.Context{Format: newDiffFormat("{{.Type}}: {{.Path}}")},
`C: /var/log/app.log
A: /usr/app/app.js
D: /usr/app/old_app.js
@ -47,11 +47,10 @@ D: /usr/app/old_app.js
}
for _, tc := range cases {
tc := tc
t.Run(string(tc.context.Format), func(t *testing.T) {
out := bytes.NewBufferString("")
tc.context.Output = out
err := DiffFormatWrite(tc.context, diffs)
err := diffFormatWrite(tc.context, diffs)
if err != nil {
assert.Error(t, err, tc.expected)
} else {

View File

@ -5,8 +5,7 @@ import (
"sync"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/pkg/stringid"
units "github.com/docker/go-units"
"github.com/docker/go-units"
)
const (
@ -22,6 +21,8 @@ const (
winMemUseHeader = "PRIV WORKING SET" // Used only on Windows
memUseHeader = "MEM USAGE / LIMIT" // Used only on Linux
pidsHeader = "PIDS" // Used only on Linux
noValue = "--"
)
// StatsEntry represents the statistics data collected from a container
@ -169,19 +170,19 @@ func (c *statsContext) Name() string {
if len(c.s.Name) > 1 {
return c.s.Name[1:]
}
return "--"
return noValue
}
func (c *statsContext) ID() string {
if c.trunc {
return stringid.TruncateID(c.s.ID)
return formatter.TruncateID(c.s.ID)
}
return c.s.ID
}
func (c *statsContext) CPUPerc() string {
if c.s.IsInvalid {
return "--"
return noValue
}
return formatPercentage(c.s.CPUPercentage)
}
@ -198,28 +199,28 @@ func (c *statsContext) MemUsage() string {
func (c *statsContext) MemPerc() string {
if c.s.IsInvalid || c.os == winOSType {
return "--"
return noValue
}
return formatPercentage(c.s.MemoryPercentage)
}
func (c *statsContext) NetIO() string {
if c.s.IsInvalid {
return "--"
return noValue
}
return units.HumanSizeWithPrecision(c.s.NetworkRx, 3) + " / " + units.HumanSizeWithPrecision(c.s.NetworkTx, 3)
}
func (c *statsContext) BlockIO() string {
if c.s.IsInvalid {
return "--"
return noValue
}
return units.HumanSizeWithPrecision(c.s.BlockRead, 3) + " / " + units.HumanSizeWithPrecision(c.s.BlockWrite, 3)
}
func (c *statsContext) PIDs() string {
if c.s.IsInvalid || c.os == winOSType {
return "--"
return noValue
}
return strconv.FormatUint(c.s.PidsCurrent, 10)
}

View File

@ -5,13 +5,13 @@ import (
"testing"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/cli/internal/test"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestContainerStatsContext(t *testing.T) {
containerID := stringid.GenerateRandomID()
containerID := test.RandomID()
var ctx statsContext
tt := []struct {
@ -148,7 +148,7 @@ container2 -- --
`,
},
}
stats := []StatsEntry{
entries := []StatsEntry{
{
Container: "container1",
CPUPercentage: 20,
@ -178,11 +178,10 @@ container2 -- --
}
for _, tc := range cases {
tc := tc
t.Run(string(tc.context.Format), func(t *testing.T) {
var out bytes.Buffer
tc.context.Output = &out
err := statsFormatWrite(tc.context, stats, "windows", false)
err := statsFormatWrite(tc.context, entries, "windows", false)
if err != nil {
assert.Error(t, err, tc.expected)
} else {
@ -223,7 +222,6 @@ func TestContainerStatsContextWriteWithNoStats(t *testing.T) {
}
for _, tc := range cases {
tc := tc
t.Run(string(tc.context.Format), func(t *testing.T) {
err := statsFormatWrite(tc.context, []StatsEntry{}, "linux", false)
assert.NilError(t, err)
@ -265,7 +263,6 @@ func TestContainerStatsContextWriteWithNoStatsWindows(t *testing.T) {
}
for _, tc := range cases {
tc := tc
t.Run(string(tc.context.Format), func(t *testing.T) {
err := statsFormatWrite(tc.context, []StatsEntry{}, "windows", false)
assert.NilError(t, err)
@ -276,45 +273,46 @@ func TestContainerStatsContextWriteWithNoStatsWindows(t *testing.T) {
}
func TestContainerStatsContextWriteTrunc(t *testing.T) {
var out bytes.Buffer
contexts := []struct {
tests := []struct {
doc string
context formatter.Context
trunc bool
expected string
}{
{
formatter.Context{
doc: "non-truncated",
context: formatter.Context{
Format: "{{.ID}}",
Output: &out,
},
false,
"b95a83497c9161c9b444e3d70e1a9dfba0c1840d41720e146a95a08ebf938afc\n",
expected: "b95a83497c9161c9b444e3d70e1a9dfba0c1840d41720e146a95a08ebf938afc\n",
},
{
formatter.Context{
doc: "truncated",
context: formatter.Context{
Format: "{{.ID}}",
Output: &out,
},
true,
"b95a83497c91\n",
trunc: true,
expected: "b95a83497c91\n",
},
}
for _, context := range contexts {
statsFormatWrite(context.context, []StatsEntry{{ID: "b95a83497c9161c9b444e3d70e1a9dfba0c1840d41720e146a95a08ebf938afc"}}, "linux", context.trunc)
assert.Check(t, is.Equal(context.expected, out.String()))
// Clean buffer
out.Reset()
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
var out bytes.Buffer
tc.context.Output = &out
err := statsFormatWrite(tc.context, []StatsEntry{{ID: "b95a83497c9161c9b444e3d70e1a9dfba0c1840d41720e146a95a08ebf938afc"}}, "linux", tc.trunc)
assert.NilError(t, err)
assert.Check(t, is.Equal(tc.expected, out.String()))
})
}
}
func BenchmarkStatsFormat(b *testing.B) {
b.ReportAllocs()
stats := genStats()
entries := genStats()
for i := 0; i < b.N; i++ {
for _, s := range stats {
for _, s := range entries {
_ = s.CPUPerc()
_ = s.MemUsage()
_ = s.MemPerc()
@ -337,9 +335,9 @@ func genStats() []statsContext {
NetworkTx: 987.654321,
PidsCurrent: 123456789,
}}
stats := make([]statsContext, 100)
for i := 0; i < 100; i++ {
stats = append(stats, entry)
entries := make([]statsContext, 0, 100)
for range 100 {
entries = append(entries, entry)
}
return stats
return entries
}

View File

@ -8,9 +8,8 @@ import (
"sync"
"github.com/docker/cli/cli/command"
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/stdcopy"
"github.com/moby/moby/api/stdcopy"
"github.com/moby/moby/api/types"
"github.com/moby/term"
"github.com/sirupsen/logrus"
)
@ -19,6 +18,18 @@ import (
// TODO: This could be moved to `pkg/term`.
var defaultEscapeKeys = []byte{16, 17}
// readCloserWrapper wraps an io.Reader, and implements an io.ReadCloser
// It calls the given callback function when closed.
type readCloserWrapper struct {
io.Reader
closer func() error
}
// Close calls back the passed closer function
func (r *readCloserWrapper) Close() error {
return r.closer()
}
// A hijackedIOStreamer handles copying input to and output from streams to the
// connection.
type hijackedIOStreamer struct {
@ -84,12 +95,9 @@ func (h *hijackedIOStreamer) setupInput() (restore func(), err error) {
// Use sync.Once so we may call restore multiple times but ensure we
// only restore the terminal once.
var restoreOnce sync.Once
restore = func() {
restoreOnce.Do(func() {
_ = restoreTerminal(h.streams, h.inputStream)
})
}
restore = sync.OnceFunc(func() {
_ = restoreTerminal(h.streams, h.inputStream)
})
// Wrap the input to detect detach escape sequence.
// Use default escape keys if an invalid sequence is given.
@ -103,7 +111,10 @@ func (h *hijackedIOStreamer) setupInput() (restore func(), err error) {
}
}
h.inputStream = ioutils.NewReadCloserWrapper(term.NewEscapeProxy(h.inputStream, escapeKeys), h.inputStream.Close)
h.inputStream = &readCloserWrapper{
Reader: term.NewEscapeProxy(h.inputStream, escapeKeys),
closer: h.inputStream.Close,
}
return restore, nil
}

View File

@ -1,5 +1,5 @@
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.21
//go:build go1.23
package container
@ -42,11 +42,9 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd
}
func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client()
getRefFunc := func(ref string) (any, []byte, error) {
return client.ContainerInspectWithRaw(ctx, ref, opts.size)
}
return inspect.Inspect(dockerCli.Out(), opts.refs, opts.format, getRefFunc)
func runInspect(ctx context.Context, dockerCLI command.Cli, opts inspectOptions) error {
apiClient := dockerCLI.Client()
return inspect.Inspect(dockerCLI.Out(), opts.refs, opts.format, func(ref string) (any, []byte, error) {
return apiClient.ContainerInspectWithRaw(ctx, ref, opts.size)
})
}

View File

@ -2,13 +2,12 @@ package container
import (
"context"
"errors"
"fmt"
"strings"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
@ -38,23 +37,25 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command {
flags := cmd.Flags()
flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container")
_ = cmd.RegisterFlagCompletionFunc("signal", completeSignals)
return cmd
}
func runKill(ctx context.Context, dockerCli command.Cli, opts *killOptions) error {
var errs []string
func runKill(ctx context.Context, dockerCLI command.Cli, opts *killOptions) error {
apiClient := dockerCLI.Client()
errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
return dockerCli.Client().ContainerKill(ctx, container, opts.signal)
return apiClient.ContainerKill(ctx, container, opts.signal)
})
var errs []error
for _, name := range opts.containers {
if err := <-errChan; err != nil {
errs = append(errs, err.Error())
} else {
fmt.Fprintln(dockerCli.Out(), name)
errs = append(errs, err)
continue
}
_, _ = fmt.Fprintln(dockerCLI.Out(), name)
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
return errors.Join(errs...)
}

Some files were not shown because too many files have changed in this diff Show More