Compare commits

...

293 Commits

Author SHA1 Message Date
ecc694264d Merge pull request #6621 from thaJeztah/28.x_plugin_hide
Some checks failed
build / prepare (push) Has been cancelled
build / build (push) Has been cancelled
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 25, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 25, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
test / host (macos-15) (push) Has been cancelled
test / host (macos-15-intel) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x backport] Plugin may set itself as hidden
2025-11-05 11:32:31 +01:00
c475c696cf Plugin may set itself as hidden
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 700875b666)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-05 07:33:23 +01:00
7494d2cee4 cli: allManagementSubCommands: improve handling of plugin stubs
The allManagementSubCommands function is used to present plugin-commands
in the docker --help output; these commands are included in the "management
commands" section, but for plugins we don't know if they have sub-commands.

However, plugin stubs may be hidden (for placeholders that are not yet loaded),
or not be runnable, which was previously ignored.

This patch treats plugin-stubs the same as other commands, with the exception
of checking if they have subcommands (which is not yet known for plugin-stubs).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 259df25a96)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-05 07:33:08 +01:00
5306df36fa Merge pull request #6610 from thaJeztah/28.x_backport_deprecate_builder_utils
[28.x backport] cli/command/image/build: deprecate `DefaultDockerfileName`, `DetectArchiveReader`, `WriteTempDockerfile`, `ResolveAndValidateContextPath`
2025-11-04 07:23:51 -06:00
5dbaa52325 cli/command/image/build: deprecate ResolveAndValidateContextPath util
This utility was used internally and will be removed in the next release.
Use `DetectContextType` to detect the context-type, and use `GetContextFromLocalDir`,
`GetContextFromLocalDir`, `GetContextFromGitURL`, or `GetContextFromURL`
instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 0f2f9e9c41)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-04 07:14:44 -06:00
dd832b6d97 cli/command/image/build: deprecate WriteTempDockerfile util
It was only used internal in the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 6e1ff0bec1)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-04 07:14:44 -06:00
a99e91cc89 cli/command/image/build: deprecate DetectArchiveReader util
It was only used internal in the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit c52fa073cd)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-04 07:14:44 -06:00
579b72aa06 cli/command/image/build: deprecate DefaultDockerfileName const
It was only used internal in the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit f24bb4bc76)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-04 07:14:40 -06:00
6fc5891770 Merge pull request #6560 from thaJeztah/28.x_backport_deprecations
[28.x backport] opts, image/build: deprecate IsArchive, ValidateMACAddress,  ListOpts.Delete()
2025-11-04 07:12:50 -06:00
9af6cbc489 Merge pull request #6613 from thaJeztah/28.x_bump_go
[28.x] update to go1.24.9
2025-11-04 06:45:14 -06:00
ba53322412 update to go1.24.9
go1.24.9 (released 2025-10-13) includes fixes to the crypto/x509 package.
See the Go 1.24.9 milestone on our issue tracker for details:

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

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-04 11:10:08 +01:00
61d2e8aaad Merge pull request #6609 from thaJeztah/28.x_backport_bump_golangci_lint
[28.x backport] Dockerfile: update golangci-lint to v2.5.0
2025-11-03 11:39:06 -06:00
6abcd4a2a1 Merge pull request #6608 from thaJeztah/28.x_backport_update_gotestsum
[28.x backport] Dockerfile: bump gotest.tools/gotestsum v1.13.0
2025-11-03 15:41:42 +01:00
00c129b974 Merge pull request #6607 from thaJeztah/28.x_backport_update_actions
[28.x backport] update actions
2025-11-03 15:33:29 +01:00
fbf5c8a86d Dockerfile: update golangci-lint to v2.5.0
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5ad9fbdef7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-03 12:45:13 +01:00
4c7d52534f Dockerfile: bump gotest.tools/gotestsum v1.13.0
full diff: https://github.com/gotestyourself/gotestsum/compare/v1.12.3...v1.13.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit f8b1b8d165)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-03 12:37:13 +01:00
70123c523c build(deps): bump actions/upload-artifact from 4 to 5
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
(cherry picked from commit aef2ef8c77)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-03 12:32:03 +01:00
4942b2747f build(deps): bump github/codeql-action from 3 to 4
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3 to 4.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
(cherry picked from commit 5483b10e94)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-11-03 12:31:44 +01:00
d8bab71747 opts: deprecate ListOpts.Delete()
This method was added as part of a refactor in [moby@1ba1138], at which
time it was used to delete original values for "--host" and "--volume"
after normalizing. This beccame redundant in [moby@6200002], which added
specialized options that used a validate function, which both validated
and normalized inputs.

It's no longer used, so let's mark it deprecated so that we can remove it.

[moby@1ba1138]: 1ba11384bf
[moby@6200002]: 6200002669

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 193db8ec41)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-13 14:33:08 +02:00
36d9523e31 opts: deprecate ValidateMACAddress
It was a wrapper around net.ParseMAC from stdlib, so users should
use that directly.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 17d6a92954)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-13 14:30:34 +02:00
7063a0ef07 cli/command/image: runBuild: inline vars and minor cleanups
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9e646f6d92)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-13 14:26:53 +02:00
22487ad6f6 cli/command/image/build: deprecate IsArchive utility
It was only used internally.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 64be664e85)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-13 14:24:44 +02:00
4737ed4906 cli/command/image/build: fix linting, add sub-tests
- fix minor linting issues (unhandled errors)
- rename vars to prevent shadowing
- use sub-tests for tests that already prepared for it

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 2c539a6530)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-13 14:24:30 +02:00
8cff0087da Merge pull request #6544 from thaJeztah/28.x_bump_engine
[28.x] vendor: github.com/docker/docker v28.5.1
2025-10-09 10:11:06 +02:00
e8b22ce03c vendor: github.com/docker/docker v28.5.1
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-08 16:17:13 +02:00
e180ab8ab8 Merge pull request #6541 from vvoland/6540-28.x
Some checks failed
build / prepare (push) Has been cancelled
build / build (push) Has been cancelled
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 25, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 25, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
test / host (macos-15) (push) Has been cancelled
test / host (macos-15-intel) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x backport] update to go1.24.8
2025-10-07 19:50:32 -07:00
0d799c556f update to go1.24.8
This minor release includes 10 security fixes following the security policy:

- net/mail: excessive CPU consumption in ParseAddress

    The ParseAddress function constructed domain-literal address components through repeated string concatenation. When parsing large domain-literal components, this could cause excessive CPU consumption.

    Thanks to Philippe Antoine (Catena cyber) for reporting this issue.

    This is CVE-2025-61725 and Go issue https://go.dev/issue/75680.

- crypto/x509: quadratic complexity when checking name constraints

    Due to the design of the name constraint checking algorithm, the processing time
    of some inputs scales non-linearly with respect to the size of the certificate.

    This affects programs which validate arbitrary certificate chains.

    Thanks to Jakub Ciolek for reporting this issue.

    This is CVE-2025-58187 and Go issue https://go.dev/issue/75681.

- crypto/tls: ALPN negotiation errors can contain arbitrary text

    The crypto/tls conn.Handshake method returns an error on the server-side when
    ALPN negotation fails which can contain arbitrary attacker controlled
    information provided by the client-side of the connection which is not escaped.

    This affects programs which log these errors without any additional form of
    sanitization, and may allow injection of attacker controlled information into
    logs.

    Thanks to National Cyber Security Centre Finland for reporting this issue.

    This is CVE-2025-58189 and Go issue https://go.dev/issue/75652.

- encoding/pem: quadratic complexity when parsing some invalid inputs

    Due to the design of the PEM parsing function, the processing time for some
    inputs scales non-linearly with respect to the size of the input.

    This affects programs which parse untrusted PEM inputs.

    Thanks to Jakub Ciolek for reporting this issue.

    This is CVE-2025-61723 and Go issue https://go.dev/issue/75676.

- net/url: insufficient validation of bracketed IPv6 hostnames

    The Parse function permitted values other than IPv6 addresses to be included in square brackets within the host component of a URL. RFC 3986 permits IPv6 addresses to be included within the host component, enclosed within square brackets. For example: "http://[::1]/". IPv4 addresses and hostnames must not appear within square brackets. Parse did not enforce this requirement.

    Thanks to Enze Wang, Jingcheng Yang and Zehui Miao of Tsinghua University for reporting this issue.

    This is CVE-2025-47912 and Go issue https://go.dev/issue/75678.

- encoding/asn1: pre-allocating memory when parsing DER payload can cause memory exhaustion

    When parsing DER payloads, memories were being allocated prior to fully validating the payloads.
    This permits an attacker to craft a big empty DER payload to cause memory exhaustion in functions such as asn1.Unmarshal, x509.ParseCertificateRequest, and ocsp.ParseResponse.

    Thanks to Jakub Ciolek for reporting this issue.

    This is CVE-2025-58185 and Go issue https://go.dev/issue/75671.

- net/http: lack of limit when parsing cookies can cause memory exhaustion

    Despite HTTP headers having a default limit of 1 MB, the number of cookies that can be parsed did not have a limit.
    By sending a lot of very small cookies such as "a=;", an attacker can make an HTTP server allocate a large amount of structs, causing large memory consumption.

    net/http now limits the number of cookies accepted to 3000, which can be adjusted using the httpcookiemaxnum GODEBUG option.

    Thanks to jub0bs for reporting this issue.

    This is CVE-2025-58186 and Go issue https://go.dev/issue/75672.

- crypto/x509: panic when validating certificates with DSA public keys

    Validating certificate chains which contain DSA public keys can cause programs
    to panic, due to a interface cast that assumes they implement the Equal method.

    This affects programs which validate arbitrary certificate chains.

    Thanks to Jakub Ciolek for reporting this issue.

    This is CVE-2025-58188 and Go issue https://go.dev/issue/75675.

- archive/tar: unbounded allocation when parsing GNU sparse map

    tar.Reader did not set a maximum size on the number of sparse region data blocks in GNU tar pax 1.0 sparse files. A maliciously-crafted archive containing a large number of sparse regions could cause a Reader to read an unbounded amount of data from the archive into memory. When reading from a compressed source, a small compressed input could result in large allocations.

    Thanks to Harshit Gupta (Mr HAX) - https://www.linkedin.com/in/iam-harshit-gupta/ for reporting this issue.

    This is CVE-2025-58183 and Go issue https://go.dev/issue/75677.

- net/textproto: excessive CPU consumption in Reader.ReadResponse

    The Reader.ReadResponse function constructed a response string through
    repeated string concatenation of lines. When the number of lines in a response is large,
    this could cause excessive CPU consumption.

    Thanks to Jakub Ciolek for reporting this issue.

    This is CVE-2025-61724 and Go issue https://go.dev/issue/75716.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
(cherry picked from commit e598ea0176)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-10-07 21:51:36 +02:00
887030fbe8 Merge pull request #6522 from thaJeztah/28.x_bump_moby
Some checks failed
build / prepare (push) Has been cancelled
build / build (push) Has been cancelled
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 25, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 25, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
test / host (macos-15) (push) Has been cancelled
test / host (macos-15-intel) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x] vendor: github.com/docker/docker cd048300a487 (v28.5.0-dev)
2025-10-02 14:36:11 +00:00
9c6a0e0ba9 Merge pull request #6531 from thaJeztah/28.x_backport_bump_macos
[28.x backport] gha: add macOS 15, remove macOS 13 (deprecated)
2025-10-02 14:35:37 +00:00
f784471104 vendor: github.com/docker/docker cd048300a487 (v28.5.0-dev)
full diff: https://github.com/moby/moby/compare/v28.5.0-rc.1...cd048300a48700294339c9c91d2dcc691cb8f63b

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-01 17:34:28 +02:00
d7afcf9b98 Merge pull request #6529 from thaJeztah/28.x_backport_deprecate_ResolveDefaultContext
[28.x backport] cli/command: deprecate ResolveDefaultContext
2025-10-01 16:33:50 +02:00
9d9adf6346 gha: add macOS 15, remove macOS 13 (deprecated)
The macOS 13 runners are deprecated and will be removed on December 4th,
with brownouts in November;
https://github.blog/changelog/2025-09-19-github-actions-macos-13-runner-image-is-closing-down/

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 91d8c0bf62)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-01 12:05:21 +02:00
d4b7734f18 cli/command: deprecate ResolveDefaultContext
The ResolveDefaultContext function was exported in [cli@f820766] to allow
(unit) testing, but did not document that it was only exported for this
purpose. The only external use of this function is in buildx, which uses
it in a unit test that can be implemented without this function.

This patch deprecates the function so that we can remove it.

[cli@f820766]: f820766f6a

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 311a97a210)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-10-01 11:49:22 +02:00
a1061611fd Merge pull request #6519 from thaJeztah/28.x_backport_authconfig_no_direct_cast
[28.x backport] cli/command: explicitly map AuthConfig fields instead of a direct cast
2025-09-29 15:55:27 -07:00
5e42f826b4 Merge pull request #6518 from thaJeztah/28.x_backport_memstore_notfounderr
[28.x backport] cli/config/memorystore: remove unused IsErrValueNotFound
2025-09-29 15:13:54 -07:00
645c23bd13 Merge pull request #6514 from thaJeztah/28.x_backport_manifeststore_notfound
[28.x backport] cli/manifest/store: deprecate IsNotFound
2025-09-29 15:11:41 -07:00
e491078fc6 cli/command: explicitly map AuthConfig fields instead of a direct cast
Commit [cli@27b2797] forked the AuthConfig type from the API, and changed
existing code to do a direct cast / convert of the forked type to the API
type. This can cause issues if the API types diverges, such as the removal
of the Email field.

This patch explicitly maps each field to the corresponding API type, but
adds some TODOs, because various code-paths only included a subset of the
fields, which may be intentional for fields that were meant to be handled
on the daemon / registry-client only.

We should evaluate these conversions to make sure these fields should
be sent from the client or not (and possibly even removed from the API
type).

[cli@27b2797]: 27b2797f7d

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9f02d9643d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-29 13:15:05 +02:00
a3ffb8a148 cli/config/memorystore: remove unused IsErrValueNotFound
This utility was added in 9b83d5bbf9, but
was never used. Remove the utility, and rewrite the error returned to
implement the errdefs.NotFound interface, so that it can be detected
using the errdefs.IsNotFound() utility if needed.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 3c78ac2aad)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-29 13:08:43 +02:00
a4ae5f2f7a cli/manifest/store: deprecate IsNotFound
Deprecate the IsNotFound utility in favor of errdefs.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit f3fb7728c7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-26 23:35:20 +02:00
394991e2ab Merge pull request #6510 from thaJeztah/28.x_backport_auth
[28.x backport] cli/command/image: pushTrustedReference: internalize constructing indexInfo
2025-09-26 08:14:49 -07:00
e5bce5cd2d Merge pull request #6509 from thaJeztah/28.x_backport_dct_retiring
[28.x backport] trust: print deprecation warning when using hub Notary server
2025-09-26 08:13:53 -07:00
d5c181abf4 cli/command/image: pushTrustedReference: internalize constructing indexInfo
All information needed can be deducted from the image reference, which
is used to create a indexInfo, repoInfo, and to resolve auth-config.

In some situations this may result in resolving the auth-config twice
after it already was resolved to an encoded auth-config.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9a6313ed3b)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-26 11:29:44 +02:00
0351ece9e5 trust: print deprecation warning when using hub Notary server
Docker Hub's Notary service is being retired, and now produces
failures in most cases. Add a warning when attempting to use
it, pending full removal of trust;
https://www.docker.com/blog/retiring-docker-content-trust/

With this PR:

    DOCKER_CONTENT_TRUST=1 docker pull -q hello-world
    WARNING: Docker is retiring DCT for Docker Official Images (DOI).
             For details, refer to https://docs.docker.com/go/dct-deprecation/

    could not validate the path to a trusted root: unable to retrieve valid leaf certificates

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 43b03ef2c5)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-26 11:24:04 +02:00
ec00b85794 cli/command/image: runPush: minor cleanups and linting issues
- Remove redundant intermediate variables
- Explicitly use an early return on error instead of combining with
  other checks.
- Fix unhandled errors and combine defers
- Remove outstanding TODO that unlikely will be addressed

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit c36e67d7b6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-26 11:21:59 +02:00
a69c591c5a Merge pull request #6501 from thaJeztah/28.x_bump_docker_28.5
[28.x] vendor: github.com/docker/docker v28.5.0-rc.1
2025-09-25 17:33:08 +02:00
f9d2820a20 vendor: github.com/docker/docker v28.5.0-rc.1
full diff: https://github.com/docker/docker/compare/d21856f25dbe...v28.5.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 15:50:30 +02:00
c28ec0e4ce Merge pull request #6497 from thaJeztah/28.x_backport_deprecate_apply
Some checks failed
build / prepare (push) Has been cancelled
build / build (push) Has been cancelled
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 25, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 25, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 25, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-13) (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x backport] cli/command: deprecate DockerCli.Apply
2025-09-25 12:29:30 +00:00
d1c8336395 cli/command: deprecate DockerCli.Apply
The Apply method was added when CLI options for constructing the CLI were
rewritten into functional options in [cli@7f207f3]. There was no mention
in the pull request of this method specifically, and this may have been
related to work being done elsewhere on compose-on-kubernetes or the
compose-cli plugin that may have needed options to modify the CLI config
after it was already initialized.

The CLI itself no longer depends on this method since [cli@133279f], and
the only known consumer (docker compose) no longer needs it since [cli@2711800]
and [cli@048e931].

This patch deprecates the method with the intent to remove it in a future
release.

[cli@7f207f3]: 7f207f3f95
[cli@133279f]: 133279fb0d
[cli@2711800]: 2711800430
[cli@048e931]: 048e931b42

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 24bfedf3f8)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 13:30:15 +02:00
61b9fd4068 Merge pull request #6491 from thaJeztah/28.x_backport_deprecate_defaultversion
[28.x backport] cli/command: deprecate DockerCli.DefaultVersion
2025-09-25 11:25:04 +00:00
2ef1b4eabe Merge pull request #6495 from thaJeztah/28.x_backport_deprecate_ContentTrustEnabled
[28.x backport] cli/command: deprecate DockerCli.ContentTrustEnabled
2025-09-25 11:24:29 +00:00
bea31fccbb Merge pull request #6489 from thaJeztah/28.x_backport_deprecate_dct_opts
[28.x backport] cli/command: deprecate WithContentTrustFromEnv, WithContentTrust
2025-09-25 11:23:41 +00:00
e9c189e1c2 cli/command: deprecate DockerCli.DefaultVersion
This function was used internally, but is no longer used. There are
no known users of this method, so already removing it from the Cli
interface.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 0270b2d6f7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 12:58:46 +02:00
118548d02b cli/command: deprecate DockerCli.ContentTrustEnabled
This function was used internally, but is no longer used. Users should check
the value of the `DOCKER_CONTENT_TRUST` environment variable instead.

There are no known external users of this method, so already removing it
from the Cli interface; this method will be removed in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 11d40488dd)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 12:55:31 +02:00
026ef0df2d [28.x] remove remaining uses of DockerCli.ContentTrustEnabled
These were already replaced for stubs in master.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 12:55:26 +02:00
4665091715 cli/command: deprecate WithContentTrustFromEnv, WithContentTrust
These options were used internally as defaults for the constructor and
only impact commands implemented in the CLI itself.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 40cdfc0d81)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 12:52:28 +02:00
261d8bcf8d trust: add internal utility for checking DOCKER_CONTENT_TRUST
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 1bae6aafa8)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 12:50:30 +02:00
3755161455 Merge pull request #6493 from thaJeztah/28.x_backport_fix_alpine
[28.x backport] e2e: update openssh, openssl to work around openssh bug
2025-09-25 11:41:45 +02:00
db5a0ae673 e2e: update openssh, openssl to work around openssh bug
relates to https://gitlab.alpinelinux.org/alpine/aports/-/issues/17547

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit b611f288ee)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-25 10:59:32 +02:00
843153da37 Merge pull request #6477 from thaJeztah/28.x_backport_cli_user_agent
[28.x backport] cli/command: add WithUserAgent option
2025-09-24 10:36:10 -07:00
a2d7989230 Merge pull request #6483 from austinvazquez/vendor-docker-docker-28.x
[28.x] vendor: github.com/docker/docker v28.5.0-dev
2025-09-24 19:19:30 +02:00
985cee2de0 cli/command: add WithUserAgent option
Add support to the `cli/command` package to accept a custom User
Agent to pass to the underlying client.

This is used as the `UpstreamClient` portion of the `User-Agent`
when the Moby daemon makes requests.

For example, pushing and pulling images with Compose might result
in the registry seeing a `User-Agent` value of:

```
docker/24.0.7 go/go1.20.10 git-commit/311b9ff kernel/6.5.13-linuxkit os/linux arch/arm64 UpstreamClient(docker-cli-plugin-compose/v2.24.0)
```

Signed-off-by: Milas Bowman <milas.bowman@docker.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 048e931b42)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-09-24 19:18:04 +02:00
e1dd0e1501 Merge pull request #6481 from thaJeztah/28.x_backport_cli_plugin_options
[28.x backport] cli-plugins/plugin: Run: allow customizing the CLI
2025-09-24 19:10:17 +02:00
82ff4b5634 Merge pull request #6482 from thaJeztah/28.x_backport_plugin_semverish
[28.x backport] cli-plugins/manager: allow schema-versions <= 2.0.0
2025-09-24 19:09:27 +02:00
4de56bc72f vendor: github.com/docker/docker v28.5.0-dev
Signed-off-by: Austin Vazquez <austin.vazquez@docker.com>
2025-09-24 11:39:14 -05:00
2ed0d99acc cli-plugins/manager: allow schema-versions <= 2.0.0
The CLI currently hard-codes the schema-version for CLI plugins to
"0.1.0", which doesn't allow us to expand the schema for plugins.

As there's many plugins that we shipped already, we can't break
compatibility until we reach 2.0.0, but we can expand the schema
with non-breaking changes.

This patch makes the validation more permissive to allow new schema
versions <= 2.0.0. Note that existing CLIs will still invalidate
such versions, so we cannot update the version until such CLIs are
no longer expected to be used, but this patch lays the ground-work
to open that option.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit ec912e5524)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 11:09:58 -05:00
cbeddb1390 Merge pull request #6480 from thaJeztah/28.x_backport_remove_cli_experimental_remnants
[28.x backport] remove some remnants from CLI "experimental" config option
2025-09-24 18:06:20 +02:00
1fb1577626 cli-plugins/plugin: Run: allow customizing the CLI
Currently, the plugin.Run command constructs the DockerCli using
the default options, assuming plugins run with all the same options
as the CLI itself; to customize the CLI there's a "Apply" option,
but this means mutating the CLI after it's already constructed, which
is not ideal.

This patch adds a variadic ops argument to allow CLI plugins to pass
custom options to use for the CLI, so that there's no need to mutate
its config in most cases.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 2711800430)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 16:24:39 +02:00
67885d0dcc Merge pull request #6474 from thaJeztah/28.x_backport_bump_go_connections
[28.x backport] vendor: github.com/docker/go-connections v0.6.0
2025-09-24 07:20:43 -07:00
2ed42a8ade cli-plugins/manager: reformat TestValidateCandidate table
Slightly more verbose, but makes it easier to see properties
of each test.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 057f3128b6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 16:20:11 +02:00
4bac500fb2 remove some remnants from CLI "experimental" config option
Experimental is always enabled (977d3ae046),
and the `Experimental` field in plugin metadata was deprecated in
977d3ae046 and removed in commit
6a50c4f700.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit dfbac70efa)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 16:20:11 +02:00
9d9f632527 Merge pull request #6476 from thaJeztah/28.x_backport_ignore_broken_symlinks
[28.x backport] cli-plugins/manager: ignore broken symlinks
2025-09-24 07:18:05 -07:00
a2e17eb9d5 Merge pull request #6478 from thaJeztah/28.x_backport_cli_plugins_touchup
[28.x backport] cli-plugins/plugin: Run: touch-up godoc and minor cleanups
2025-09-24 07:13:18 -07:00
5d201ca436 cli-plugins/plugin: Run: touch-up godoc and minor cleanups
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 635a718209)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 15:17:50 +02:00
d1122a2293 cli-plugins/manager: ignore broken symlinks
Before this patch, a broken symlink would print a warning;

    docker info > /dev/null
    WARNING: Plugin "/Users/thajeztah/.docker/cli-plugins/docker-feedback" is not valid: failed to fetch metadata: fork/exec /Users/thajeztah/.docker/cli-plugins/docker-feedback: no such file or directory

After this patch, such symlinks are ignored:

    docker info > /dev/null

With debug enabled, we don't ignore the faulty plugin, which will
make the warning shown on docker info;

    mkdir -p ~/.docker/cli-plugins
    ln -s nosuchplugin ~/.docker/cli-plugins/docker-brokenplugin
    docker --debug info
    Client:
     Version:    29.0.0-dev
     Context:    default
     Debug Mode: true
     Plugins:
      buildx: Docker Buildx (Docker Inc.)
        Version:  v0.25.0
        Path:     /usr/libexec/docker/cli-plugins/docker-buildx
    WARNING: Plugin "/Users/thajeztah/.docker/cli-plugins/docker-brokenplugin" is not valid: failed to fetch metadata: fork/exec /Users/thajeztah/.docker/cli-plugins/docker-brokenplugin: no such file or directory

    # ...

We should als consider passing a "seen" map to de-duplicate entries.
Entries can be either a direct symlink or in a symlinked path (for
which we can filepath.EvalSymlinks). We need to benchmark the overhead
of resolving the symlink vs possibly calling the plugin (to get their
metadata) further down the line.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9b2f831452)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 14:34:44 +02:00
d52de77ef4 vendor: github.com/docker/go-connections v0.6.0
- deprecate sockets.GetProxyEnv, sockets.DialerFromEnvironment
- add support for unix sockets on Windows
- remove legacy CBC cipher suites from client config
- align client and server defaults to be the same.
- remove support for encrypted TLS private keys.
- nat: optimize ParsePortSpec

full diff: https://github.com/docker/go-connections/compare/v0.5.0...v0.6.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 3529651fa7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:59:33 +02:00
01f8949484 Merge pull request #6472 from thaJeztah/28.x_backport_remove_special_handlings
[28.x backport] remove special handling for plugin errors and Windows warning on Build
2025-09-24 13:56:45 +02:00
b9e3346b1e Merge pull request #6473 from thaJeztah/28.x_backport_deprecation_preparations
[28.x backport] remove uses of client options that will be deprecated
2025-09-24 13:54:43 +02:00
25421ace0b Merge pull request #6471 from thaJeztah/28.x_backport_fix_stats_bounds
[28.x backport] cli/command/container: prevent panic during stats on empty event Actor.ID
2025-09-24 13:50:25 +02:00
ede7019b14 Merge pull request #6470 from thaJeztah/28.x_backport_setup-go-6
[28.x backport] CI updates
2025-09-24 13:50:09 +02:00
d48256b26d Merge pull request #6469 from thaJeztah/28.x_backport_template_deprecate_newparse
[28.x backport] templates: deprecate NewParse()
2025-09-24 13:44:06 +02:00
09fcf8e3dd cli/command: NewDockerCli: don't depend on DockerCli.Apply
The Apply method was added when CLI options for constructing the CLI were
rewritten into functional options in [cli@7f207f3]. There was no mention
in the pull request of this method specifically, and this may have been
related to work being done elsewhere on compose-on-kubernetes or the
compose-cli plugin that may have needed options to modify the CLI config
after it was already initialized.

We should try to remove functions that mutate the CLI configuration after
initialization if possible (and likely remove the `Apply` method); currently
this function is used in docker compose, but as part of a hack that can
probably be avoided.

[cli@7f207f3]: 7f207f3f95

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 133279fb0d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:37:57 +02:00
56f7bd0759 Set ReservedSpace field in preparation of KeepStorage deprecation
This change updates the builder prune command to send the `ReservedSpace` parameter in preparation of `KeepStorage` deprecation in API v1.52.

Signed-off-by: Austin Vazquez <austin.vazquez@docker.com>
(cherry picked from commit 7d85d8fbea)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:37:45 +02:00
3bacc99580 cli/command/image: build: remove permissions warning on Windows
This warning was added in [moby@4a8b3ca] to print a warning when building
Linux images from a Windows client. Window's filesystem does not have an
"executable" bit, which mean that, for example, copying a shell script
to an image during build would lose the executable bit. So for Windows
clients, the executable bit would be set on all files, unconditionally.

Originally this was detected in the client, which had direct access to
the API response headers, but when refactoring the client to use a common
library in [moby@535c4c9], this was refactored into a `ImageBuildResponse`
wrapper, deconstructing the API response into an `io.Reader` and a string
field containing only the `OSType` header.

This was the only use and only purpose of the `OSType` field, and now that
BuildKit is the default builder for Linux images, this warning didn't get
printed unless BuildKit was explicitly disabled.

This patch removes the warning, so that we can potentially remove the
field, or the `ImageBuildResponse` type altogether.

[moby@4a8b3ca]: 4a8b3cad60
[moby@535c4c9]: 535c4c9a59

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit af65ee4584)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:34:50 +02:00
f77defa891 cli/command/plugin: remove special error handling on install, upgrade
Similar to 323fbc485e - this code was added
in [moby@c127d96], but used string-matching to detect cases where a user
tried to install an image as plugin. However, this handling no longer matched
any error-strings, so no longer worked:

    docker plugin install busybox
    Error response from daemon: did not find plugin config for specified reference docker.io/library/busybox:latest

[moby@c127d96]: c127d9614f

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit fb3f2da50e)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:34:34 +02:00
4a677b86a6 cli/command/image: remove special handling for plugin errors on pull
This special handling was added in [moby@9b6dcc8], and later updated in
[moby@c127d96], but it fully depended on string-matching, which is brittle.
Testing the original ticket that lead to this handling, it looks like the
string matching no longer works, and the daemon error is returned as-is:

With graphdrivers:

    docker pull tiborvass/no-remove
    Using default tag: latest
    Error response from daemon: Encountered remote "application/vnd.docker.plugin.v0+json"(unknown) when fetching

With containerd snapshotters enabled:

    docker pull tiborvass/no-remove
    Using default tag: latest
    latest: Pulling from tiborvass/no-remove
    cf635291f7c9: Download complete
    failed to unpack image on snapshotter overlayfs: mismatched image rootfs and manifest layers

The error-message for containerd can probably be improved, but as the special
handling in the CLI no longer works, we can remove it.

[moby@9b6dcc8]: 9b6dcc8b9d
[moby@c127d96]: c127d9614f

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 323fbc485e)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:33:40 +02:00
1cf78c49ab cli/command/container: prevent panic during stats on empty event Actor.ID
This code was missing a check for the ID field before truncating it to a
shorter length for presentation. This would result in a panic if an event
would either have an empty ID field or a shorter length ID;

    panic: runtime error: slice bounds out of range [:12] with length 0

    goroutine 82 [running]:
    github.com/docker/cli/cli/command/container.RunStats.func2({{0x0, 0x0}, {0x0, 0x0}, {0x0, 0x0}, {0x40001fcba0, 0x9}, {0x40001fcba9, 0x5}, ...})
        /go/src/github.com/docker/cli/cli/command/container/stats.go:146 +0x1d0
    created by github.com/docker/cli/cli/command/container.(*eventHandler).watch in goroutine 6
        /go/src/github.com/docker/cli/cli/command/container/stats.go:363 +0x1c8

We need to look at this code in general; the truncated ID is passed to
NewStats, which uses the ID to propagate the `Container` field in the
`StatsEntry` struct. which is not used in the default format used by
`docker stats` and, having the same content as the `ID` field on the
same struct, doesn't make it very useful, other than being able to
present it under a `CONTAINER` column (instead of `CONTAINER ID`);
we should consider deprecating it; there may be some subtle things
to look into here; the `Container` field originally held the container
name. This was changed in [moby@ef915fd], which introduced separate
`ID` and `Name` fields, renaming the old `Name` field to container.

Looking at [`Stats.SetStatistics()`] and related code in [stats_helpers.go],
the `Container` field is used as the "canonical" reference for the stats
record; this allows the stats _data_ to be refreshed when a new stats
sample arrives for the same container (also see [moby@929a77b], which
moved locking to the `Stats` wrapper struct). This construct allows to
account for intermediate states, where a stats sample was incomplete
or could produce an error; in that case, the reference to the container
for which the stats were sampled is kept to allow removing a container
from the list once the container was removed. We should consider removing
`Container` as a formatting option, and moving the `Container` field to
the outer struct; this makes the outer struct responsible for keeping a
reference to the container, allowing the `StatsEntry` as a whole to be
replaced atomically.

This patch only addresses the panic;

- It changes the logic to preserve the container ID verbatim instead
  of truncating. This allows stats samples to be matched against the
  `Actor.ID` as-is.
- Truncating the `Container` is moved to the presentation logic;
  currently this does not take `--no-trunc` into account to keep
  the existing behavior, but we can (should) consider adding this.
- Logging is improved to use structured logs, and an extra check is
  added to prevent empty IDs from being added as watcher.

[`Stats.SetStatistics()`]: 82281087e3/cli/command/container/formatter_stats.go (L88-L94)
[moby@ef915fd]: ef915fd036
[moby@929a77b]: 929a77b814
[stats_helpers.go]: 82281087e3/cli/command/container/stats_helpers.go (L26-L51)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9b79e48646)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:30:08 +02:00
2fb1298416 cli/command/container: improve TestContainerStatsContext
- Use sub-tests
- Don't use un-named keys
- Add test-cases for 'Name', 'ID' and custom container names

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit b9314938b7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:29:59 +02:00
a0ebf3e35c cli/command/container: improve TestContainerStatsContext
- Don't use unnamed keys
- Use sub-tests
- Add test-cases for Name and ID fields

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit b8cda96d11)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:29:51 +02:00
428518a84a gha: update test-matrix: remove docker 23.x, 26.x, add 25.x
- Mirantis Container Runtime (MCR) 23.0 reached EOL, and the next LTS
  version of MCR is 25.x
- Docker 26.x reached EOL and is no longer maintained

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 83e40c39b4)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:26:32 +02:00
c1914f73f5 build(deps): bump actions/setup-go from 5 to 6
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 5 to 6.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
(cherry picked from commit 44e66a97a9)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:25:53 +02:00
cab5014d57 templates: deprecate NewParse()
It it just a chain of `New("sometag").Parse(...)`, and most of our
uses don't use a tag for the template, so can call Parse.

There's no public users of this function, but deprecating it first
just in case.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 7ab3e7e774)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-24 13:14:00 +02:00
7c3ec3ec02 Merge pull request #6428 from thaJeztah/28.x_backport_avoid_client_types_in_opts
[28.x backport] don't wrap client options
2025-09-04 15:46:08 -07:00
aa976192cb cli/command: don't wrap client options
We may still change this, but in the client module, the signature
of the client.Opt changed to now include a non-exported type, which
means that we can't construct a custom option that is implemented
using client options:

    #18 16.94 # github.com/docker/cli/cli/context/docker
    #18 16.94 cli/context/docker/load.go:105:29: cannot use withHTTPClient(tlsConfig) (value of type func(*client.Client) error) as client.Opt value in argument to append
    #18 16.94 cli/context/docker/load.go:152:6: cannot use c (variable of type *client.Client) as *client.clientConfig value in argument to client.WithHTTPClient(&http.Client{…})

We can consider exporting the `client.clientConfig` type (but keep its
fields non-exported), but for this use, we don't strictly need it, so
let's change the implementation to not having to depend on that.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit e7d14d905e)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-04 19:03:45 +02:00
2de1ea9769 cli/context/docker: don't wrap client options
We may still change this, but in the client module, the signature
of the client.Opt changed to now include a non-exported type, which
means that we can't construct a custom option that is implemented
using client options:

    #18 16.94 # github.com/docker/cli/cli/context/docker
    #18 16.94 cli/context/docker/load.go:105:29: cannot use withHTTPClient(tlsConfig) (value of type func(*client.Client) error) as client.Opt value in argument to append
    #18 16.94 cli/context/docker/load.go:152:6: cannot use c (variable of type *client.Client) as *client.clientConfig value in argument to client.WithHTTPClient(&http.Client{…})

We can consider exporting the `client.clientConfig` type (but keep its
fields non-exported), but for this use, we don't strictly need it, so
let's change the implementation to not having to depend on that.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit b0b0e457f0)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-04 19:01:40 +02:00
0ac676b171 Merge pull request #6425 from vvoland/update-docker
[28.x] vendor: github.com/docker/docker v28.4.0
2025-09-04 01:01:14 +02:00
b627f18262 vendor: github.com/docker/docker v28.4.0
full diff: https://github.com/docker/docker/compare/249d679a6baf...v28.4.0

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-09-04 00:22:49 +02:00
d8eb465f86 Merge pull request #6424 from vvoland/update-docker
Some checks failed
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 23, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 23, local) (push) Has been cancelled
e2e / tests (alpine, 26, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 26, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 23, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 23, local) (push) Has been cancelled
e2e / tests (debian, 26, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 26, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-13) (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x] vendor: github.com/docker/docker v28.4.0-dev (249d679a6baf)
2025-09-03 22:52:20 +02:00
a83e3df40b vendor: github.com/docker/docker v28.4.0-dev (249d679a6baf)
full diff: https://github.com/docker/docker/compare/v28.4.0-rc.2...249d679a6baf

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-09-03 22:32:15 +02:00
ff5ea757b4 Merge pull request #6422 from vvoland/6421-28.x
[28.x backport] update to go1.24.7
2025-09-03 21:28:57 +02:00
c1d14aef3c Merge pull request #6423 from vvoland/update-docker
[28.x] vendor: github.com/docker/docker v28.4.0-rc.2
2025-09-03 21:04:36 +02:00
18adfd54a9 vendor: github.com/docker/docker v28.4.0-rc.2
full diff: https://github.com/docker/docker/compare/5d5332b00c76...v28.4.0-rc.2

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-09-03 20:58:26 +02:00
6e20b9d93c update to go1.24.7
This includes 1 security fix:

- net/http: CrossOriginProtection bypass patterns are over-broad

    When passing patterns to CrossOriginProtection.AddInsecureBypassPattern,
    requests that would have redirected to those patterns (e.g. without a trailing
    slash) were also exempted, which might be unexpected.

    Thanks to Marco Gazerro for reporting this issue.

    This is CVE-2025-47910 and Go issue https://go.dev/issue/75054.

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

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
(cherry picked from commit f64b8a332d)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-09-03 20:44:05 +02:00
3cadbd82c5 Merge pull request #6420 from thaJeztah/28.x_backport_complete_pull
[28.x backport] add completion for docker image pull
2025-09-03 17:35:07 +02:00
b3df92053d add completion for docker image pull
With this patch, completion is provided for images already present
in the local image cache to help pulling the latest version of the
same tag;

    docker pull go<tab>
    golang:1.12    golang:1.18.0  golang:1.21    golang:1.24    gopher:latest
    golang:1.13    golang:1.20    golang:1.23    golang:latest

    docker pull golang:<tab>
    1.12    1.13    1.18.0  1.20    1.21    1.23    1.24    latest

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5bf3c6793d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-03 15:42:07 +02:00
b89b069082 Merge pull request #6416 from vvoland/update-docker
Some checks failed
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 23, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 23, local) (push) Has been cancelled
e2e / tests (alpine, 26, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 26, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 23, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 23, local) (push) Has been cancelled
e2e / tests (debian, 26, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 26, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-13) (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x] vendor: github.com/docker/docker v28.4.0-rc.2-dev (5d5332b00c76)
2025-09-02 12:37:23 +02:00
9deb5e9cd3 vendor: github.com/docker/docker v28.4.0-rc.2-dev (5d5332b00c76)
full diff: https://github.com/docker/docker/compare/v28.4.0-rc.1...5d5332b00c76

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-09-02 12:15:13 +02:00
e8be20bc9c Merge pull request #6413 from thaJeztah/28.x_backport_deprecate_OauthLoginEscapeHatchEnvVar
[28.x backport] cli/command/registry: deprecate OauthLoginEscapeHatchEnvVar
2025-09-01 18:05:08 +02:00
f2cd1979c0 Merge pull request #6411 from thaJeztah/28.x_backport_deprecate_ReexecEnvvar
[28.x backport] cli-plugins/manager: deprecate ReexecEnvvar
2025-09-01 17:57:49 +02:00
991d942cc3 cli/command/registry: deprecate OauthLoginEscapeHatchEnvVar
This const was added in 846ecf59ff, but
only used internally. This patch deprecates the const, to be removed
in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 18cdc25bb4)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-01 17:47:37 +02:00
8e49313c0c cli-plugins/manager: deprecate ReexecEnvvar
This alias was added in 4321293972, which is
part of v28.0, but did not deprecate them. They are no longer used in the
CLI itself, but may be used by cli-plugin implementations.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 6fa7d18320)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-01 17:37:27 +02:00
6cd42da462 Merge pull request #6409 from thaJeztah/28.x_bump_engine
[28.x] vendor: github.com/docker/docker v28.4.0-rc.1
2025-09-01 13:14:46 +02:00
2b9489d827 [28.x] vendor: github.com/docker/docker v28.4.0-rc.1
full diff: https://github.com/moby/moby/compare/02b4a1a3decc...v28.4.0-rc.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-09-01 11:24:20 +02:00
fbeae8516b Merge pull request #6405 from thaJeztah/28.x_backport_deprecate_nocomplete
[28.x backport] cli/command/completion: deprecate NoComplete
2025-09-01 09:13:54 +02:00
d593e61275 Merge pull request #6403 from thaJeztah/28.x_backport_deprecate_context_funcs
[28.x backport] cli/command/context: deprecate exported types and functions
2025-09-01 09:12:27 +02:00
139968dff2 cli/command/completion: deprecate NoComplete
This function was an exact duplicate of [cobra.NoFileCompletions], so
deprecating it in favor of that.

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

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 2827d037ba)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-30 12:24:11 +02:00
925db59377 cli/command/context: deprecate exported types and functions
These functions and types are shallow wrappers around the context
store and were intended for internal use as implementation for the
CLI itself.

They were exported in 3126920af1 to be
used by plugins and Docker Desktop. However, there's currently no public
uses of this, and Docker Desktop does not use these functions.

This patch deprecates the exported functions as they were meant to be
implementation specific for the CLI. If there's a need to provide
utilities for manipulating the context-store other than through the
CLI itself, we can consider creating an SDK for that purpose.

This deprecates:

- `RunCreate` and `CreateOptions`
- `RunExport` and `ExportOptions`
- `RunImport`
- `RunRemove` and `RemoveOptions`
- `RunUpdate` and `UpdateOptions`
- `RunUse`

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 95eeafa551)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-30 12:13:27 +02:00
aced30d906 Merge pull request #6399 from vvoland/6371-28.x
Some checks failed
build / bin-image (push) Has been cancelled
build / prepare-plugins (push) Has been cancelled
build / plugins (push) Has been cancelled
codeql / codeql (push) Has been cancelled
e2e / tests (alpine, 23, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 23, local) (push) Has been cancelled
e2e / tests (alpine, 26, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 26, local) (push) Has been cancelled
e2e / tests (alpine, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 27, local) (push) Has been cancelled
e2e / tests (alpine, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (alpine, 28, local) (push) Has been cancelled
e2e / tests (debian, 23, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 23, local) (push) Has been cancelled
e2e / tests (debian, 26, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 26, local) (push) Has been cancelled
e2e / tests (debian, 27, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 27, local) (push) Has been cancelled
e2e / tests (debian, 28, connhelper-ssh) (push) Has been cancelled
e2e / tests (debian, 28, local) (push) Has been cancelled
test / ctn (push) Has been cancelled
test / host (macos-13) (push) Has been cancelled
test / host (macos-14) (push) Has been cancelled
validate / validate (lint) (push) Has been cancelled
validate / validate (shellcheck) (push) Has been cancelled
validate / validate (update-authors) (push) Has been cancelled
validate / validate (validate-vendor) (push) Has been cancelled
validate / validate-md (push) Has been cancelled
validate / validate-make (manpages) (push) Has been cancelled
validate / validate-make (yamldocs) (push) Has been cancelled
[28.x backport] Add escape hatch for GODEBUG=x509negativeserial
2025-08-29 16:34:50 +02:00
b9e15efde0 return early if GODEBUG set or context is default
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 72f79333e5)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-08-29 16:00:23 +02:00
4108febfae rename function to fit what it is doing
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 6163c03b11)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-08-29 16:00:21 +02:00
8cfe1f712e Test setAllowNegativex509
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 467305fcea)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-08-29 16:00:19 +02:00
7c34fd56d0 Cleanup setAllowNegativex509
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 65a6c35d90)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-08-29 16:00:18 +02:00
0a2eaa4d05 Add escape hatch for GODEBUG=x509negativeserial
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 7d7a7aac4d)
Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
2025-08-29 16:00:16 +02:00
d26f1fd6d3 Merge pull request #6266 from thaJeztah/28.x_bump_engine
[28.x] vendor: github.com/docker/docker 02b4a1a3decc (v28.4.0-dev)
2025-08-28 16:38:19 +02:00
4f6182a50c Merge pull request #6394 from thaJeztah/28.x_bump_version
[28.x] bump version to v28.4.0-dev
2025-08-28 16:37:58 +02:00
4caa99468d [28.x] bump version to v28.4.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-08-28 15:52:47 +02:00
c2117f956f vendor: github.com/docker/docker 02b4a1a3decc (v28.4.0-dev)
full diff: https://github.com/moby/moby/compare/v28.3.3...02b4a1a3decc99de2965421cea5634c1e5297266

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 15:51:57 +02:00
19b86ef9e2 Merge pull request #6391 from thaJeztah/28.x_backport_deprecate_stack_commands
[28.x backport] cli/command/stack/*: deprecate exported functions and types
2025-08-28 13:55:57 +02:00
88d6197d4c Merge pull request #6392 from thaJeztah/28.x_backport_fix_email_deprecation
[28.x backport] cli/config/types: update deprecation comment for AuthConfig.Email
2025-08-28 13:52:44 +02:00
bda15c766a cli/config/types: update deprecation comment for AuthConfig.Email
Relates to [cli@27b2797], which forked this type from the Moby API, and
[moby@6cfff7e], which made the same change on the API side.

The Email field was originally used to create a new Docker Hub account
through the `docker login` command. The `docker login` command could be
used both to log in to an existing account (providing only username and
password), or to create a new account (providing desired username and
password, and an e-mail address to use for the new account).

This functionality was confusing, because it was implemented when Docker
Hub was the only registry, but the same functionality could not be used
for other registries. This functionality was removed in Docker 1.11 (API
version 1.23) through [moby@aee260d], which also removed the Email field
([engine-api@9a9e468]) as it was no longer used.

However, this caused issues when using a new CLI connecting with an old
daemon, as the field would no longer be serialized, and the deprecation
may not yet be picked up by custom registries, so [engine-api@167efc7]
added the field back, deprecated it, and added an "omitempty". There
was no official "deprecated" format yet at the time, so let's make sure
the deprecation follows the proper format to make sure it gets noticed.

[cli@27b2797]: 27b2797f7d
[moby@6cfff7e]: 6cfff7e880
[moby@aee260d]: aee260d4eb
[engine-api@9a9e468]: 9a9e468f50
[engine-api@167efc7]: 167efc72bb

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit aab947de8f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 13:22:09 +02:00
e636ed2ae5 cli/command/stack: deprecate RunList, RunServices
Functions and types in this package were exported as part of the "compose
on kubernetes" feature, which was deprecated and removed. These functions
are meant for internal use, and will be removed in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit d16c560664)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 12:07:56 +02:00
19b7dfa1cf deprecate cli/command/stack/swarm
Functions and types in this package were exported as part of the "compose
on kubernetes" feature, which was deprecated and removed. These functions
are meant for internal use, and will be removed in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 036d3a6bab)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 12:07:52 +02:00
91de2a6dae deprecate cli/command/stack/options
Functions and types in this package were exported as part of the "compose
on kubernetes" feature, which was deprecated and removed. These functions
are meant for internal use, and will be removed in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit f0e5a0d654)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 12:04:51 +02:00
7c6f58affe deprecate cli/command/stack/loader
Functions and types in this package were exported as part of the "compose
on kubernetes" feature, which was deprecated and removed. These functions
are meant for internal use, and will be removed in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit ad6ab189a6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 12:04:51 +02:00
8c6a7fcbc9 deprecate cli/command/stack/formatter
Functions and types in this package were exported as part of the "compose
on kubernetes" feature, which was deprecated and removed. These functions
are meant for internal use, and will be removed in the next release.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 30774ed1f2)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 12:04:48 +02:00
3e87f59859 Merge pull request #6390 from thaJeztah/28.x_backport_avoid_shadowing
[28.x backport] cli/command: rename vars for consistency and prevent shadowing
2025-08-28 12:03:34 +02:00
a621313658 cli/command: rename vars for consistency and prevent shadowing
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9fd71c8347)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-28 11:37:25 +02:00
69dd67fc06 Merge pull request #6381 from thaJeztah/28.x_backport_internalize_ParseEnvFile
[28.x backport] opts: deprecate ParseEnvFile
2025-08-27 12:26:38 -07:00
b90c5a8fcb Merge pull request #6379 from thaJeztah/28.x_backport_test_fixes
[28.x backport] cli/command/system: don't use deprecated fields in tests
2025-08-27 12:22:48 -07:00
99676e6c9c Merge pull request #6384 from thaJeztah/28.x_backport_mergo
[28.x backport] vendor: dario.cat/mergo v1.0.2
2025-08-27 11:18:09 -07:00
524fd156f5 Merge pull request #6380 from thaJeztah/28.x_backport_docs_fixes
[28.x backport] docs fixes and fix flag annotation
2025-08-27 11:17:14 -07:00
07bcb9cca2 Merge pull request #6386 from thaJeztah/28.x_backport_bump_go_events
[28.x backport] vendor: github.com/docker/go-events v0.0.0-20250114142523-c867878c5e32
2025-08-27 11:14:41 -07:00
48ea3fa14f vendor: github.com/docker/go-events v0.0.0-20250114142523-c867878c5e32
full diff: e31b211e4f...c867878c5e

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 05220c5f19)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 15:55:20 +02:00
a27a86289e vendor: dario.cat/mergo v1.0.2
drops gopkg.in/yaml.v3 as dependency

full diff: https://github.com/darccio/mergo/compare/v1.0.1...v1.0.2

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit a93ed48d06)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 15:47:11 +02:00
e112eeea4d opts: deprecate ParseEnvFile
It was a wrapper around kvfile.Load, which should be used instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit e650803f09)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 15:00:30 +02:00
3b68cde77a cli/command/service: fix API annotations for generic resource flags
These flags were added in 20a6ff32ee, and require
API version v1.32 or up, but they accidentally copied the flag-name from another
flag, so were not setting the annotation correctly.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit dcc3d25dc2)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 14:57:28 +02:00
c712d97172 docs: add missing backticks in 'run.md'
Signed-off-by: Hossein Abbasi <16090309+hsnabszhdn@users.noreply.github.com>
(cherry picked from commit d9cafa759f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 14:57:15 +02:00
f385cb994f docs: fix sentence structures in 'run.md'
Signed-off-by: Hossein Abbasi <16090309+hsnabszhdn@users.noreply.github.com>
(cherry picked from commit ba2c1c94ab)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 14:57:00 +02:00
44c1d5775d cli/command/system: don't use deprecated fields in test
This only impacts the JSON marshaled output; the "regular" output
of `docker info` already ignores these fields.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 3d87aa441f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 14:51:55 +02:00
1468bb1962 cli/command/system: TestEventsFormat: remove use of deprecated fields
These were just testing JSON marshaling fields that are deprecated, but
may be present in a response; these fields will be removed in future
API versions, so stop testing for them.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 823c6a75b3)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-27 14:49:21 +02:00
44fb305591 Merge pull request #6348 from thaJeztah/28.x_backport_bump_x_sync
[28.x backport] vendor: golang.org/x/sync v0.16.0
2025-08-26 08:26:11 -07:00
b74574cd53 Merge pull request #6369 from thaJeztah/28.x_backport_deprecate_exported_config_funcs
[28.x backport] cli/command/config: deprecate exported types and functions
2025-08-26 13:19:00 +02:00
e60b20f08e cli/command/config: deprecate exported types and functions
These were exported in f60369dfe6 to be
used in docker enterprise, but this never happened, and there's no
known consumers of these, so we should deprecate these. External
consumers can still call the API-client directly, which should've
been the correct thing to do in the first place.

This deprecates:

- `RunConfigCreate` and  `CreateOptions`
- `RunConfigInspect` and `InspectOptions`
- `RunConfigList` and `ListOptions`
- `RunConfigRemove` and `RemoveOptions`

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit a5f4ba08d9)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-25 18:55:48 +02:00
6f7865f89a Merge pull request #6358 from thaJeztah/28.x_backport_rm_image_pull
[28.x backport] cli/command/image: remove exported RunPull, PullOptions
2025-08-25 16:20:31 +02:00
23518a47dd Merge pull request #6357 from thaJeztah/28.x_backport_unexport_authresolver_util
[28.x backport] cli/command/image: deprecate AuthResolver and un-export
2025-08-25 16:20:09 +02:00
eb120d2c28 Merge pull request #6354 from thaJeztah/28.x_backport_rm_json_deprecated
[28.x backport] internal/jsonstream: remove uses of deprecated fields
2025-08-25 15:52:28 +02:00
146f6492c7 cli/command/image: remove exported RunPull, PullOptions
These were exported in 812f113685, but
while the function and options are exported, the option-fields were
all un-exported, so these were not usable.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 9216f04eb6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-23 03:51:47 +02:00
8def226e53 cli/command/image: deprecate AuthResolver and un-export
This function was exported to share it between "trust" and "image",
but was only a shallow wrapper, so split the implementations where
used.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 7ad113ccc2)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-23 03:48:35 +02:00
82c5138c8e internal/jsonstream: remove uses of deprecated fields
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 045ac0b159)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-23 02:18:45 +02:00
bd3e420cc7 vendor: golang.org/x/sync v0.16.0
Brings in the errgroup implementation for reverted auto-recover from panics.

full diff: https://github.com/golang/sync/compare/v0.14.0...v0.16.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit c7cbac58b3)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 21:12:55 +02:00
bb2ed910bb Merge pull request #6343 from thaJeztah/28.x_backport_deprecate_builder_NewPruneCommand
[28.x backport] cli/command/builder: deprecate NewPruneCommand
2025-08-22 12:35:24 +02:00
1415080cfa cli/command/builder: deprecate NewPruneCommand
This patch deprecates exported NewPruneCommand and moves the
implementation details to an unexported function.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 7032f5922e)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 12:22:11 +02:00
0bbdda88e6 Merge pull request #6341 from thaJeztah/28.x_backport_internalize_formatters
[28.x backport] cli/command/*: deprecate formatting-related functions and types
2025-08-22 12:10:03 +02:00
4133271530 cli/command/trust: deprecate formatting-related functions and types
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.

This deprecates the following types and functions:

- `SignedTagInfo`
- `SignerInfo`
- `NewTrustTagFormat`
- `NewSignerInfoFormat`
- `TagWrite`
- `SignerInfoWrite`

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 95c9b1b13b)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:54 +02:00
0e17907266 cli/command/task: deprecate NewTaskFormat, FormatWrite
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>
(cherry picked from commit c3ee82fdc3)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:54 +02:00
b0b7dcfe86 cli/command/service: deprecate NewFormat, InspectFormatWrite
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>
(cherry picked from commit 9f453d3fea)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:54 +02:00
531ea22e7d cli/command/secret: deprecate NewFormat, FormatWrite, InspectFormatWrite
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>
(cherry picked from commit f3088e37a0)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:53 +02:00
e8cf8e65f7 cli/command/registry: deprecate NewSearchFormat, SearchWrite
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>
(cherry picked from commit 83371c2014)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:53 +02:00
22c68c5366 cli/command/plugin: deprecate NewFormat, FormatWrite
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>
(cherry picked from commit bf47419852)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:53 +02:00
e424c50373 cli/command/node: deprecate NewFormat, FormatWrite, InspectFormatWrite
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>
(cherry picked from commit 123ef81f7d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:53 +02:00
399861e7d2 cli/command/config: deprecate NewFormat, FormatWrite, InspectFormatWrite
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>
(cherry picked from commit e626f778ec)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:52 +02:00
694e92aa10 cli/command/checkpoint: deprecate NewFormat, FormatWrite
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>
(cherry picked from commit d861b78a8a)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:52 +02:00
09a36f2ef1 cli/command/image: deprecate NewHistoryFormat, HistoryWrite
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>
(cherry picked from commit 15cf4fa912)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:52 +02:00
73fbe6a020 cli/command/network: deprecate NewFormat, FormatWrite
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>
(cherry picked from commit e3903a1ac8)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:52 +02:00
4480024a80 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>
(cherry picked from commit fdc90caeee)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:52 +02:00
b4f2c0ca3d cli/command/container: newDiffContext: use struct-literal
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 0db7b9f774)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:51 +02:00
85a5e3da36 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>
(cherry picked from commit 239b727834)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:51 +02:00
34a75fb6f4 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>
(cherry picked from commit 907507e22a)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 11:47:48 +02:00
b52ab17a14 Merge pull request #6340 from thaJeztah/28.x_backport_cleanup_plugins
[28.x backport] cli/command/plugin: fix linting issues, and assorted cleanups
2025-08-22 11:31:06 +02:00
ec89d0ba67 cli/command/plugin: fix linting issues, and assorted cleanups
- fix various unhandled errors
- remove some locally defined option-types in favor of option-types
  defined by the client / api
- don't use unkeyed structs in tests, and add docs for some subtests
- fix some values in tests that triggered "spellcheck" warnings
- inline vars / functions that only had a single use.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit c6f935eba5)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-22 09:54:50 +02:00
aa44c436d7 Merge pull request #6333 from thaJeztah/28.x_fix_plugin_tests
[28.x] e2e/testutils: fix incorrect use of PluginConfigInterface
2025-08-20 15:29:46 -07:00
39e1213615 e2e/testutils: fix incorrect use of PluginConfigInterface
This code was using the type incorrectly; current versions of the
API MarshalText ignore this mistake, but the moby/moby/api module
produces an error:

    === Failed
    === FAIL: e2e/global TestPromptExitCode/plugin_install (0.28s)
        cli_test.go:203: assertion failed: error is not nil: json: error calling MarshalText for type plugin.CapabilityID: capability "docker.dummy/1.0" cannot contain a dot

    === FAIL: e2e/global TestPromptExitCode/plugin_upgrade (0.26s)
        cli_test.go:203: assertion failed: error is not nil: json: error calling MarshalText for type plugin.CapabilityID: capability "docker.dummy/1.0" cannot contain a dot

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 22:00:06 +02:00
5184f2ed65 Merge pull request #6332 from thaJeztah/28.x_deprecate_prompt_utils
[28.x] cli/command: deprecate prompt utilities that were for internal use
2025-08-20 11:55:06 -07:00
cb42a72704 cli/command: deprecate prompt utilities that were for internal use
- The `DisableInputEcho` and `PromptForInput` utilities were added in
  c15ade0c64 as part of a bug-fix, which
  was part of v28.x. [There are no (publicly visible) users][1] of either.
- The `ErrPromptTerminated` was added in v26.x (originally added in
  10bf91a02d, later updated in commit
  7c722c08d0. [It is not used][2]
- The `PromptForConfirmation` was added in [moby@280c872] (docker v1.13.0)
  as part of the `docker <object> prune` subcommands. It was meant for
  internal use but exported to allow re-using it in the `container`,
  `image` (etc.) packages. However, a breaking change to its signature
  was made in 10bf91a02d. It currently
  does [not appear to have any (public) users][2].

This patch deprecates the `ErrPromptTerminated`, `DisableInputEcho`,
`PromptForInput`, and `PromptForConfirmation` utilities from the
`cli/command` package. The core functionality of these is still
available in the `internal/prompt` package, which we may make
public at some point, but still needs some refining / decoupling.

[moby@280c872]: 280c872366
[1]: https://grep.app/search?f.lang=Go&regexp=true&q=%5C.%28DisableInputEcho%7CPromptForInput%29%5C%28
[2]: https://grep.app/search?f.lang=Go&q=%5C.ErrPromptTerminated
[3]: https://grep.app/search?f.lang=Go&q=.PromptForConfirmation%28

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 18:04:22 +02:00
5ef48d620d Merge pull request #6331 from thaJeztah/28.x_backport_issue_6188
[28.x backport] refactor(cli/compose/loader): extract ParseVolume() to its own package
2025-08-20 17:27:05 +02:00
9e08776681 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>
(cherry picked from commit ef7fd8bb67)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 16:52:12 +02:00
85512e35cd Merge pull request #6312 from thaJeztah/28.x_backport_deprecate_cobra_commands
[28.x backport] un-export and deprecate cobra commands
2025-08-20 15:55:43 +02:00
ce242b0ee8 Unexport trust commands
This patch deprecates exported trust commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- trust.NewTrustCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit bd8e3e4440)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 14:20:43 +02:00
ae3ee9b47b Unexport plugin commands
This patch deprecates exported plugin commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- plugin.NewPluginCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit c6b7268932)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 14:20:32 +02:00
733762af0a Unexport swarm commands
This patch deprecates exported swarm commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- swarm.NewSwarmCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit bf39340294)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 14:20:16 +02:00
46862878f7 Unexport registry commands
This patch deprecates exported registry commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- registry.NewLoginCommand
- registry.NewLogoutCommand
- registry.NewSearchCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit d4588c711c)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 13:45:11 +02:00
4a2b024c57 Unexport stack commands
This patch deprecates exported stack commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- stack.NewStackCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 630fe430ff)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 13:41:28 +02:00
82de0590b6 Unexport context command
This patch deprecates exported context commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- context.NewContextCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 3b0edc794c)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 13:41:25 +02:00
3e36fa624a Unexport volume commands
This patch deprecates exported volume commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- volume.NewVolumeCommand
- volume.NewPruneCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 9961e39d40)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 13:19:17 +02:00
01ea3a7da7 Unexport service commands
This patch deprecates exported service commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- service.NewServiceCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 88178eda32)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:58:33 +02:00
0f2721ee4f Unexport secret commands
This patch deprecates exported secret commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- secrets.NewSecretCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit e00762ed7d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:55:01 +02:00
6fc62cf5b6 Unexport manifest command
This patch deprecates exported manifest commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- manifest.NewManifestCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 02fda07211)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:54:49 +02:00
c580c9741e Unexport node commands
This patch deprecates exported node commands and moves the implementation
details to an unexported function.

Commands that are affected include:

- node.NewNodeCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit ab3fcf9f9b)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:54:38 +02:00
ba8b22e783 Unexport network commands
This patch deprecates exported network commands and moves the
implementation details to an unexported function.

Commands that are affected include:

- network.NewNetworkCommand
- network.NewPruneCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 78a8856c14)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:54:20 +02:00
def5bfc11c Unexport system commands
This patch deprecates exported system commands and moves the
implementation details to an unexported function.

Commands that are affected include:

- system.NewVersionCommand
- system.NewInfoCommand
- system.NewSystemCommand
- system.NewEventsCommand
- system.NewInspectCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit cfb8cb91f2)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:37:17 +02:00
9d258edf27 Unexport image commands
This patch deprecates exported image commands and moves the
implementation details to an unexported function.

Commands that are affected include:

- image.NewBuildCommand
- image.NewPullCommand
- image.NewPushCommand
- image.NewImagesCommand
- image.NewImageCommand
- image.NewHistoryCommand
- image.NewImportCommand
- image.NewLoadCommand
- image.NewRemoveCommand
- image.NewSaveCommand
- image.NewTagCommand
- image.NewPruneCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit e66a1456d3)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:37:17 +02:00
f68a9a06fe Unexport container commands
This patch deprecates exported container commands and moves the
implementation details to an unexported function.

Commands that are affected include:
- container.NewRunCommand
- container.NewExecCommand
- container.NewPsCommand
- container.NewContainerCommand
- container.NewAttachCommand
- container.NewCommitCommand
- container.NewCopyCommand
- container.NewCreateCommand
- container.NewDiffCommand
- container.NewExportCommand
- container.NewKillCommand
- container.NewLogsCommand
- container.NewPauseCommand
- container.NewPortCommand
- container.NewRenameCommand
- container.NewRestartCommand
- container.NewRmCommand
- container.NewStartCommand
- container.NewStatsCommand
- container.NewStopCommand
- container.NewTopCommand
- container.NewUnpauseCommand
- container.NewUpdateCommand
- container.NewWaitCommand
- container.NewPruneCommand

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 38595fecb6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:37:17 +02:00
60caaa39e0 Unexport config command
This patch unexports the `config` command.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit cce29da061)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:37:17 +02:00
c94245da66 Unexport checkpoint command
This patch unexports the `checkpoint` command.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 3265cead1d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:37:16 +02:00
79c03dcaaf Unexport the builder command and bake stub command
This patch unexports the `builder` and `bake` stub command and it adds
deprecation notices on the exported functions.

It also registers the commands using the new `cli/internal/commands`
package when the init function executes.

Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
(cherry picked from commit 1b9d0762a5)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-20 12:37:16 +02:00
acb019a344 Merge pull request #6311 from thaJeztah/28.x_backport_deprecate_platform_flags
[28.x backport] cli/command: remove `AddTrustSigningFlags`, `AddTrustVerificationFlags`, `AddPlatformFlag` utilities
2025-08-20 12:04:45 +02:00
5a80c3e98d Merge pull request #6315 from thaJeztah/28.x_backport_auth_cleanups
[28.x backport] cli/command: fix godoc links and inline resolveAuthConfigFromImage
2025-08-20 11:58:27 +02:00
e250694a35 Merge pull request #6313 from thaJeztah/28.x_backport_internalize_registryclient
[28.x backport] cli/registry/client: deprecate and move internal
2025-08-20 11:58:05 +02:00
942eade165 cli/command: inline resolveAuthConfigFromImage
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 4286883b95)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 23:42:44 +02:00
a746a99d97 cli/command: fix godoc links
- Use versioned links to github.com/docker/docker packages
- Fix links to RFC 4648, section 5

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 2d3b0b33b4)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 23:42:44 +02:00
66c3dbdfed cli/registry/client: deprecate and move internal
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 13010ba673)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 22:37:33 +02:00
cf44e3164b Merge pull request #6310 from thaJeztah/28.x_backport_rm_decodeauthconfig
[28.x backport] cli/command: TestRetrieveAuthTokenFromImage: don't decode authconfig
2025-08-19 11:30:51 -07:00
ce3196c726 Merge pull request #6309 from thaJeztah/28.x_backport_docs
[28.x backport] docs/deprecated: legacy links env vars
2025-08-19 11:19:41 -07:00
80884714de cli/command: remove AddPlatformFlag utility
It was only used internally and has no external users. It should not be
used for new uses, because it also adds a minimum API version constraint
and a default from env-var, which must be evaluated for each individual
use of such flags.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 7026e68a71)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:35:03 +02:00
4e00c31c71 cli/command: remove AddTrustVerificationFlags
It was only used internally; inline it where used.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit c0fbbe05ca)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:35:03 +02:00
7126bf7d22 [28.x] remove some uses of AddTrustVerificationFlags
These were already removed in master, so adding an extra commit
in the 28.x branch to remove their use.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:34:56 +02:00
53ed958805 cli/command: remove AddTrustSigningFlags
it was only used internally in a single location, so inline the
code where it's used.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 8c22927978)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:17:52 +02:00
be307b2925 cli/command: TestRetrieveAuthTokenFromImage: don't decode authconfig
Rewrite the test to not depend on registry.DecodeAuthConfig, which
may be moved internal to the daemon as part of the modules transition.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit ae1727c41e)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:12:39 +02:00
8f8d39c35e docs: deprecated: fix formatting of deprecated/removed in
- Use sentence-case to follow our docs guidelines.
- Add newlines to prevent these being rendered on a
  single line.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 1d571d178d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:09:18 +02:00
c61c0cdb3c docs/deprecated: legacy links env vars
Signed-off-by: Albin Kerouanton <albinker@gmail.com>
Co-authored-by: Sebastiaan van Stijn <github@gone.nl>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5c76f7f2d8)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 18:05:08 +02:00
830b5f1d2f Merge pull request #6308 from thaJeztah/28.x_backport_mountrecursive
[28.x] docs: add deprecated `bind-nonrecursive` option for `--mount`
2025-08-19 08:06:35 -07:00
abfc1f4c76 Merge pull request #6307 from thaJeztah/28.x_bump_gha
[28.x backport] build(deps): bump actions/checkout from 4 to 5
2025-08-19 08:03:23 -07:00
31fa40cb25 docs: add deprecated bind-nonrecursive option for --mount
The `bind-nonrecursive` option was replaced with the [`bind-recursive`]
option (see [cli-4316], [cli-4671]), but the deprecated docs was not
updated to mention.

Based on abfe4d4629 in master

[`bind-recursive`]: https://docs.docker.com/engine/storage/bind-mounts/#recursive-mounts
[cli-4316]: https://github.com/docker/cli/pull/4316
[cli-4671]: https://github.com/docker/cli/pull/4671

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit abfe4d4629)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 16:49:51 +02:00
4881921784 build(deps): bump actions/checkout from 4 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
(cherry picked from commit f2af519f2e)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-19 16:32:19 +02:00
4313a2bbb7 Merge pull request #6294 from thaJeztah/28.x_backport_progress_test
[28.x] cli/command/container: TestRunPullTermination: rewrite with streamformatter
2025-08-19 13:04:32 +02:00
20c34ef13b Merge pull request #6292 from thaJeztah/28.x_backport_deprecate_opts
[28.x backport] opts: deprecate NewNamedListOptsRef, NewNamedMapOpts
2025-08-19 12:50:57 +02:00
34a90bdd81 Merge pull request #6298 from thaJeztah/28.x_backport_plugin_manager_more_deprecations
[28.x backport] cli-plugins/manager: deprecate annotation metadata aliases
2025-08-19 12:50:08 +02:00
98b82d5156 cli-plugins/manager: deprecate annotation metadata aliases
These aliases were added in 292713c887
(part of v28.0), but did not deprecate them. They are no longer used
in the CLI itself, but may be used by cli-plugin implementations.

This deprecates the aliases in `cli-plugins/manager` in favor of
their equivalent in `cli-plugins/manager/metadata`:

- `CommandAnnotationPlugin`
- `CommandAnnotationPluginVendor`
- `CommandAnnotationPluginVersion`
- `CommandAnnotationPluginInvalid`
- `CommandAnnotationPluginCommandPath`

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 72f76f2720)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-18 21:54:05 +02:00
0e474e38f1 [28.x] cli/command/container: TestRunPullTermination: rewrite with streamformatter
This makes the test slightly closer to the actual code in the daemon producing
the progress response;
cd844fd0b2/daemon/images/image_pull.go (L58-L70)
cd844fd0b2/daemon/internal/distribution/utils/progress.go (L14-L34)

This is a modified version of 69854c4e08
with some changes specific to the 28.x branch (the variant on master
had some patches for the moby/api and moby/client transition).

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 69854c4e08)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-18 19:17:14 +02:00
6adde56036 Merge pull request #6291 from thaJeztah/28.x_backport_deprecate_quoted_values
[28.x backport] Deprecate special handling for quoted values for TLS flags
2025-08-18 18:35:07 +02:00
7ccd6d29c6 opts: deprecate NewNamedListOptsRef, NewNamedMapOpts
The `NewNamedListOptsRef`, `NewNamedMapOpts` and related `NamedListOpts`,
`NamedMapOpts`, and `NamedOption` interface were added in [moby@677a6b3],
which added support for a `daemon.json` configuration file. That change
required a way to correlate command-line flags with their corresponding
fields in the `daemon.json` to detect conflicting options. At the time,
the CLI and daemon were produced from the same code, and shared packages
for command-line options, but when the CLI was moved to a separate
repository, these options were inherited.

[moby@677a6b3]: 677a6b3506

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 6f0c66c152)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-18 18:28:48 +02:00
14f297204f Merge pull request #6289 from thaJeztah/28.x_backport_hosts_regular_stringarray
[28.x backport] cli/flags: add "hostVar" to handle --host / -H as a single string
2025-08-18 18:28:25 +02:00
d1617cb0c0 Deprecate special handling for quoted values for TLS flags
The `--tlscacert`, `--tlscert`, and `--tlskey` command-line flags had
non-standard behavior for handling values contained in quotes (`"` or `'`).
Normally, quotes are handled by the shell, for example, in the following
example, the shell takes care of handling quotes before passing the values
to the `docker` CLI:

    docker --some-option "some-value-in-quotes" ...

However, when passing values using an equal sign (`=`), this may not happen
and values may be handled including quotes;

    docker --some-option="some-value-in-quotes" ...

This caused issues with "Docker Machine", which used this format as part
of its `docker-machine config` output, and the CLI carried special, non-standard
handling for these flags.

Docker Machine reached EOL, and this special handling made the processing
of flag values inconsistent with other flags used, so this behavior is
deprecated. Users depending on this behavior are recommended to specify
the quoted values using a space between the flag and its value, as illustrated
above.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit ee05a71513)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-18 18:18:04 +02:00
7091e8bea4 cli/flags: add "hostVar" to handle --host / -H as a single string
hostVar is used for the '--host' / '-H' flag to set [ClientOptions.Hosts].
The [ClientOptions.Hosts] field is a slice because it was originally shared
with the daemon config. However, the CLI only allows for a single host to
be specified.

hostVar presents itself as a "string", but stores the value in a string
slice. It produces an error when trying to set multiple values, matching
the check in [getServerHost].

[getServerHost]: 7eab668982/cli/command/cli.go (L542-L551)

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit f14eeeb361)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-18 17:12:54 +02:00
ff42ff9f06 cli/flags: use a regular StringArray for the --host / -H flag
The ClientOptions struct and related flags were inherited from the Moby
repository, where originally the CLI and Daemon used the same implementation
and had a "Common" options struct. When the CLI moved to a separate repository,
those structs were duplicated, but some daemon-specific logic remained. For
example, the daemon can be configured to listen on multiple ports and sockets
([moby@dede158]), but the CLI [can only connect to a single host][1]. The
daemon config also had to account for flags conflicting with `daemon.json`,
and use special flag-vars for this ([moby@677a6b3]).

Unfortunately, the `ClientConfig` struct became part of the public API and
is used as argument in various places, but we can remove the use of the
special flag var. This patch replaces the use of `NewNamedListOptsRef`
for a regular `StringArray`.

Unfortunately this changes the flag's type description from `list` to
`stringArray`, but we can look at changing that separately.

[moby@dede158]: dede1585ee
[1]: 0af135e906/docker/docker.go (L191-L193)
[moby@677a6b3]: 677a6b3506

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5ee2906e78)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-18 17:11:54 +02:00
bcc479b4c3 Merge pull request #6276 from thaJeztah/28.x_backport_cli_internalize_utils
[28.x backport] cli: deprecate VisitAll, DisableFlagsInUseLine utilities, remove HasCompletionArg
2025-08-18 11:41:10 +02:00
6a596c007c Merge pull request #6269 from thaJeztah/28.x_backport_plugin_manager_unexport
[28.x backport] cli-plugins/manager: various fixes and deprecations
2025-08-18 11:24:41 +02:00
79e0b1d7d9 cli-plugins/manager: remove deprecated ResourceAttributesEnvvar
This const was deprecated in 9dc175d6ef,
which is part of v28.0, so let's remove it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 513ceeec0a)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:54 +02:00
099820d8ca cli-plugins/manager: deprecate metadata aliases
These aliases were added in 4321293972
(part of v28.0), but did not deprecate them. They are no longer used
in the CLI itself, but may be used by cli-plugin implementations.

This deprecates the aliases in `cli-plugins/manager` in favor of
their equivalent in `cli-plugins/manager/metadata`:

- `NamePrefix`
- `MetadataSubcommandName`
- `HookSubcommandName`
- `Metadata`
- `ReexecEnvvar`

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5876b2941c)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:53 +02:00
ac88b74462 cli-plugins/manager: wrapAsPluginError: don't special-case nil
This was a pattern inheritted from pkg/errors.Wrapf, which ignored
nil errors for convenience. However, it is error-prone, as it is
not obvious when returning a nil-error.

All call-sites using `wrapAsPluginError` already do a check for
nil errors, so remove this code to prevent hard to find bugs.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 50963accec)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:53 +02:00
7f699066bd cli-plugins/manager: pluginError: remove Causer interface
We no longer depend on this interface and it implements Unwrap for
native handling by go stdlib.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit d789bac04a)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:53 +02:00
fe1d790d8e cli-plugins/manager: deprecate "IsNotFound"
These errors satisfy errdefs.IsNotFound, so make it a wrapper, and
deprecate it.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 71460215d3)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:53 +02:00
5e29918a44 cli-plugins/manager: un-export "NewPluginError"
It is for internal use, and no longer needed for testing, now that
the `Plugin` type handles marshalling errors.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 1cc698c68f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:53 +02:00
09efe3f408 cli-plugins/manager: fix Plugin marshaling with regular errors
Go does not by default marshal `error` type fields to JSON. The manager
package therefore implemented a `pluginError` type that implements
[encoding.TextMarshaler]. However, the field was marked as a regular
`error`, which made it brittle; assining any other type of error would
result in the error being discarded in the marshaled JSON (as used in
`docker info` output), resulting in the error being marshaled as `{}`.

This patch adds a custom `MarshalJSON()` on the `Plugin` type itself
so that any error is rendered. It checks if the error used already
implements [encoding.TextMarshaler], otherwise wraps the error in
a `pluginError`.

[encoding.TextMarshaler]: https://pkg.go.dev/encoding#TextMarshaler

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 549d39a89f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:52 +02:00
79dd3a3c79 cli-plugins/manager: un-export "Candidate" interface
It is for internal use for mocking purposes, and is not part
of any public interface / signature.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 54367b3283)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-17 19:44:49 +02:00
a8fe4aaa7f Merge pull request #6272 from thaJeztah/28.x_backport_errdefs_unalias
[28.x backport] remove aliases for containerd/errdefs, disallow docker/errdefs
2025-08-16 15:34:43 -07:00
034dc932d7 remove aliases for containerd/errdefs, disallow docker/errdefs
We transitioned most functionality of docker/errdefs to containerd
errdefs module, and the docker/errdefs package should no longer be
used.

Because of that, there will no longer be ambiguity, so we can remove
the aliases for this package, and use it as "errdefs".

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 89d8c8a2a7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-16 18:29:23 +02:00
0718529a7e Merge pull request #6221 from thaJeztah/28.x_fork_registry
[28.x] add internal fork of docker/docker/registry
2025-08-16 08:04:59 -07:00
c754ac3c5b Merge pull request #6280 from thaJeztah/28.x_backport_deprecate_ValidateHost
[28.x backport] opts: deprecate ValidateHost utility
2025-08-16 07:21:56 -07:00
5d327e8032 Merge pull request #6277 from thaJeztah/28.x_backport_fix_prune_example
[28.x backport] docs: fix output example for docker system prune
2025-08-16 07:20:24 -07:00
bce66f6126 Merge pull request #6275 from thaJeztah/28.x_backport_deprecate_quotedstring
[28.x backport] opts: deprecate QuotedString
2025-08-15 13:20:06 -07:00
511821052a opts: deprecate ValidateHost utility
The `ValidateHost` option was introduced in [moby@1ba1138] to be used
as validation func for the `--host` flag on the daemon in and CLI in
[moby@5e3f6e7], but is no longer used since [cli@6f61cf0]. which added
support for `ssh://` connections, and required validation elsewhere.

[moby@1ba1138]: 1ba11384bf
[moby@5e3f6e7]: 5e3f6e7023
[cli@6f61cf0]: 6f61cf053a

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit d0ac0acff0)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 22:18:29 +02:00
9fc26d43ed Merge pull request #6278 from thaJeztah/28.x_backport_update-golang-1.24.6
[28.x backport] update to go1.24.6
2025-08-15 13:06:03 -07:00
2b4e0a0f45 update to go1.24.6
- https://github.com/golang/go/issues?q=milestone%3AGo1.24.6+label%3ACherryPickApproved
- full diff: golang/go@go1.24.5...go1.24.6

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

- os/exec: LookPath may return unexpected paths

If the PATH environment variable contains paths which are executables (rather
than just directories), passing certain strings to LookPath ("", ".", and ".."),
can result in the binaries listed in the PATH being unexpectedly returned.

Thanks to Olivier Mengué for reporting this issue.

This is CVE-2025-47906 and Go issue https://go.dev/issue/74466.

- database/sql: incorrect results returned from Rows.Scan

Cancelling a query (e.g. by cancelling the context passed to one of the query
methods) during a call to the Scan method of the returned Rows can result in
unexpected results if other queries are being made in parallel. This can result
in a race condition that may overwrite the expected results with those of
another query, causing the call to Scan to return either unexpected results
from the other query or an error.

We believe this affects most database/sql drivers.

Thanks to Spike Curtis from Coder for reporting this issue.

This is CVE-2025-47907 and https://go.dev/issue/74831.

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

Signed-off-by: Austin Vazquez <austin.vazquez@docker.com>
(cherry picked from commit 6769f62746)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 19:16:22 +02:00
5d6e64c4a6 docs: fix output example for docker system prune
The example shows that the `--volumes` option is used, which in current
versions of docker only removes "anonymous" volumes, but preserves named
volume:

    $ docker system prune -a --volumes
    ...
            - all anonymous volumes not used by at least one container
    ...

But the example output showed that a named volume ("named-vol") was
deleted;

    Deleted Volumes:
    named-vol

Co-authored-by: Roberto Villarreal <rrjjvv@yahoo.com>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit bf13010df8)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 19:13:57 +02:00
ed52ada4a3 cmd/docker: fix some minor linting issues
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5a38118956)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 19:11:17 +02:00
60d16e20ac cli: deprecate VisitAll, DisableFlagsInUseLine utilities
These utilities were only used internally; create a local copy
where used, and deprecate the ones in cli.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 6bd8a4b2b5)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 19:11:17 +02:00
713ed839fe cli: remove HasCompletionArg utility
It was only used in a single place and has no external consumers.
Move it to where it's used to keep things together.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5a99022556)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 19:11:17 +02:00
6bfee62d6d opts: deprecate QuotedString
The `QuotedString` option was added in [moby@e4c1f07] and [moby@abe32de]
to work around a regression in Docker 1.13 that caused `docker-machine`
to fail. `docker-machine` produced instructions on how to set up a cli
to connect to the Machine it produced. These instructions used quotes
around the paths for TLS certificates, but with an `=` for the flag's
values instead of a space; due to this the shell would not handle
stripping quotes, so the CLI would now get the value including quotes.

Preserving quotes in such cases is expected (and standard behavior), but
versions of Docker before 1.13 used a custom "mflag" package for flag
parsing, and that package contained custom handling for quotes (added
in [moby@0e9c40e]).

For other flags, this problem could be solved by the user, but as these
instructions were produced by `docker-machine`'s `config` command, an
exception was made for the `--tls-xxx` flags. From [moby-29761]:

> The flag trimming behaviour is really unusual, and I would say unexpected.
> I think removing it is generally the right idea. Since we have one very
> common case where it's necessary for backwards compatibility we need to
> add a special case, but I don't think we should apply that case to every
> flag.

The `QuotedString` implementation has various limitations, as it doesn't
follow the same handling of quotes as a shell would.

Given that Docker Machine reached EOL a long time ago and other options,
such as `docker context`, have been added to configure the CLI to connect
to a specific host (with corresponding TLS configuration), we should remove
the special handling for these flags, as it's inconsitent with all other
flags, and not worth maintaining for a tool that no longer exists.

This patch deprecates the `QuotedString` option and removes its use. A
temporary, non-exported copy is added, but will be removed in the next
release.

[moby-29761]: https://github.com/moby/moby/issues/29761#issuecomment-270211265
[moby@e4c1f07]: e4c1f07729
[moby@abe32de]: abe32de6b4
[moby@0e9c40e]: 0e9c40eb82
[moby@c79a169]: c79a169a35

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 187a942a88)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 19:07:52 +02:00
efdf008933 internal/registry: remove RepositoryInfo, add NewIndexInfo
Most places only use IndexInfo (and may not even need that), so replace
the use of ParseRepositoryInfo for NewIndexInfo, and move the RepositoryInfo
type to the trust package, which uses it as part of its ImageRefAndAuth
struct.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 21e8bbc8a2)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:49 +02:00
28ffe2416d internal/registry: ParseRepositoryInfo: remove unused error return
Removed the error return from the `ParseRepositoryInfo` function.
There are no validation steps inside `ParseRepositoryInfo` which
could cause an error, so we always returned a nil error.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 86b5b528a6)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:49 +02:00
b0bb4acc11 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>
(cherry picked from commit f907c7a4b0)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:49 +02:00
2e5a36728b cli/command/system: remove use of Mirrors field in test
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit cd277a5815)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:49 +02:00
a5a17eb2c7 internal/registry: remove pkg/errors
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit c297770d2d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:48 +02:00
e1f79927f3 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>
(cherry picked from commit 219cfc8b7d)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:48 +02:00
cab6012db9 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>
(cherry picked from commit 2607ba8062)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:48 +02:00
75a4cbbf8e 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>
(cherry picked from commit 5322affc9f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:48 +02:00
9071d3868c internal/registry: remove NewStaticCredentialStore
It was only used in a single place; inline it there.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit dc41365b56)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:48 +02:00
e7f4f04156 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>
(cherry picked from commit dad2e67860)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:48 +02:00
7e01a3a8a9 internal/registry: Service.Auth remove unused statusmessage return
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 7cf245d2f7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:47 +02:00
72f85ccd16 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>
(cherry picked from commit e0b351b3d9)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:47 +02:00
ecd54bc6dd internal/registry: remove dead code
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 7716219e17)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:47 +02:00
8b9baffdf7 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>
(cherry picked from commit f6b90bc253)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:47 +02:00
93a51c39f4 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>
(cherry picked from commit e504faf6da)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-15 15:45:45 +02:00
2dc9daae32 Merge pull request #6265 from thaJeztah/28.x_backport_fork_remotecontext
[28.x backport] add local fork of github.com/docker/docker/builder/remotecontext
2025-08-15 05:51:05 -07:00
a4f8f22a33 Merge pull request #6190 from thaJeztah/fork_remotecontext
add local fork of github.com/docker/docker/builder/remotecontext

(cherry picked from commit 8c317ad3fd)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-14 21:50:07 +02:00
7d3bde083c 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>
(cherry picked from commit 260f1dbebb)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-14 21:50:07 +02:00
32207833d0 Merge pull request #6262 from thaJeztah/28.x_backport_no_pkg_process
[28.x backport] cli/connhelper: remove dependency on pkg/process
2025-08-14 21:49:42 +02:00
7399781944 cli/connhelper: remove dependency on pkg/process
This package will not be included in the api or client modules, and
we're currently only using a single function of it, and only the
unix implementation, so let's fork it for now (although the package
may be moved to moby/sys).

This removes the last dependency on github.com/docker/docker.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 2abcbf842f)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-14 18:45:43 +02:00
efee5879a1 Merge pull request #6264 from thaJeztah/28.x_merge_28.3.3
[28.x] merge v28.3.3 tag into v28.x
2025-08-14 18:42:32 +02:00
b82e19efe0 [28.x] merge v28.3.3 tag into v28.x
The v28.3.3 tag was created from master, but the v28.x branch
wasn't fast-forwarded, and PR's merged after that. This should
bring the v28.3.3 tag's changes into the v28.x branch.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-14 17:45:14 +02:00
eceff3dbc5 Merge pull request #6256 from thaJeztah/28.x_backport_remove_prompt_privilege_func
[28.x backport] cli/command: remove interactive login prompt from docker push/pull, deprecate RegistryAuthenticationPrivilegedFunc
2025-08-14 14:43:15 +02:00
3598fc3745 Merge pull request #6259 from thaJeztah/28.x_backport_rm_completion
[28.x backport] cli/command/completion: remove deprecated ValidArgsFn
2025-08-14 10:51:34 +02:00
2df466710b Merge pull request #6258 from thaJeztah/28.x_backport_remove_RepoNameForReference
[28.x backport] cli/registry/client: remove deprecated RepoNameForReference
2025-08-14 10:22:59 +02:00
29f2ce760a Merge pull request #6257 from thaJeztah/28.x_backport_remove_deprecated
[28.x backport] cli/command: remove deprecated CopyToFile, ConfigureAuth utilities
2025-08-14 10:22:07 +02:00
363f4c0031 cli/command/completion: remove deprecated ValidArgsFn
This was deprecated in 9f19820f88, which
is part of v28.x, and unlikely used externally.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 5052a39915)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-13 18:06:23 +02:00
6d4ffec3fb 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>
(cherry picked from commit a87bde0068)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-13 18:02:48 +02:00
5c1cee4630 cli/command: remove deprecated ConfigureAuth utility
It was deprecated in 6e4818e7d6, which
is part of v28.x and backported to v27.x.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit 22cc0e90ae)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-13 17:54:06 +02:00
88274f4805 cli/command: remove deprecated CopyToFile utility
It was deprecated in 7cc6b8ebf4, which is
part of v28.x

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
(cherry picked from commit de54347518)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-13 17:53:58 +02:00
5566c3a9b8 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>
(cherry picked from commit 29263e865b)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-13 17:38:45 +02:00
5edc6748f4 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>
(cherry picked from commit 2b56b66b10)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-08-13 17:38:29 +02:00
6007e83a75 Merge pull request #6218 from thaJeztah/28.x_bump_deps
[28.x] vendor: github.com/docker/docker v28.3.3, github.com/opencontainers/image-spec v1.1.1
2025-07-29 20:17:56 +02:00
ce2a0a4ecb vendor: github.com/opencontainers/image-spec v1.1.1
full diff: https://github.com/opencontainers/image-spec/compare/v1.1.0...v1.1.1

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-29 18:10:03 +02:00
3cd108fcd0 vendor: github.com/docker/docker v28.3.3
full diff: https://github.com/docker/docker/compare/v28.3.1...v28.3.3

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-07-29 18:09:24 +02:00
416 changed files with 6188 additions and 5682 deletions

View File

@ -35,7 +35,7 @@ jobs:
steps:
-
name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
-
name: Create matrix
id: platforms
@ -88,7 +88,7 @@ jobs:
fi
-
name: Upload artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: ${{ env.ARTIFACT_NAME }}
path: /tmp/out/*
@ -143,7 +143,7 @@ jobs:
steps:
-
name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
-
name: Create matrix
id: platforms

View File

@ -46,7 +46,7 @@ jobs:
steps:
-
name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 2
# CodeQL 2.16.4's auto-build added support for multi-module repositories,
@ -61,19 +61,19 @@ jobs:
ln -s vendor.sum go.sum
-
name: Update Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: "1.24.5"
go-version: "1.24.9"
-
name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v4
with:
languages: go
-
name: Autobuild
uses: github/codeql-action/autobuild@v3
uses: github/codeql-action/autobuild@v4
-
name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v4
with:
category: "/language:go"

View File

@ -39,12 +39,11 @@ jobs:
engine-version:
- 28 # latest
- 27 # latest - 1
- 26 # github actions default
- 23 # mirantis lts
- 25 # mirantis lts
steps:
-
name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
-
name: Update daemon.json
run: |

View File

@ -53,20 +53,21 @@ jobs:
fail-fast: false
matrix:
os:
- macos-13 # macOS 13 on Intel
- macos-14 # macOS 14 on arm64 (Apple Silicon M1)
- macos-14 # macOS 14 on arm64 (Apple Silicon M1)
- macos-15-intel # macOS 15 on Intel
- macos-15 # macOS 15 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: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
path: ${{ env.GOPATH }}/src/github.com/docker/cli
-
name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: "1.24.5"
go-version: "1.24.9"
-
name: Test
run: |

View File

@ -48,7 +48,7 @@ jobs:
steps:
-
name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
-
name: Generate
shell: 'script --return --quiet --command "bash {0}"'
@ -74,7 +74,7 @@ jobs:
steps:
-
name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
-
name: Run
shell: 'script --return --quiet --command "bash {0}"'

View File

@ -5,7 +5,7 @@ run:
# 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"
go: "1.24.9"
timeout: 5m
@ -86,6 +86,8 @@ linters:
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/errdefs"
desc: Use github.com/containerd/errdefs instead.
- pkg: "github.com/docker/docker/pkg/system"
desc: This package should not be used unless strictly necessary.
- pkg: "github.com/docker/distribution/uuid"
@ -124,10 +126,9 @@ linters:
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
# Should no longer be aliased, because we no longer allow moby/docker errdefs.
- pkg: "github.com/docker/docker/errdefs"
alias: ""
- pkg: github.com/opencontainers/image-spec/specs-go/v1
alias: ocispec
# Enforce that gotest.tools/v3/assert/cmp is always aliased as "is"
@ -221,6 +222,14 @@ linters:
linters:
- staticcheck
# Ignore deprecation linting for cli/command/stack/*.
#
# FIXME(thaJeztah): remove exception once these functions are un-exported or internal; see https://github.com/docker/cli/pull/6389
- text: '^(SA1019): '
path: "cli/command/stack"
linters:
- staticcheck
# Log a warning if an exclusion rule is unused.
# Default: false
warn-unused: true

View File

@ -8,13 +8,13 @@ ARG BASE_VARIANT=alpine
ARG ALPINE_VERSION=3.21
ARG BASE_DEBIAN_DISTRO=bookworm
ARG GO_VERSION=1.24.5
ARG GO_VERSION=1.24.9
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
ARG GOTESTSUM_VERSION=v1.13.0
# 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
@ -31,7 +31,7 @@ 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

View File

@ -1 +1 @@
28.3.0-dev
28.4.0-dev

View File

@ -6,25 +6,35 @@ 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.
//
// Deprecated: use [metadata.CommandAnnotationPlugin]. This alias will be removed in the next release.
CommandAnnotationPlugin = metadata.CommandAnnotationPlugin
// CommandAnnotationPluginVendor is added to every stub command
// added by AddPluginCommandStubs and contains the vendor of
// that plugin.
//
// Deprecated: use [metadata.CommandAnnotationPluginVendor]. This alias will be removed in the next release.
CommandAnnotationPluginVendor = metadata.CommandAnnotationPluginVendor
// CommandAnnotationPluginVersion is added to every stub command
// added by AddPluginCommandStubs and contains the version of
// that plugin.
//
// Deprecated: use [metadata.CommandAnnotationPluginVersion]. This alias will be removed in the next release.
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.
//
// Deprecated: use [metadata.CommandAnnotationPluginInvalid]. This alias will be removed in the next release.
CommandAnnotationPluginInvalid = metadata.CommandAnnotationPluginInvalid
// CommandAnnotationPluginCommandPath is added to overwrite the
// command path for a plugin invocation.
//
// Deprecated: use [metadata.CommandAnnotationPluginCommandPath]. This alias will be removed in the next release.
CommandAnnotationPluginCommandPath = metadata.CommandAnnotationPluginCommandPath
)

View File

@ -6,12 +6,6 @@ import (
"github.com/docker/cli/cli-plugins/metadata"
)
// Candidate represents a possible plugin candidate, for mocking purposes
type Candidate interface {
Path() string
Metadata() ([]byte, error)
}
type candidate struct {
path string
}

View File

@ -32,14 +32,12 @@ func (c *fakeCandidate) Metadata() ([]byte, error) {
func TestValidateCandidate(t *testing.T) {
const (
goodPluginName = metadata.NamePrefix + "goodplugin"
builtinName = metadata.NamePrefix + "builtin"
builtinAlias = metadata.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"
goodPluginPath = "/usr/local/libexec/cli-plugins/" + goodPluginName
metaExperimental = `{"SchemaVersion": "0.1.0", "Vendor": "e2e-testing", "Experimental": true}`
badPrefixPath = "/usr/local/libexec/cli-plugins/wobble"
badNamePath = "/usr/local/libexec/cli-plugins/docker-123456"
goodPluginPath = "/usr/local/libexec/cli-plugins/" + goodPluginName
)
fakeroot := &cobra.Command{Use: "docker"}
@ -51,31 +49,103 @@ func TestValidateCandidate(t *testing.T) {
})
for _, tc := range []struct {
name string
c *fakeCandidate
name string
plugin *fakeCandidate
// Either err or invalid may be non-empty, but not both (both can be empty for a good plugin).
err string
invalid string
expVer string
}{
/* 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", 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"`},
{name: "fetch failure", c: &fakeCandidate{path: goodPluginPath, exec: false}, invalid: fmt.Sprintf("failed to fetch metadata: faked a failure to exec %q", goodPluginPath)},
{name: "metadata not json", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: `xyzzy`}, invalid: "invalid character"},
{name: "empty schemaversion", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{}`}, invalid: `plugin SchemaVersion "" is not valid`},
{name: "invalid schemaversion", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "xyzzy"}`}, invalid: `plugin SchemaVersion "xyzzy" is not valid`},
{name: "no vendor", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0"}`}, invalid: "plugin metadata does not define a vendor"},
{name: "empty vendor", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0", "Vendor": ""}`}, invalid: "plugin metadata does not define a vendor"},
// This one should work
{name: "valid", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0", "Vendor": "e2e-testing"}`}},
{name: "experimental + allowing experimental", c: &fakeCandidate{path: goodPluginPath, exec: true, meta: metaExperimental}},
// Invalid cases.
{
name: "empty path",
plugin: &fakeCandidate{path: ""},
err: "plugin candidate path cannot be empty",
},
{
name: "bad prefix",
plugin: &fakeCandidate{path: badPrefixPath},
err: fmt.Sprintf("does not have %q prefix", metadata.NamePrefix),
},
{
name: "bad path",
plugin: &fakeCandidate{path: badNamePath},
invalid: "did not match",
},
{
name: "builtin command",
plugin: &fakeCandidate{path: builtinName},
invalid: `plugin "builtin" duplicates builtin command`,
},
{
name: "builtin alias",
plugin: &fakeCandidate{path: builtinAlias},
invalid: `plugin "alias" duplicates an alias of builtin command "builtin"`,
},
{
name: "fetch failure",
plugin: &fakeCandidate{path: goodPluginPath, exec: false},
invalid: fmt.Sprintf("failed to fetch metadata: faked a failure to exec %q", goodPluginPath),
},
{
name: "metadata not json",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `xyzzy`},
invalid: "invalid character",
},
{
name: "empty schemaversion",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{}`},
invalid: `plugin SchemaVersion version cannot be empty`,
},
{
name: "invalid schemaversion",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "xyzzy"}`},
invalid: `plugin SchemaVersion "xyzzy" has wrong format: must be <major>.<minor>.<patch>`,
},
{
name: "invalid schemaversion major",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "2.0.0"}`},
invalid: `plugin SchemaVersion "2.0.0" is not supported: must be lower than 2.0.0`,
},
{
name: "no vendor",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0"}`},
invalid: "plugin metadata does not define a vendor",
},
{
name: "empty vendor",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0", "Vendor": ""}`},
invalid: "plugin metadata does not define a vendor",
},
// Valid cases.
{
name: "valid",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0", "Vendor": "e2e-testing"}`},
expVer: "0.1.0",
},
{
// Including the deprecated "experimental" field should not break processing.
name: "with legacy experimental",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.1.0", "Vendor": "e2e-testing", "Experimental": true}`},
expVer: "0.1.0",
},
{
// note that this may not be supported by older CLIs
name: "new minor schema version",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "0.2.0", "Vendor": "e2e-testing"}`},
expVer: "0.2.0",
},
{
// note that this may not be supported by older CLIs
name: "new major schema version",
plugin: &fakeCandidate{path: goodPluginPath, exec: true, meta: `{"SchemaVersion": "1.0.0", "Vendor": "e2e-testing"}`},
expVer: "1.0.0",
},
} {
t.Run(tc.name, func(t *testing.T) {
p, err := newPlugin(tc.c, fakeroot.Commands())
p, err := newPlugin(tc.plugin, fakeroot.Commands())
switch {
case tc.err != "":
assert.ErrorContains(t, err, tc.err)
@ -86,7 +156,7 @@ func TestValidateCandidate(t *testing.T) {
default:
assert.NilError(t, err)
assert.Equal(t, metadata.NamePrefix+p.Name, goodPluginName)
assert.Equal(t, p.SchemaVersion, "0.1.0")
assert.Equal(t, p.SchemaVersion, tc.expVer)
assert.Equal(t, p.Vendor, "e2e-testing")
}
})

View File

@ -38,6 +38,7 @@ func AddPluginCommandStubs(dockerCLI config.Provider, rootCmd *cobra.Command) (e
rootCmd.AddCommand(&cobra.Command{
Use: p.Name,
Short: p.ShortDescription,
Hidden: p.Hidden,
Run: func(_ *cobra.Command, _ []string) {},
Annotations: annotations,
DisableFlagParsing: true,

View File

@ -23,11 +23,6 @@ func (e *pluginError) Error() string {
return e.cause.Error()
}
// Cause satisfies the errors.causer interface for pluginError.
func (e *pluginError) Cause() error {
return e.cause
}
// Unwrap provides compatibility for Go 1.13 error chains.
func (e *pluginError) Unwrap() error {
return e.cause
@ -41,14 +36,11 @@ func (e *pluginError) MarshalText() (text []byte, err error) {
// wrapAsPluginError wraps an error in a pluginError with an
// additional message.
func wrapAsPluginError(err error, msg string) error {
if err == nil {
return nil
}
return &pluginError{cause: fmt.Errorf("%s: %w", msg, err)}
}
// NewPluginError creates a new pluginError, analogous to
// newPluginError creates a new pluginError, analogous to
// errors.Errorf.
func NewPluginError(msg string, args ...any) error {
func newPluginError(msg string, args ...any) error {
return &pluginError{cause: fmt.Errorf(msg, args...)}
}

View File

@ -10,7 +10,7 @@ import (
)
func TestPluginError(t *testing.T) {
err := NewPluginError("new error")
err := newPluginError("new error")
assert.Check(t, is.Error(err, "new error"))
inner := errors.New("testing")
@ -21,4 +21,7 @@ func TestPluginError(t *testing.T) {
actual, err := json.Marshal(err)
assert.Check(t, err)
assert.Check(t, is.Equal(`"wrapping: testing"`, string(actual)))
err = wrapAsPluginError(nil, "wrapping")
assert.Check(t, is.Error(err, "wrapping: %!w(<nil>)"))
}

View File

@ -2,6 +2,7 @@ package manager
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
@ -9,9 +10,11 @@ import (
"strings"
"sync"
"github.com/containerd/errdefs"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/debug"
"github.com/fvbommel/sortorder"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
@ -22,13 +25,9 @@ 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 = 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"
// Deprecated: use [metadata.ReexecEnvvar]. This alias will be removed in the next release.
ReexecEnvvar = metadata.ReexecEnvvar
)
// errPluginNotFound is the error returned when a plugin could not be found.
@ -40,15 +39,11 @@ func (e errPluginNotFound) Error() string {
return "Error: No such CLI plugin: " + string(e)
}
type notFound interface{ NotFound() }
// IsNotFound is true if the given error is due to a plugin not being found.
//
// Deprecated: use [errdefs.IsNotFound].
func IsNotFound(err error) bool {
if e, ok := err.(*pluginError); ok {
err = e.Cause()
}
_, ok := err.(notFound)
return ok
return errdefs.IsNotFound(err)
}
// getPluginDirs returns the platform-specific locations to search for plugins
@ -81,9 +76,17 @@ func addPluginCandidatesFromDir(res map[string][]string, d string) {
return
}
for _, dentry := range dentries {
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
switch mode := dentry.Type() & os.ModeType; mode { //nolint:exhaustive,nolintlint // no need to include all possible file-modes in this list
case os.ModeSymlink:
if !debug.IsEnabled() {
// Skip broken symlinks unless debug is enabled. With debug
// enabled, this will print a warning in "docker info".
if _, err := os.Stat(filepath.Join(d, dentry.Name())); errors.Is(err, os.ErrNotExist) {
continue
}
}
case 0:
// Regular file, keep going
default:
// Something else, ignore.
continue
@ -127,7 +130,7 @@ func getPlugin(name string, pluginDirs []string, rootcmd *cobra.Command) (*Plugi
if err != nil {
return nil, err
}
if !IsNotFound(p.Err) {
if !errdefs.IsNotFound(p.Err) {
p.ShadowedPaths = paths[1:]
}
return &p, nil
@ -164,7 +167,7 @@ func ListPlugins(dockerCli config.Provider, rootcmd *cobra.Command) ([]Plugin, e
if err != nil {
return err
}
if !IsNotFound(p.Err) {
if !errdefs.IsNotFound(p.Err) {
p.ShadowedPaths = paths[1:]
mu.Lock()
defer mu.Unlock()
@ -185,9 +188,9 @@ func ListPlugins(dockerCli config.Provider, rootcmd *cobra.Command) ([]Plugin, e
return plugins, nil
}
// PluginRunCommand returns an "os/exec".Cmd which when .Run() will execute the named plugin.
// PluginRunCommand returns an [os/exec.Cmd] which when [os/exec.Cmd.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.
// The error returned satisfies the [errdefs.IsNotFound] predicate if no plugin was found or if the first candidate plugin was invalid somehow.
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

View File

@ -5,6 +5,7 @@ import (
"strings"
"testing"
"github.com/containerd/errdefs"
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/internal/test"
@ -37,7 +38,7 @@ func TestListPluginCandidates(t *testing.T) {
"plugins3-target", // Will be referenced as a symlink from below
fs.WithFile("docker-plugin1", ""),
fs.WithDir("ignored3"),
fs.WithSymlink("docker-brokensymlink", "broken"), // A broken symlink is still a candidate (but would fail tests later)
fs.WithSymlink("docker-brokensymlink", "broken"), // A broken symlink is ignored
fs.WithFile("non-plugin-symlinked", ""), // This shouldn't appear, but ...
fs.WithSymlink("docker-symlinked", "non-plugin-symlinked"), // ... this link to it should.
),
@ -71,9 +72,6 @@ func TestListPluginCandidates(t *testing.T) {
"hardlink2": {
dir.Join("plugins2", "docker-hardlink2"),
},
"brokensymlink": {
dir.Join("plugins3", "docker-brokensymlink"),
},
"symlinked": {
dir.Join("plugins3", "docker-symlinked"),
},
@ -131,7 +129,7 @@ echo '{"SchemaVersion":"0.1.0"}'`, fs.WithMode(0o777)),
_, err = GetPlugin("ccc", cli, &cobra.Command{})
assert.Error(t, err, "Error: No such CLI plugin: ccc")
assert.Assert(t, IsNotFound(err))
assert.Assert(t, errdefs.IsNotFound(err))
}
func TestListPluginsIsSorted(t *testing.T) {
@ -166,8 +164,8 @@ func TestErrPluginNotFound(t *testing.T) {
var err error = errPluginNotFound("test")
err.(errPluginNotFound).NotFound()
assert.Error(t, err, "Error: No such CLI plugin: test")
assert.Assert(t, IsNotFound(err))
assert.Assert(t, !IsNotFound(nil))
assert.Assert(t, errdefs.IsNotFound(err))
assert.Assert(t, !errdefs.IsNotFound(nil))
}
func TestGetPluginDirs(t *testing.T) {

View File

@ -6,18 +6,26 @@ import (
const (
// NamePrefix is the prefix required on all plugin binary names
//
// Deprecated: use [metadata.NamePrefix]. This alias will be removed in a future release.
NamePrefix = metadata.NamePrefix
// MetadataSubcommandName is the name of the plugin subcommand
// which must be supported by every plugin and returns the
// plugin metadata.
//
// Deprecated: use [metadata.MetadataSubcommandName]. This alias will be removed in a future release.
MetadataSubcommandName = metadata.MetadataSubcommandName
// HookSubcommandName is the name of the plugin subcommand
// which must be implemented by plugins declaring support
// for hooks in their metadata.
//
// Deprecated: use [metadata.HookSubcommandName]. This alias will be removed in a future release.
HookSubcommandName = metadata.HookSubcommandName
)
// Metadata provided by the plugin.
//
// Deprecated: use [metadata.Metadata]. This alias will be removed in a future release.
type Metadata = metadata.Metadata

View File

@ -2,12 +2,14 @@ package manager
import (
"context"
"encoding"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/docker/cli/cli-plugins/metadata"
@ -31,12 +33,34 @@ type Plugin struct {
ShadowedPaths []string `json:",omitempty"`
}
// MarshalJSON implements [json.Marshaler] to handle marshaling the
// [Plugin.Err] field (Go doesn't marshal errors by default).
func (p *Plugin) MarshalJSON() ([]byte, error) {
type Alias Plugin // avoid recursion
cp := *p // shallow copy to avoid mutating original
if cp.Err != nil {
if _, ok := cp.Err.(encoding.TextMarshaler); !ok {
cp.Err = &pluginError{cp.Err}
}
}
return json.Marshal((*Alias)(&cp))
}
// pluginCandidate represents a possible plugin candidate, for mocking purposes.
type pluginCandidate interface {
Path() string
Metadata() ([]byte, error)
}
// newPlugin determines if the given candidate is valid and returns a
// Plugin. If the candidate fails one of the tests then `Plugin.Err`
// is set, and is always a `pluginError`, but the `Plugin` is still
// returned with no error. An error is only returned due to a
// non-recoverable error.
func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) {
func newPlugin(c pluginCandidate, cmds []*cobra.Command) (Plugin, error) {
path := c.Path()
if path == "" {
return Plugin{}, errors.New("plugin candidate path cannot be empty")
@ -63,7 +87,7 @@ func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) {
// Now apply the candidate tests, so these update p.Err.
if !pluginNameRe.MatchString(p.Name) {
p.Err = NewPluginError("plugin candidate %q did not match %q", p.Name, pluginNameRe.String())
p.Err = newPluginError("plugin candidate %q did not match %q", p.Name, pluginNameRe.String())
return p, nil
}
@ -75,11 +99,11 @@ func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) {
continue
}
if cmd.Name() == p.Name {
p.Err = NewPluginError("plugin %q duplicates builtin command", p.Name)
p.Err = newPluginError("plugin %q duplicates builtin command", p.Name)
return p, nil
}
if cmd.HasAlias(p.Name) {
p.Err = NewPluginError("plugin %q duplicates an alias of builtin command %q", p.Name, cmd.Name())
p.Err = newPluginError("plugin %q duplicates an alias of builtin command %q", p.Name, cmd.Name())
return p, nil
}
}
@ -95,17 +119,42 @@ func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) {
p.Err = wrapAsPluginError(err, "invalid metadata")
return p, nil
}
if p.Metadata.SchemaVersion != "0.1.0" {
p.Err = NewPluginError("plugin SchemaVersion %q is not valid, must be 0.1.0", p.Metadata.SchemaVersion)
if err := validateSchemaVersion(p.Metadata.SchemaVersion); err != nil {
p.Err = &pluginError{cause: err}
return p, nil
}
if p.Metadata.Vendor == "" {
p.Err = NewPluginError("plugin metadata does not define a vendor")
p.Err = newPluginError("plugin metadata does not define a vendor")
return p, nil
}
return p, nil
}
// validateSchemaVersion validates if the plugin's schemaVersion is supported.
//
// The current schema-version is "0.1.0", but we don't want to break compatibility
// until v2.0.0 of the schema version. Check for the major version to be < 2.0.0.
//
// Note that CLI versions before 28.4.1 may not support these versions as they were
// hard-coded to only accept "0.1.0".
func validateSchemaVersion(version string) error {
if version == "0.1.0" {
return nil
}
if version == "" {
return errors.New("plugin SchemaVersion version cannot be empty")
}
major, _, ok := strings.Cut(version, ".")
majorVersion, err := strconv.Atoi(major)
if !ok || err != nil {
return fmt.Errorf("plugin SchemaVersion %q has wrong format: must be <major>.<minor>.<patch>", version)
}
if majorVersion > 1 {
return fmt.Errorf("plugin SchemaVersion %q is not supported: must be lower than 2.0.0", version)
}
return nil
}
// RunHook executes the plugin's hooks command
// and returns its unprocessed output.
func (p *Plugin) RunHook(ctx context.Context, hookData HookPluginData) ([]byte, error) {

View File

@ -0,0 +1,43 @@
package manager
import (
"encoding/json"
"errors"
"testing"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestPluginMarshal(t *testing.T) {
const jsonWithError = `{"Name":"some-plugin","Err":"something went wrong"}`
const jsonNoError = `{"Name":"some-plugin"}`
tests := []struct {
doc string
error error
expected string
}{
{
doc: "no error",
expected: jsonNoError,
},
{
doc: "regular error",
error: errors.New("something went wrong"),
expected: jsonWithError,
},
{
doc: "custom error",
error: newPluginError("something went wrong"),
expected: jsonWithError,
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
actual, err := json.Marshal(&Plugin{Name: "some-plugin", Err: tc.error})
assert.NilError(t, err)
assert.Check(t, is.Equal(string(actual), tc.expected))
})
}
}

View File

@ -33,4 +33,6 @@ type Metadata struct {
ShortDescription string `json:",omitempty"`
// URL is a pointer to the plugin's homepage.
URL string `json:",omitempty"`
// Hidden hides the plugin in completion and help message output.
Hidden bool `json:",omitempty"`
}

View File

@ -80,19 +80,23 @@ func RunPlugin(dockerCli *command.DockerCli, plugin *cobra.Command, meta metadat
return cmd.Execute()
}
// 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 metadata.Metadata) {
// Run is the top-level entry point to the CLI plugin framework. It should
// be called from the plugin's "main()" function. It initializes a new
// [command.DockerCli] instance with the given options before calling
// makeCmd to construct the plugin command, then invokes the plugin command
// using [RunPlugin].
func Run(makeCmd func(command.Cli) *cobra.Command, meta metadata.Metadata, ops ...command.CLIOption) {
otel.SetErrorHandler(debug.OTELErrorHandler)
dockerCli, err := command.NewDockerCli()
dockerCLI, err := command.NewDockerCli(ops...)
if err != nil {
fmt.Fprintln(os.Stderr, err)
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
plugin := makeCmd(dockerCli)
plugin := makeCmd(dockerCLI)
if err := RunPlugin(dockerCli, plugin, meta); err != nil {
if err := RunPlugin(dockerCLI, plugin, meta); err != nil {
var stErr cli.StatusError
if errors.As(err, &stErr) {
// StatusError should only be used for errors, and all errors should
@ -100,10 +104,10 @@ func Run(makeCmd func(command.Cli) *cobra.Command, meta metadata.Metadata) {
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
}
_, _ = fmt.Fprintln(dockerCli.Err(), stErr)
_, _ = fmt.Fprintln(dockerCLI.Err(), stErr)
os.Exit(stErr.StatusCode)
}
_, _ = fmt.Fprintln(dockerCli.Err(), err)
_, _ = fmt.Fprintln(dockerCLI.Err(), err)
os.Exit(1)
}
}
@ -175,11 +179,24 @@ func newPluginCommand(dockerCli *command.DockerCli, plugin *cobra.Command, meta
newMetadataSubcommand(plugin, meta),
)
cli.DisableFlagsInUseLine(cmd)
visitAll(cmd,
// prevent adding "[flags]" to the end of the usage line.
func(c *cobra.Command) { c.DisableFlagsInUseLine = true },
)
return cli.NewTopLevelCommand(cmd, dockerCli, opts, cmd.Flags())
}
// visitAll traverses all commands from the root.
func visitAll(root *cobra.Command, fns ...func(*cobra.Command)) {
for _, cmd := range root.Commands() {
visitAll(cmd, fns...)
}
for _, fn := range fns {
fn(root)
}
}
func newMetadataSubcommand(plugin *cobra.Command, meta metadata.Metadata) *cobra.Command {
if meta.ShortDescription == "" {
meta.ShortDescription = plugin.Short

View File

@ -0,0 +1,28 @@
package plugin
import (
"slices"
"testing"
"github.com/spf13/cobra"
)
func TestVisitAll(t *testing.T) {
root := &cobra.Command{Use: "root"}
sub1 := &cobra.Command{Use: "sub1"}
sub1sub1 := &cobra.Command{Use: "sub1sub1"}
sub1sub2 := &cobra.Command{Use: "sub1sub2"}
sub2 := &cobra.Command{Use: "sub2"}
root.AddCommand(sub1, sub2)
sub1.AddCommand(sub1sub1, sub1sub2)
var visited []string
visitAll(root, func(ccmd *cobra.Command) {
visited = append(visited, ccmd.Name())
})
expected := []string{"sub1sub1", "sub1sub2", "sub1", "sub2", "root"}
if !slices.Equal(expected, visited) {
t.Errorf("expected %#v, got %#v", expected, visited)
}
}

View File

@ -168,34 +168,30 @@ func (tcmd *TopLevelCommand) Initialize(ops ...command.CLIOption) error {
}
// VisitAll will traverse all commands from the root.
// This is different from the VisitAll of cobra.Command where only parents
// are checked.
//
// Deprecated: this utility was only used internally and will be removed in the next release.
func VisitAll(root *cobra.Command, fn func(*cobra.Command)) {
visitAll(root, fn)
}
func visitAll(root *cobra.Command, fn func(*cobra.Command)) {
for _, cmd := range root.Commands() {
VisitAll(cmd, fn)
visitAll(cmd, fn)
}
fn(root)
}
// DisableFlagsInUseLine sets the DisableFlagsInUseLine flag on all
// commands within the tree rooted at cmd.
//
// Deprecated: this utility was only used internally and will be removed in the next release.
func DisableFlagsInUseLine(cmd *cobra.Command) {
VisitAll(cmd, func(ccmd *cobra.Command) {
visitAll(cmd, func(ccmd *cobra.Command) {
// do not add a `[flags]` to the end of the usage line.
ccmd.DisableFlagsInUseLine = true
})
}
// HasCompletionArg returns true if a cobra completion arg request is found.
func HasCompletionArg(args []string) bool {
for _, arg := range args {
if arg == cobra.ShellCompRequestCmd || arg == cobra.ShellCompNoDescRequestCmd {
return true
}
}
return false
}
var helpCommand = &cobra.Command{
Use: "help [command]",
Short: "Help about the command",
@ -380,13 +376,10 @@ func orchestratorSubCommands(cmd *cobra.Command) []*cobra.Command {
func allManagementSubCommands(cmd *cobra.Command) []*cobra.Command {
cmds := []*cobra.Command{}
for _, sub := range cmd.Commands() {
if isPlugin(sub) {
if invalidPluginReason(sub) == "" {
cmds = append(cmds, sub)
}
if invalidPluginReason(sub) != "" {
continue
}
if sub.IsAvailableCommand() && sub.HasSubCommands() {
if sub.IsAvailableCommand() && (isPlugin(sub) || sub.HasSubCommands()) {
cmds = append(cmds, sub)
}
}

View File

@ -10,28 +10,6 @@ import (
is "gotest.tools/v3/assert/cmp"
)
func TestVisitAll(t *testing.T) {
root := &cobra.Command{Use: "root"}
sub1 := &cobra.Command{Use: "sub1"}
sub1sub1 := &cobra.Command{Use: "sub1sub1"}
sub1sub2 := &cobra.Command{Use: "sub1sub2"}
sub2 := &cobra.Command{Use: "sub2"}
root.AddCommand(sub1, sub2)
sub1.AddCommand(sub1sub1, sub1sub2)
// Take the opportunity to test DisableFlagsInUseLine too
DisableFlagsInUseLine(root)
var visited []string
VisitAll(root, func(ccmd *cobra.Command) {
visited = append(visited, ccmd.Name())
assert.Assert(t, ccmd.DisableFlagsInUseLine, "DisableFlagsInUseLine not set on %q", ccmd.Name())
})
expected := []string{"sub1sub1", "sub1sub2", "sub1", "sub2", "root"}
assert.DeepEqual(t, expected, visited)
}
func TestVendorAndVersion(t *testing.T) {
// Non plugin.
assert.Equal(t, vendorAndVersion(&cobra.Command{Use: "test"}), "")
@ -78,6 +56,33 @@ func TestInvalidPlugin(t *testing.T) {
assert.DeepEqual(t, invalidPlugins(root), []*cobra.Command{sub1}, cmpopts.IgnoreUnexported(cobra.Command{}))
}
func TestHiddenPlugin(t *testing.T) {
root := &cobra.Command{Use: "root"}
sub1 := &cobra.Command{
Use: "sub1",
Hidden: true,
Annotations: map[string]string{
metadata.CommandAnnotationPlugin: "true",
},
Run: func(cmd *cobra.Command, args []string) {},
}
sub1sub1 := &cobra.Command{Use: "sub1sub1"}
sub1sub2 := &cobra.Command{Use: "sub1sub2"}
sub2 := &cobra.Command{
Use: "sub2",
Annotations: map[string]string{
metadata.CommandAnnotationPlugin: "true",
},
Run: func(cmd *cobra.Command, args []string) {},
}
root.AddCommand(sub1, sub2)
sub1.AddCommand(sub1sub1, sub1sub2)
assert.DeepEqual(t, allManagementSubCommands(root), []*cobra.Command{sub2}, cmpopts.IgnoreFields(cobra.Command{}, "Run"), cmpopts.IgnoreUnexported(cobra.Command{}))
}
func TestCommandAliases(t *testing.T) {
root := &cobra.Command{Use: "root"}
sub := &cobra.Command{Use: "subcommand", Aliases: []string{"alias1", "alias2"}}

View File

@ -9,17 +9,25 @@ import (
)
// NewBuilderCommand returns a cobra command for `builder` subcommands
func NewBuilderCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewBuilderCommand(dockerCLI command.Cli) *cobra.Command {
return newBuilderCommand(dockerCLI)
}
func newBuilderCommand(dockerCLI command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "builder",
Short: "Manage builds",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
RunE: command.ShowHelp(dockerCLI.Err()),
Annotations: map[string]string{"version": "1.31"},
}
cmd.AddCommand(
NewPruneCommand(dockerCli),
image.NewBuildCommand(dockerCli),
newPruneCommand(dockerCLI),
// we should have a mechanism for registering sub-commands in the cli/internal/commands.Register function.
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
image.NewBuildCommand(dockerCLI),
)
return cmd
}
@ -28,7 +36,13 @@ func NewBuilderCommand(dockerCli command.Cli) *cobra.Command {
// 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).
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewBakeStubCommand(dockerCLI command.Streams) *cobra.Command {
return newBakeStubCommand(dockerCLI)
}
func newBakeStubCommand(dockerCLI command.Streams) *cobra.Command {
return &cobra.Command{
Use: "bake [OPTIONS] [TARGET...]",
Short: "Build from a file",

View File

@ -8,7 +8,6 @@ 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/build"
@ -24,7 +23,14 @@ type pruneOptions struct {
}
// NewPruneCommand returns a new cobra prune command for images
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
return newPruneCommand(dockerCli)
}
// newPruneCommand returns a new cobra prune command for images
func newPruneCommand(dockerCLI command.Cli) *cobra.Command {
options := pruneOptions{filter: opts.NewFilterOpt()}
cmd := &cobra.Command{
@ -32,18 +38,18 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove build cache",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options)
spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCLI, options)
if err != nil {
return err
}
if output != "" {
fmt.Fprintln(dockerCli.Out(), output)
_, _ = fmt.Fprintln(dockerCLI.Out(), output)
}
fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
_, _ = fmt.Fprintln(dockerCLI.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
return nil
},
Annotations: map[string]string{"version": "1.39"},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()
@ -79,9 +85,12 @@ func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions)
}
report, err := dockerCli.Client().BuildCachePrune(ctx, build.CachePruneOptions{
All: options.all,
KeepStorage: options.keepStorage.Value(), // FIXME(thaJeztah): rewrite to use new options; see https://github.com/moby/moby/pull/48720
Filters: pruneFilters,
All: options.all,
// TODO(austinvazquez): remove when updated to use github.com/moby/moby/client@v0.1.0
// See https://github.com/moby/moby/pull/50772 for more details.
KeepStorage: options.keepStorage.Value(),
ReservedSpace: options.keepStorage.Value(),
Filters: pruneFilters,
})
if err != nil {
return 0, "", err

View File

@ -19,7 +19,7 @@ func TestBuilderPromptTermination(t *testing.T) {
return nil, errors.New("fakeClient builderPruneFunc should not be called")
},
})
cmd := NewPruneCommand(cli)
cmd := newPruneCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
test.TerminatePrompt(ctx, t, cmd, cli)

View File

@ -7,12 +7,18 @@ import (
)
// NewCheckpointCommand returns the `checkpoint` subcommand (only in experimental)
func NewCheckpointCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewCheckpointCommand(dockerCLI command.Cli) *cobra.Command {
return newCheckpointCommand(dockerCLI)
}
func newCheckpointCommand(dockerCLI command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "checkpoint",
Short: "Manage checkpoints",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
RunE: command.ShowHelp(dockerCLI.Err()),
Annotations: map[string]string{
"experimental": "",
"ostype": "linux",
@ -20,9 +26,9 @@ func NewCheckpointCommand(dockerCli command.Cli) *cobra.Command {
},
}
cmd.AddCommand(
newCreateCommand(dockerCli),
newListCommand(dockerCli),
newRemoveCommand(dockerCli),
newCreateCommand(dockerCLI),
newListCommand(dockerCLI),
newRemoveCommand(dockerCLI),
)
return cmd
}

View File

@ -6,7 +6,6 @@ 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/spf13/cobra"
)
@ -30,7 +29,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
opts.checkpoint = args[1]
return runCreate(cmd.Context(), dockerCli, opts)
},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()

View File

@ -11,7 +11,14 @@ const (
)
// NewFormat returns a format for use with a checkpoint Context
//
// Deprecated: this function was only used internally and will be removed in the next release.
func NewFormat(source string) formatter.Format {
return newFormat(source)
}
// newFormat returns a format for use with a checkpointContext.
func newFormat(source string) formatter.Format {
if source == formatter.TableFormatKey {
return defaultCheckpointFormat
}
@ -19,7 +26,14 @@ func NewFormat(source string) formatter.Format {
}
// FormatWrite writes formatted checkpoints using the Context
func FormatWrite(ctx formatter.Context, checkpoints []checkpoint.Summary) error {
//
// Deprecated: this function was only used internally and will be removed in the next release.
func FormatWrite(fmtCtx formatter.Context, checkpoints []checkpoint.Summary) error {
return formatWrite(fmtCtx, checkpoints)
}
// formatWrite writes formatted checkpoints using the Context
func formatWrite(fmtCtx formatter.Context, checkpoints []checkpoint.Summary) error {
render := func(format func(subContext formatter.SubContext) error) error {
for _, cp := range checkpoints {
if err := format(&checkpointContext{c: cp}); err != nil {
@ -28,7 +42,7 @@ func FormatWrite(ctx formatter.Context, checkpoints []checkpoint.Summary) error
}
return nil
}
return ctx.Write(newCheckpointContext(), render)
return fmtCtx.Write(newCheckpointContext(), render)
}
type checkpointContext struct {

View File

@ -15,7 +15,7 @@ func TestCheckpointContextFormatWrite(t *testing.T) {
expected string
}{
{
formatter.Context{Format: NewFormat(defaultCheckpointFormat)},
formatter.Context{Format: newFormat(defaultCheckpointFormat)},
`CHECKPOINT NAME
checkpoint-1
checkpoint-2
@ -23,14 +23,14 @@ checkpoint-3
`,
},
{
formatter.Context{Format: NewFormat("{{.Name}}")},
formatter.Context{Format: newFormat("{{.Name}}")},
`checkpoint-1
checkpoint-2
checkpoint-3
`,
},
{
formatter.Context{Format: NewFormat("{{.Name}}:")},
formatter.Context{Format: newFormat("{{.Name}}:")},
`checkpoint-1:
checkpoint-2:
checkpoint-3:
@ -41,7 +41,7 @@ checkpoint-3:
for _, testcase := range cases {
out := bytes.NewBufferString("")
testcase.context.Output = out
err := FormatWrite(testcase.context, []checkpoint.Summary{
err := formatWrite(testcase.context, []checkpoint.Summary{
{Name: "checkpoint-1"},
{Name: "checkpoint-2"},
{Name: "checkpoint-3"},

View File

@ -45,7 +45,7 @@ func runList(ctx context.Context, dockerCli command.Cli, container string, opts
cpCtx := formatter.Context{
Output: dockerCli.Out(),
Format: NewFormat(formatter.TableFormatKey),
Format: newFormat(formatter.TableFormatKey),
}
return FormatWrite(cpCtx, checkpoints)
return formatWrite(cpCtx, checkpoints)
}

View File

@ -48,9 +48,7 @@ type Cli interface {
Apply(ops ...CLIOption) error
config.Provider
ServerInfo() ServerInfo
DefaultVersion() string
CurrentVersion() string
ContentTrustEnabled() bool
BuildKitEnabled() (bool, error)
ContextStore() store.Store
CurrentContext() string
@ -78,6 +76,7 @@ type DockerCli struct {
dockerEndpoint docker.Endpoint
contextStoreConfig *store.Config
initTimeout time.Duration
userAgent string
res telemetryResource
// baseCtx is the base context used for internal operations. In the future
@ -89,6 +88,8 @@ type DockerCli struct {
}
// DefaultVersion returns [api.DefaultVersion].
//
// Deprecated: this function is no longer used and will be removed in the next release.
func (*DockerCli) DefaultVersion() string {
return api.DefaultVersion
}
@ -159,6 +160,8 @@ func (cli *DockerCli) ServerInfo() ServerInfo {
// ContentTrustEnabled returns whether content trust has been enabled by an
// environment variable.
//
// Deprecated: check the value of the DOCKER_CONTENT_TRUST environment variable to detect whether content-trust is enabled.
func (cli *DockerCli) ContentTrustEnabled() bool {
return cli.contentTrust
}
@ -269,7 +272,7 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption)
cli.contextStore = &ContextStoreWithDefault{
Store: store.New(config.ContextStoreDir(), *cli.contextStoreConfig),
Resolver: func() (*DefaultContext, error) {
return ResolveDefaultContext(cli.options, *cli.contextStoreConfig)
return resolveDefaultContext(cli.options, *cli.contextStoreConfig)
},
}
@ -282,6 +285,17 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...CLIOption)
}
filterResourceAttributesEnvvar()
// early return if GODEBUG is already set or the docker context is
// the default context, i.e. is a virtual context where we won't override
// any GODEBUG values.
if v := os.Getenv("GODEBUG"); cli.currentContext == DefaultContextName || v != "" {
return nil
}
meta, err := cli.contextStore.GetMetadata(cli.currentContext)
if err == nil {
setGoDebug(meta)
}
return nil
}
@ -295,17 +309,17 @@ func NewAPIClientFromFlags(opts *cliflags.ClientOptions, configFile *configfile.
contextStore := &ContextStoreWithDefault{
Store: store.New(config.ContextStoreDir(), storeConfig),
Resolver: func() (*DefaultContext, error) {
return ResolveDefaultContext(opts, storeConfig)
return resolveDefaultContext(opts, storeConfig)
},
}
endpoint, err := resolveDockerEndpoint(contextStore, resolveContextName(opts, configFile))
if err != nil {
return nil, errors.Wrap(err, "unable to resolve docker endpoint")
}
return newAPIClientFromEndpoint(endpoint, configFile)
return newAPIClientFromEndpoint(endpoint, configFile, client.WithUserAgent(UserAgent()))
}
func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigFile) (client.APIClient, error) {
func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigFile, extraOpts ...client.Opt) (client.APIClient, error) {
opts, err := ep.ClientOpts()
if err != nil {
return nil, err
@ -313,7 +327,14 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF
if len(configFile.HTTPHeaders) > 0 {
opts = append(opts, client.WithHTTPHeaders(configFile.HTTPHeaders))
}
opts = append(opts, withCustomHeadersFromEnv(), client.WithUserAgent(UserAgent()))
withCustomHeaders, err := withCustomHeadersFromEnv()
if err != nil {
return nil, err
}
if withCustomHeaders != nil {
opts = append(opts, withCustomHeaders)
}
opts = append(opts, extraOpts...)
return client.NewClientWithOpts(opts...)
}
@ -475,6 +496,57 @@ func (cli *DockerCli) getDockerEndPoint() (ep docker.Endpoint, err error) {
return resolveDockerEndpoint(cli.contextStore, cn)
}
// setGoDebug is an escape hatch that sets the GODEBUG environment
// variable value using docker context metadata.
//
// {
// "Name": "my-context",
// "Metadata": { "GODEBUG": "x509negativeserial=1" }
// }
//
// WARNING: Setting x509negativeserial=1 allows Go's x509 library to accept
// X.509 certificates with negative serial numbers.
// This behavior is deprecated and non-compliant with current security
// standards (RFC 5280). Accepting negative serial numbers can introduce
// serious security vulnerabilities, including the risk of certificate
// collision or bypass attacks.
// This option should only be used for legacy compatibility and never in
// production environments.
// Use at your own risk.
func setGoDebug(meta store.Metadata) {
fieldName := "GODEBUG"
godebugEnv := os.Getenv(fieldName)
// early return if GODEBUG is already set. We don't want to override what
// the user already sets.
if godebugEnv != "" {
return
}
var cfg any
var ok bool
switch m := meta.Metadata.(type) {
case DockerContext:
cfg, ok = m.AdditionalFields[fieldName]
if !ok {
return
}
case map[string]any:
cfg, ok = m[fieldName]
if !ok {
return
}
default:
return
}
v, ok := cfg.(string)
if !ok {
return
}
// set the GODEBUG environment variable with whatever was in the context
_ = os.Setenv(fieldName, v)
}
func (cli *DockerCli) initialize() error {
cli.init.Do(func() {
cli.dockerEndpoint, cli.initErr = cli.getDockerEndPoint()
@ -483,7 +555,8 @@ func (cli *DockerCli) initialize() error {
return
}
if cli.client == nil {
if cli.client, cli.initErr = newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile); cli.initErr != nil {
ops := []client.Opt{client.WithUserAgent(cli.userAgent)}
if cli.client, cli.initErr = newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile, ops...); cli.initErr != nil {
return
}
}
@ -496,6 +569,8 @@ func (cli *DockerCli) initialize() error {
}
// Apply all the operation on the cli
//
// Deprecated: this method is no longer used and will be removed in the next release if there are no remaining users.
func (cli *DockerCli) Apply(ops ...CLIOption) error {
for _, op := range ops {
if err := op(cli); err != nil {
@ -527,15 +602,18 @@ type ServerInfo struct {
// environment.
func NewDockerCli(ops ...CLIOption) (*DockerCli, error) {
defaultOps := []CLIOption{
WithContentTrustFromEnv(),
withContentTrustFromEnv(),
WithDefaultContextStoreConfig(),
WithStandardStreams(),
WithUserAgent(UserAgent()),
}
ops = append(defaultOps, ops...)
cli := &DockerCli{baseCtx: context.Background()}
if err := cli.Apply(ops...); err != nil {
return nil, err
for _, op := range ops {
if err := op(cli); err != nil {
return nil, err
}
}
return cli, nil
}
@ -551,7 +629,7 @@ func getServerHost(hosts []string, defaultToTLS bool) (string, error) {
}
}
// UserAgent returns the user agent string used for making API requests
// UserAgent returns the default user agent string used for making API requests.
func UserAgent() string {
return "Docker-Client/" + version.Version + " (" + runtime.GOOS + ")"
}

View File

@ -75,8 +75,8 @@ func WithErrorStream(err io.Writer) CLIOption {
}
}
// WithContentTrustFromEnv enables content trust on a cli from environment variable DOCKER_CONTENT_TRUST value.
func WithContentTrustFromEnv() CLIOption {
// withContentTrustFromEnv enables content trust on a cli from environment variable DOCKER_CONTENT_TRUST value.
func withContentTrustFromEnv() CLIOption {
return func(cli *DockerCli) error {
cli.contentTrust = false
if e := os.Getenv("DOCKER_CONTENT_TRUST"); e != "" {
@ -89,7 +89,16 @@ func WithContentTrustFromEnv() CLIOption {
}
}
// WithContentTrustFromEnv enables content trust on a cli from environment variable DOCKER_CONTENT_TRUST value.
//
// Deprecated: this option is no longer used, and will be removed in the next release.
func WithContentTrustFromEnv() CLIOption {
return withContentTrustFromEnv()
}
// WithContentTrust enables content trust on a cli.
//
// Deprecated: this option is no longer used, and will be removed in the next release.
func WithContentTrust(enabled bool) CLIOption {
return func(cli *DockerCli) error {
cli.contentTrust = enabled
@ -180,61 +189,70 @@ const envOverrideHTTPHeaders = "DOCKER_CUSTOM_HEADERS"
// 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,
func withCustomHeadersFromEnv() (client.Opt, error) {
value := os.Getenv(envOverrideHTTPHeaders)
if value == "" {
return nil, nil
}
csvReader := csv.NewReader(strings.NewReader(value))
fields, err := csvReader.Read()
if err != nil {
return nil, 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, 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 nil, 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,
))
}
if len(fields) == 0 {
return nil
// 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 nil, invalidParameter(errors.Errorf(
`failed to set custom headers from %s environment variable: missing "=" in key=value pair: '%s'`,
envOverrideHTTPHeaders, kv,
))
}
env := map[string]string{}
for _, kv := range fields {
k, v, hasValue := strings.Cut(kv, "=")
env[http.CanonicalHeaderKey(k)] = v
}
// Only strip whitespace in keys; preserve whitespace in values.
k = strings.TrimSpace(k)
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, nil
}
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,
))
}
// 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), nil
}
// 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
// WithUserAgent configures the User-Agent string for cli HTTP requests.
func WithUserAgent(userAgent string) CLIOption {
return func(cli *DockerCli) error {
if userAgent == "" {
return errors.New("user agent cannot be blank")
}
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)
cli.userAgent = userAgent
return nil
}
}

View File

@ -10,7 +10,7 @@ import (
func contentTrustEnabled(t *testing.T) bool {
t.Helper()
var cli DockerCli
assert.NilError(t, WithContentTrustFromEnv()(&cli))
assert.NilError(t, withContentTrustFromEnv()(&cli))
return cli.contentTrust
}

View File

@ -18,6 +18,7 @@ import (
"github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/context/store"
"github.com/docker/cli/cli/flags"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
@ -188,16 +189,16 @@ func TestInitializeFromClient(t *testing.T) {
for _, tc := range testcases {
t.Run(tc.doc, func(t *testing.T) {
apiclient := &fakeClient{
apiClient := &fakeClient{
pingFunc: tc.pingFunc,
version: defaultVersion,
}
cli := &DockerCli{client: apiclient}
cli := &DockerCli{client: apiClient}
err := cli.Initialize(flags.NewClientOptions())
assert.NilError(t, err)
assert.DeepEqual(t, cli.ServerInfo(), tc.expectedServer)
assert.Equal(t, apiclient.negotiated, tc.negotiated)
assert.Equal(t, apiClient.negotiated, tc.negotiated)
})
}
}
@ -353,3 +354,46 @@ func TestHooksEnabled(t *testing.T) {
assert.Check(t, !cli.HooksEnabled())
})
}
func TestSetGoDebug(t *testing.T) {
t.Run("GODEBUG already set", func(t *testing.T) {
t.Setenv("GODEBUG", "val1,val2")
meta := store.Metadata{}
setGoDebug(meta)
assert.Equal(t, "val1,val2", os.Getenv("GODEBUG"))
})
t.Run("GODEBUG in context metadata can set env", func(t *testing.T) {
meta := store.Metadata{
Metadata: DockerContext{
AdditionalFields: map[string]any{
"GODEBUG": "val1,val2=1",
},
},
}
setGoDebug(meta)
assert.Equal(t, "val1,val2=1", os.Getenv("GODEBUG"))
})
}
func TestNewDockerCliWithCustomUserAgent(t *testing.T) {
var received string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
received = r.UserAgent()
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
host := strings.Replace(ts.URL, "http://", "tcp://", 1)
opts := &flags.ClientOptions{Hosts: []string{host}}
cli, err := NewDockerCli(
WithUserAgent("fake-agent/0.0.1"),
)
assert.NilError(t, err)
cli.currentContext = DefaultContextName
cli.options = opts
cli.configFile = &configfile.ConfigFile{}
_, err = cli.Client().Ping(context.Background())
assert.NilError(t, err)
assert.DeepEqual(t, received, "fake-agent/0.0.1")
}

View File

@ -29,69 +29,127 @@ import (
func AddCommands(cmd *cobra.Command, dockerCli command.Cli) {
cmd.AddCommand(
// commonly used shorthands
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
container.NewRunCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
container.NewExecCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
container.NewPsCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
image.NewBuildCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
image.NewPullCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
image.NewPushCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
image.NewImagesCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
registry.NewLoginCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
registry.NewLogoutCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
registry.NewSearchCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
system.NewVersionCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
system.NewInfoCommand(dockerCli),
// management commands
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
builder.NewBakeStubCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
builder.NewBuilderCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
checkpoint.NewCheckpointCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
container.NewContainerCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
context.NewContextCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
image.NewImageCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
manifest.NewManifestCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
network.NewNetworkCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
plugin.NewPluginCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
system.NewSystemCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
trust.NewTrustCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
volume.NewVolumeCommand(dockerCli),
// orchestration (swarm) commands
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
config.NewConfigCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
node.NewNodeCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
secret.NewSecretCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
service.NewServiceCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
stack.NewStackCommand(dockerCli),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
swarm.NewSwarmCommand(dockerCli),
// legacy commands may be hidden
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewAttachCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewCommitCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewCopyCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewCreateCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewDiffCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewExportCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewKillCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewLogsCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewPauseCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewPortCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewRenameCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewRestartCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewRmCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewStartCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewStatsCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewStopCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewTopCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewUnpauseCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewUpdateCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(container.NewWaitCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(image.NewHistoryCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(image.NewImportCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(image.NewLoadCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(image.NewRemoveCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(image.NewSaveCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(image.NewTagCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(system.NewEventsCommand(dockerCli)),
//nolint:staticcheck // TODO: Remove when migration to cli/internal/commands.Register is complete. (see #6283)
hide(system.NewInspectCommand(dockerCli)),
)
}

View File

@ -13,11 +13,6 @@ import (
"github.com/spf13/cobra"
)
// 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.
//
@ -146,7 +141,9 @@ func FileNames(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCom
return nil, cobra.ShellCompDirectiveDefault
}
// NoComplete is used for commands where there's no relevant completion
// NoComplete is used for commands where there's no relevant completion.
//
// Deprecated: use [cobra.NoFileCompletions]. This function will be removed in the next release.
func NoComplete(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
}

View File

@ -288,12 +288,6 @@ func TestCompleteNetworkNames(t *testing.T) {
}
}
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")

View File

@ -9,22 +9,28 @@ import (
)
// NewConfigCommand returns a cobra command for `config` subcommands
func NewConfigCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewConfigCommand(dockerCLI command.Cli) *cobra.Command {
return newConfigCommand(dockerCLI)
}
func newConfigCommand(dockerCLI command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Manage Swarm configs",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
RunE: command.ShowHelp(dockerCLI.Err()),
Annotations: map[string]string{
"version": "1.30",
"swarm": "manager",
},
}
cmd.AddCommand(
newConfigListCommand(dockerCli),
newConfigCreateCommand(dockerCli),
newConfigInspectCommand(dockerCli),
newConfigRemoveCommand(dockerCli),
newConfigListCommand(dockerCLI),
newConfigCreateCommand(dockerCLI),
newConfigInspectCommand(dockerCLI),
newConfigRemoveCommand(dockerCLI),
)
return cmd
}

View File

@ -7,7 +7,6 @@ import (
"github.com/docker/cli/cli"
"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/sys/sequential"
@ -16,6 +15,8 @@ import (
)
// CreateOptions specifies some options that are used when creating a config.
//
// Deprecated: this type was for internal use and will be removed in the next release.
type CreateOptions struct {
Name string
TemplateDriver string
@ -23,9 +24,17 @@ type CreateOptions struct {
Labels opts.ListOpts
}
func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command {
createOpts := CreateOptions{
Labels: opts.NewListOpts(opts.ValidateLabel),
// createOptions specifies some options that are used when creating a config.
type createOptions struct {
name string
templateDriver string
file string
labels opts.ListOpts
}
func newConfigCreateCommand(dockerCLI command.Cli) *cobra.Command {
createOpts := createOptions{
labels: opts.NewListOpts(opts.ValidateLabel),
}
cmd := &cobra.Command{
@ -33,39 +42,51 @@ func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command {
Short: "Create a config from a file or STDIN",
Args: cli.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
createOpts.Name = args[0]
createOpts.File = args[1]
return RunConfigCreate(cmd.Context(), dockerCli, createOpts)
createOpts.name = args[0]
createOpts.file = args[1]
return runCreate(cmd.Context(), dockerCLI, createOpts)
},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()
flags.VarP(&createOpts.Labels, "label", "l", "Config labels")
flags.StringVar(&createOpts.TemplateDriver, "template-driver", "", "Template driver")
flags.SetAnnotation("template-driver", "version", []string{"1.37"})
flags.VarP(&createOpts.labels, "label", "l", "Config labels")
flags.StringVar(&createOpts.templateDriver, "template-driver", "", "Template driver")
_ = flags.SetAnnotation("template-driver", "version", []string{"1.37"})
return cmd
}
// RunConfigCreate creates a config with the given options.
//
// Deprecated: this function was for internal use and will be removed in the next release.
func RunConfigCreate(ctx context.Context, dockerCLI command.Cli, options CreateOptions) error {
return runCreate(ctx, dockerCLI, createOptions{
name: options.Name,
templateDriver: options.TemplateDriver,
file: options.File,
labels: options.Labels,
})
}
// runCreate creates a config with the given options.
func runCreate(ctx context.Context, dockerCLI command.Cli, options createOptions) error {
apiClient := dockerCLI.Client()
configData, err := readConfigData(dockerCLI.In(), options.File)
configData, err := readConfigData(dockerCLI.In(), options.file)
if err != nil {
return errors.Errorf("Error reading content from %q: %v", options.File, err)
return errors.Errorf("Error reading content from %q: %v", options.file, err)
}
spec := swarm.ConfigSpec{
Annotations: swarm.Annotations{
Name: options.Name,
Labels: opts.ConvertKVStringsToMap(options.Labels.GetSlice()),
Name: options.name,
Labels: opts.ConvertKVStringsToMap(options.labels.GetSlice()),
},
Data: configData,
}
if options.TemplateDriver != "" {
if options.templateDriver != "" {
spec.Templating = &swarm.Driver{
Name: options.TemplateDriver,
Name: options.templateDriver,
}
}
r, err := apiClient.ConfigCreate(ctx, spec)

View File

@ -30,7 +30,14 @@ Data:
)
// NewFormat returns a Format for rendering using a config Context
//
// Deprecated: this function was only used internally and will be removed in the next release.
func NewFormat(source string, quiet bool) formatter.Format {
return newFormat(source, quiet)
}
// newFormat returns a Format for rendering using a configContext.
func newFormat(source string, quiet bool) formatter.Format {
switch source {
case formatter.PrettyFormatKey:
return configInspectPrettyTemplate
@ -44,7 +51,14 @@ func NewFormat(source string, quiet bool) formatter.Format {
}
// FormatWrite writes the context
func FormatWrite(ctx formatter.Context, configs []swarm.Config) error {
//
// Deprecated: this function was only used internally and will be removed in the next release.
func FormatWrite(fmtCtx formatter.Context, configs []swarm.Config) error {
return formatWrite(fmtCtx, configs)
}
// formatWrite writes the context
func formatWrite(fmtCtx formatter.Context, configs []swarm.Config) error {
render := func(format func(subContext formatter.SubContext) error) error {
for _, config := range configs {
configCtx := &configContext{c: config}
@ -54,7 +68,7 @@ func FormatWrite(ctx formatter.Context, configs []swarm.Config) error {
}
return nil
}
return ctx.Write(newConfigContext(), render)
return fmtCtx.Write(newConfigContext(), render)
}
func newConfigContext() *configContext {
@ -115,9 +129,16 @@ func (c *configContext) Label(name string) string {
}
// InspectFormatWrite renders the context for a list of configs
func InspectFormatWrite(ctx formatter.Context, refs []string, getRef inspect.GetRefFunc) error {
if ctx.Format != configInspectPrettyTemplate {
return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef)
//
// Deprecated: this function was only used internally and will be removed in the next release.
func InspectFormatWrite(fmtCtx formatter.Context, refs []string, getRef inspect.GetRefFunc) error {
return inspectFormatWrite(fmtCtx, refs, getRef)
}
// inspectFormatWrite renders the context for a list of configs
func inspectFormatWrite(fmtCtx formatter.Context, refs []string, getRef inspect.GetRefFunc) error {
if fmtCtx.Format != configInspectPrettyTemplate {
return inspect.Inspect(fmtCtx.Output, refs, string(fmtCtx.Format), getRef)
}
render := func(format func(subContext formatter.SubContext) error) error {
for _, ref := range refs {
@ -135,7 +156,7 @@ func InspectFormatWrite(ctx formatter.Context, refs []string, getRef inspect.Get
}
return nil
}
return ctx.Write(&configInspectContext{}, render)
return fmtCtx.Write(&configInspectContext{}, render)
}
type configInspectContext struct {

View File

@ -27,21 +27,21 @@ func TestConfigContextFormatWrite(t *testing.T) {
},
// Table format
{
formatter.Context{Format: NewFormat("table", false)},
formatter.Context{Format: newFormat("table", false)},
`ID NAME CREATED UPDATED
1 passwords Less than a second ago Less than a second ago
2 id_rsa Less than a second ago Less than a second ago
`,
},
{
formatter.Context{Format: NewFormat("table {{.Name}}", true)},
formatter.Context{Format: newFormat("table {{.Name}}", true)},
`NAME
passwords
id_rsa
`,
},
{
formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
formatter.Context{Format: newFormat("{{.ID}}-{{.Name}}", false)},
`1-passwords
2-id_rsa
`,
@ -64,7 +64,7 @@ id_rsa
t.Run(string(tc.context.Format), func(t *testing.T) {
var out bytes.Buffer
tc.context.Output = &out
if err := FormatWrite(tc.context, configs); err != nil {
if err := formatWrite(tc.context, configs); err != nil {
assert.ErrorContains(t, err, tc.expected)
} else {
assert.Equal(t, out.String(), tc.expected)

View File

@ -16,57 +16,76 @@ import (
)
// InspectOptions contains options for the docker config inspect command.
//
// Deprecated: this type was for internal use and will be removed in the next release.
type InspectOptions struct {
Names []string
Format string
Pretty bool
}
func newConfigInspectCommand(dockerCli command.Cli) *cobra.Command {
opts := InspectOptions{}
// inspectOptions contains options for the docker config inspect command.
type inspectOptions struct {
names []string
format string
pretty bool
}
func newConfigInspectCommand(dockerCLI command.Cli) *cobra.Command {
opts := inspectOptions{}
cmd := &cobra.Command{
Use: "inspect [OPTIONS] CONFIG [CONFIG...]",
Short: "Display detailed information on one or more configs",
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Names = args
return RunConfigInspect(cmd.Context(), dockerCli, opts)
opts.names = args
return runInspect(cmd.Context(), dockerCLI, opts)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete)
return completeNames(dockerCLI)(cmd, args, toComplete)
},
}
cmd.Flags().StringVarP(&opts.Format, "format", "f", "", flagsHelper.InspectFormatHelp)
cmd.Flags().BoolVar(&opts.Pretty, "pretty", false, "Print the information in a human friendly format")
cmd.Flags().StringVarP(&opts.format, "format", "f", "", flagsHelper.InspectFormatHelp)
cmd.Flags().BoolVar(&opts.pretty, "pretty", false, "Print the information in a human friendly format")
return cmd
}
// RunConfigInspect inspects the given Swarm config.
//
// Deprecated: this function was for internal use and will be removed in the next release.
func RunConfigInspect(ctx context.Context, dockerCLI command.Cli, opts InspectOptions) error {
return runInspect(ctx, dockerCLI, inspectOptions{
names: opts.Names,
format: opts.Format,
pretty: opts.Pretty,
})
}
// runInspect inspects the given Swarm config.
func runInspect(ctx context.Context, dockerCLI command.Cli, opts inspectOptions) error {
apiClient := dockerCLI.Client()
if opts.Pretty {
opts.Format = "pretty"
if opts.pretty {
opts.format = "pretty"
}
getRef := func(id string) (any, []byte, error) {
return apiClient.ConfigInspectWithRaw(ctx, id)
}
f := opts.Format
// check if the user is trying to apply a template to the pretty format, which
// is not supported
if strings.HasPrefix(f, "pretty") && f != "pretty" {
if strings.HasPrefix(opts.format, "pretty") && opts.format != "pretty" {
return errors.New("cannot supply extra formatting options to the pretty template")
}
configCtx := formatter.Context{
Output: dockerCLI.Out(),
Format: NewFormat(f, false),
Format: newFormat(opts.format, false),
}
if err := InspectFormatWrite(configCtx, opts.Names, getRef); err != nil {
if err := inspectFormatWrite(configCtx, opts.names, getRef); err != nil {
return cli.StatusError{StatusCode: 1, Status: err.Error()}
}
return nil

View File

@ -6,7 +6,6 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/formatter"
flagsHelper "github.com/docker/cli/cli/flags"
"github.com/docker/cli/opts"
@ -16,14 +15,23 @@ import (
)
// ListOptions contains options for the docker config ls command.
//
// Deprecated: this type was for internal use and will be removed in the next release.
type ListOptions struct {
Quiet bool
Format string
Filter opts.FilterOpt
}
func newConfigListCommand(dockerCli command.Cli) *cobra.Command {
listOpts := ListOptions{Filter: opts.NewFilterOpt()}
// listOptions contains options for the docker config ls command.
type listOptions struct {
quiet bool
format string
filter opts.FilterOpt
}
func newConfigListCommand(dockerCLI command.Cli) *cobra.Command {
listOpts := listOptions{filter: opts.NewFilterOpt()}
cmd := &cobra.Command{
Use: "ls [OPTIONS]",
@ -31,31 +39,42 @@ func newConfigListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List configs",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return RunConfigList(cmd.Context(), dockerCli, listOpts)
return runList(cmd.Context(), dockerCLI, listOpts)
},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()
flags.BoolVarP(&listOpts.Quiet, "quiet", "q", false, "Only display IDs")
flags.StringVar(&listOpts.Format, "format", "", flagsHelper.FormatHelp)
flags.VarP(&listOpts.Filter, "filter", "f", "Filter output based on conditions provided")
flags.BoolVarP(&listOpts.quiet, "quiet", "q", false, "Only display IDs")
flags.StringVar(&listOpts.format, "format", "", flagsHelper.FormatHelp)
flags.VarP(&listOpts.filter, "filter", "f", "Filter output based on conditions provided")
return cmd
}
// RunConfigList lists Swarm configs.
//
// Deprecated: this function was for internal use and will be removed in the next release.
func RunConfigList(ctx context.Context, dockerCLI command.Cli, options ListOptions) error {
return runList(ctx, dockerCLI, listOptions{
quiet: options.Quiet,
format: options.Format,
filter: options.Filter,
})
}
// runList lists Swarm configs.
func runList(ctx context.Context, dockerCLI command.Cli, options listOptions) error {
apiClient := dockerCLI.Client()
configs, err := apiClient.ConfigList(ctx, swarm.ConfigListOptions{Filters: options.Filter.Value()})
configs, err := apiClient.ConfigList(ctx, swarm.ConfigListOptions{Filters: options.filter.Value()})
if err != nil {
return err
}
format := options.Format
format := options.format
if len(format) == 0 {
if len(dockerCLI.ConfigFile().ConfigFormat) > 0 && !options.Quiet {
if len(dockerCLI.ConfigFile().ConfigFormat) > 0 && !options.quiet {
format = dockerCLI.ConfigFile().ConfigFormat
} else {
format = formatter.TableFormatKey
@ -68,7 +87,7 @@ func RunConfigList(ctx context.Context, dockerCLI command.Cli, options ListOptio
configCtx := formatter.Context{
Output: dockerCLI.Out(),
Format: NewFormat(format, options.Quiet),
Format: newFormat(format, options.quiet),
}
return FormatWrite(configCtx, configs)
return formatWrite(configCtx, configs)
}

View File

@ -11,34 +11,40 @@ import (
)
// RemoveOptions contains options for the docker config rm command.
//
// Deprecated: this type was for internal use and will be removed in the next release.
type RemoveOptions struct {
Names []string
}
func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command {
func newConfigRemoveCommand(dockerCLI command.Cli) *cobra.Command {
return &cobra.Command{
Use: "rm CONFIG [CONFIG...]",
Aliases: []string{"remove"},
Short: "Remove one or more configs",
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts := RemoveOptions{
Names: args,
}
return RunConfigRemove(cmd.Context(), dockerCli, opts)
return runRemove(cmd.Context(), dockerCLI, args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete)
return completeNames(dockerCLI)(cmd, args, toComplete)
},
}
}
// RunConfigRemove removes the given Swarm configs.
//
// Deprecated: this function was for internal use and will be removed in the next release.
func RunConfigRemove(ctx context.Context, dockerCLI command.Cli, opts RemoveOptions) error {
return runRemove(ctx, dockerCLI, opts.Names)
}
// runRemove removes the given Swarm configs.
func runRemove(ctx context.Context, dockerCLI command.Cli, names []string) error {
apiClient := dockerCLI.Client()
var errs []error
for _, name := range opts.Names {
for _, name := range names {
if err := apiClient.ConfigRemove(ctx, name); err != nil {
errs = append(errs, err)
continue

View File

@ -41,7 +41,13 @@ func inspectContainerAndCheckState(ctx context.Context, apiClient client.APIClie
}
// NewAttachCommand creates a new cobra.Command for `docker attach`
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewAttachCommand(dockerCLI command.Cli) *cobra.Command {
return newAttachCommand(dockerCLI)
}
func newAttachCommand(dockerCLI command.Cli) *cobra.Command {
var opts AttachOptions
cmd := &cobra.Command{

View File

@ -74,7 +74,7 @@ func TestNewAttachCommandErrors(t *testing.T) {
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}))
cmd := newAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc}))
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)

View File

@ -7,39 +7,45 @@ import (
)
// NewContainerCommand returns a cobra command for `container` subcommands
func NewContainerCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewContainerCommand(dockerCLI command.Cli) *cobra.Command {
return newContainerCommand(dockerCLI)
}
func newContainerCommand(dockerCLI command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "container",
Short: "Manage containers",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
RunE: command.ShowHelp(dockerCLI.Err()),
}
cmd.AddCommand(
NewAttachCommand(dockerCli),
NewCommitCommand(dockerCli),
NewCopyCommand(dockerCli),
NewCreateCommand(dockerCli),
NewDiffCommand(dockerCli),
NewExecCommand(dockerCli),
NewExportCommand(dockerCli),
NewKillCommand(dockerCli),
NewLogsCommand(dockerCli),
NewPauseCommand(dockerCli),
NewPortCommand(dockerCli),
NewRenameCommand(dockerCli),
NewRestartCommand(dockerCli),
newRemoveCommand(dockerCli),
NewRunCommand(dockerCli),
NewStartCommand(dockerCli),
NewStatsCommand(dockerCli),
NewStopCommand(dockerCli),
NewTopCommand(dockerCli),
NewUnpauseCommand(dockerCli),
NewUpdateCommand(dockerCli),
NewWaitCommand(dockerCli),
newListCommand(dockerCli),
newInspectCommand(dockerCli),
NewPruneCommand(dockerCli),
newAttachCommand(dockerCLI),
newCommitCommand(dockerCLI),
newCopyCommand(dockerCLI),
newCreateCommand(dockerCLI),
newDiffCommand(dockerCLI),
newExecCommand(dockerCLI),
newExportCommand(dockerCLI),
newKillCommand(dockerCLI),
newLogsCommand(dockerCLI),
newPauseCommand(dockerCLI),
newPortCommand(dockerCLI),
newRenameCommand(dockerCLI),
newRestartCommand(dockerCLI),
newRemoveCommand(dockerCLI),
newRunCommand(dockerCLI),
newStartCommand(dockerCLI),
newStatsCommand(dockerCLI),
newStopCommand(dockerCLI),
newTopCommand(dockerCLI),
newUnpauseCommand(dockerCLI),
newUpdateCommand(dockerCLI),
newWaitCommand(dockerCLI),
newListCommand(dockerCLI),
newInspectCommand(dockerCLI),
newPruneCommand(dockerCLI),
)
return cmd
}

View File

@ -23,7 +23,13 @@ type commitOptions struct {
}
// NewCommitCommand creates a new cobra.Command for `docker commit`
func NewCommitCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewCommitCommand(dockerCLI command.Cli) *cobra.Command {
return newCommitCommand(dockerCLI)
}
func newCommitCommand(dockerCLI command.Cli) *cobra.Command {
var options commitOptions
cmd := &cobra.Command{
@ -35,12 +41,12 @@ func NewCommitCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 {
options.reference = args[1]
}
return runCommit(cmd.Context(), dockerCli, &options)
return runCommit(cmd.Context(), dockerCLI, &options)
},
Annotations: map[string]string{
"aliases": "docker container commit, docker commit",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
}
flags := cmd.Flags()

View File

@ -29,7 +29,7 @@ func TestRunCommit(t *testing.T) {
},
})
cmd := NewCommitCommand(cli)
cmd := newCommitCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs(
[]string{
@ -60,7 +60,7 @@ func TestRunCommitClientError(t *testing.T) {
},
})
cmd := NewCommitCommand(cli)
cmd := newCommitCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"container-id"})

View File

@ -59,7 +59,7 @@ func TestCompletePid(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
containerListFunc: tc.containerListFunc,
})
completions, directive := completePid(cli)(NewRunCommand(cli), nil, tc.toComplete)
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))
})

View File

@ -122,7 +122,13 @@ func copyProgress(ctx context.Context, dst io.Writer, header string, total *int6
}
// NewCopyCommand creates a new `docker cp` command
func NewCopyCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewCopyCommand(dockerCLI command.Cli) *cobra.Command {
return newCopyCommand(dockerCLI)
}
func newCopyCommand(dockerCLI command.Cli) *cobra.Command {
var opts copyOptions
cmd := &cobra.Command{
@ -147,9 +153,9 @@ container source to stdout.`,
opts.destination = args[1]
if !cmd.Flag("quiet").Changed {
// User did not specify "quiet" flag; suppress output if no terminal is attached
opts.quiet = !dockerCli.Out().IsTerminal()
opts.quiet = !dockerCLI.Out().IsTerminal()
}
return runCopy(cmd.Context(), dockerCli, opts)
return runCopy(cmd.Context(), dockerCLI, opts)
},
Annotations: map[string]string{
"aliases": "docker container cp, docker cp",

View File

@ -11,7 +11,7 @@ import (
"path"
"strings"
cerrdefs "github.com/containerd/errdefs"
"github.com/containerd/errdefs"
"github.com/containerd/platforms"
"github.com/distribution/reference"
"github.com/docker/cli/cli"
@ -52,7 +52,13 @@ type createOptions struct {
}
// NewCreateCommand creates a new cobra.Command for `docker create`
func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewCreateCommand(dockerCLI command.Cli) *cobra.Command {
return newCreateCommand(dockerCLI)
}
func newCreateCommand(dockerCLI command.Cli) *cobra.Command {
var options createOptions
var copts *containerOptions
@ -65,12 +71,12 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 {
copts.Args = args[1:]
}
return runCreate(cmd.Context(), dockerCli, cmd.Flags(), &options, copts)
return runCreate(cmd.Context(), dockerCLI, cmd.Flags(), &options, copts)
},
Annotations: map[string]string{
"aliases": "docker container create, docker create",
},
ValidArgsFunction: completion.ImageNames(dockerCli, -1),
ValidArgsFunction: completion.ImageNames(dockerCLI, -1),
}
flags := cmd.Flags()
@ -86,17 +92,20 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
// with hostname
flags.Bool("help", false, "Print usage")
command.AddPlatformFlag(flags, &options.platform)
command.AddTrustVerificationFlags(flags, &options.untrusted, dockerCli.ContentTrustEnabled())
// TODO(thaJeztah): consider adding platform as "image create option" on containerOptions
addPlatformFlag(flags, &options.platform)
_ = cmd.RegisterFlagCompletionFunc("platform", completion.Platforms)
flags.BoolVar(&options.untrusted, "disable-content-trust", !trust.Enabled(), "Skip image verification")
copts = addFlags(flags)
addCompletions(cmd, dockerCli)
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)
_ = cmd.RegisterFlagCompletionFunc(flag.Name, cobra.NoFileCompletions)
})
return cmd
@ -341,7 +350,7 @@ 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 cerrdefs.IsNotFound(err) && namedRef != nil && options.pull == PullImageMissing {
if errdefs.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))

View File

@ -116,7 +116,7 @@ func TestCreateContainerImagePullPolicy(t *testing.T) {
t.Run(tc.PullPolicy, func(t *testing.T) {
pullCounter := 0
client := &fakeClient{
apiClient := &fakeClient{
createContainerFunc: func(
config *container.Config,
hostConfig *container.HostConfig,
@ -140,7 +140,7 @@ func TestCreateContainerImagePullPolicy(t *testing.T) {
return system.Info{IndexServerAddress: "https://indexserver.example.com"}, nil
},
}
fakeCLI := test.NewFakeCli(client)
fakeCLI := test.NewFakeCli(apiClient)
id, err := createContainer(context.Background(), fakeCLI, config, &createOptions{
name: "name",
platform: runtime.GOOS,
@ -206,7 +206,7 @@ func TestCreateContainerValidateFlags(t *testing.T) {
},
} {
t.Run(tc.name, func(t *testing.T) {
cmd := NewCreateCommand(test.NewFakeCli(&fakeClient{}))
cmd := newCreateCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)
@ -249,6 +249,7 @@ func TestNewCreateCommandWithContentTrustErrors(t *testing.T) {
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DOCKER_CONTENT_TRUST", "true")
fakeCLI := test.NewFakeCli(&fakeClient{
createContainerFunc: func(config *container.Config,
hostConfig *container.HostConfig,
@ -258,9 +259,9 @@ func TestNewCreateCommandWithContentTrustErrors(t *testing.T) {
) (container.CreateResponse, error) {
return container.CreateResponse{}, errors.New("shouldn't try to pull image")
},
}, test.EnableContentTrust)
})
fakeCLI.SetNotaryClient(tc.notaryFunc)
cmd := NewCreateCommand(fakeCLI)
cmd := newCreateCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)
@ -314,7 +315,7 @@ func TestNewCreateCommandWithWarnings(t *testing.T) {
return container.CreateResponse{Warnings: tc.warnings}, nil
},
})
cmd := NewCreateCommand(fakeCLI)
cmd := newCreateCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args)
err := cmd.Execute()
@ -366,7 +367,7 @@ func TestCreateContainerWithProxyConfig(t *testing.T) {
},
},
})
cmd := NewCreateCommand(fakeCLI)
cmd := newCreateCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"image:tag"})
err := cmd.Execute()

View File

@ -11,18 +11,24 @@ import (
)
// NewDiffCommand creates a new cobra.Command for `docker diff`
func NewDiffCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewDiffCommand(dockerCLI command.Cli) *cobra.Command {
return newDiffCommand(dockerCLI)
}
func newDiffCommand(dockerCLI command.Cli) *cobra.Command {
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 {
return runDiff(cmd.Context(), dockerCli, args[0])
return runDiff(cmd.Context(), dockerCLI, args[0])
},
Annotations: map[string]string{
"aliases": "docker container diff, docker diff",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
}
}
@ -33,7 +39,7 @@ func runDiff(ctx context.Context, dockerCLI command.Cli, containerID string) err
}
diffCtx := formatter.Context{
Output: dockerCLI.Out(),
Format: NewDiffFormat("{{.Type}} {{.Path}}"),
Format: newDiffFormat("{{.Type}} {{.Path}}"),
}
return DiffFormatWrite(diffCtx, changes)
return diffFormatWrite(diffCtx, changes)
}

View File

@ -36,7 +36,7 @@ func TestRunDiff(t *testing.T) {
},
})
cmd := NewDiffCommand(cli)
cmd := newDiffCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"container-id"})
@ -68,7 +68,7 @@ func TestRunDiffClientError(t *testing.T) {
},
})
cmd := NewDiffCommand(cli)
cmd := newDiffCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)

View File

@ -1,9 +1,9 @@
package container
import cerrdefs "github.com/containerd/errdefs"
import "github.com/containerd/errdefs"
func invalidParameter(err error) error {
if err == nil || cerrdefs.IsInvalidArgument(err) {
if err == nil || errdefs.IsInvalidArgument(err) {
return err
}
return invalidParameterErr{err}
@ -17,7 +17,7 @@ func (e invalidParameterErr) Unwrap() error {
}
func notFound(err error) error {
if err == nil || cerrdefs.IsNotFound(err) {
if err == nil || errdefs.IsNotFound(err) {
return err
}
return notFoundErr{err}

View File

@ -40,7 +40,13 @@ func NewExecOptions() ExecOptions {
}
// NewExecCommand creates a new cobra.Command for `docker exec`
func NewExecCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewExecCommand(dockerCLI command.Cli) *cobra.Command {
return newExecCommand(dockerCLI)
}
func newExecCommand(dockerCLI command.Cli) *cobra.Command {
options := NewExecOptions()
cmd := &cobra.Command{
@ -50,9 +56,9 @@ func NewExecCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
containerIDorName := args[0]
options.Command = args[1:]
return RunExec(cmd.Context(), dockerCli, containerIDorName, options)
return RunExec(cmd.Context(), dockerCLI, containerIDorName, options)
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(ctr container.Summary) bool {
ValidArgsFunction: completion.ContainerNames(dockerCLI, false, func(ctr container.Summary) bool {
return ctr.State != container.StatePaused
}),
Annotations: map[string]string{

View File

@ -234,13 +234,13 @@ func TestGetExecExitStatus(t *testing.T) {
}
for _, testcase := range testcases {
client := &fakeClient{
apiClient := &fakeClient{
execInspectFunc: func(id string) (container.ExecInspect, error) {
assert.Check(t, is.Equal(execID, id))
return container.ExecInspect{ExitCode: testcase.exitCode}, testcase.inspectError
},
}
err := getExecExitStatus(context.Background(), client, execID)
err := getExecExitStatus(context.Background(), apiClient, execID)
assert.Check(t, is.Equal(testcase.expectedError, err))
}
}
@ -263,7 +263,7 @@ func TestNewExecCommandErrors(t *testing.T) {
}
for _, tc := range testCases {
fakeCLI := test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc})
cmd := NewExecCommand(fakeCLI)
cmd := newExecCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetArgs(tc.args)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)

View File

@ -18,7 +18,13 @@ type exportOptions struct {
}
// NewExportCommand creates a new `docker export` command
func NewExportCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewExportCommand(dockerCLI command.Cli) *cobra.Command {
return newExportCommand(dockerCLI)
}
func newExportCommand(dockerCLI command.Cli) *cobra.Command {
var opts exportOptions
cmd := &cobra.Command{
@ -27,12 +33,12 @@ func NewExportCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0]
return runExport(cmd.Context(), dockerCli, opts)
return runExport(cmd.Context(), dockerCLI, opts)
},
Annotations: map[string]string{
"aliases": "docker container export, docker export",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, true),
ValidArgsFunction: completion.ContainerNames(dockerCLI, true),
}
flags := cmd.Flags()

View File

@ -19,7 +19,7 @@ func TestContainerExportOutputToFile(t *testing.T) {
return io.NopCloser(strings.NewReader("bar")), nil
},
})
cmd := NewExportCommand(cli)
cmd := newExportCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"-o", dir.Join("foo"), "container"})
assert.NilError(t, cmd.Execute())
@ -37,7 +37,7 @@ func TestContainerExportOutputToIrregularFile(t *testing.T) {
return io.NopCloser(strings.NewReader("foo")), nil
},
})
cmd := NewExportCommand(cli)
cmd := newExportCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"-o", "/dev/random", "container"})

View File

@ -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

@ -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
@ -50,7 +50,7 @@ D: /usr/app/old_app.js
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

@ -167,6 +167,7 @@ func (c *statsContext) Container() string {
}
func (c *statsContext) Name() string {
// TODO(thaJeztah): make this explicitly trim the "/" prefix, not just any char.
if len(c.s.Name) > 1 {
return c.s.Name[1:]
}

View File

@ -5,45 +5,181 @@ import (
"testing"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/cli/internal/test"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestContainerStatsContext(t *testing.T) {
containerID := test.RandomID()
const actorID = "c74518277ddc15a6afeaaeb06ee5f7433dcb27188224777c1efa7df1e8766d65"
var ctx statsContext
tt := []struct {
tests := []struct {
name string
stats StatsEntry
osType string
expValue string
expHeader string
call func() string
}{
{StatsEntry{Container: containerID}, "", containerID, containerHeader, ctx.Container},
{StatsEntry{CPUPercentage: 5.5}, "", "5.50%", cpuPercHeader, ctx.CPUPerc},
{StatsEntry{CPUPercentage: 5.5, IsInvalid: true}, "", "--", cpuPercHeader, ctx.CPUPerc},
{StatsEntry{NetworkRx: 0.31, NetworkTx: 12.3}, "", "0.31B / 12.3B", netIOHeader, ctx.NetIO},
{StatsEntry{NetworkRx: 0.31, NetworkTx: 12.3, IsInvalid: true}, "", "--", netIOHeader, ctx.NetIO},
{StatsEntry{BlockRead: 0.1, BlockWrite: 2.3}, "", "0.1B / 2.3B", blockIOHeader, ctx.BlockIO},
{StatsEntry{BlockRead: 0.1, BlockWrite: 2.3, IsInvalid: true}, "", "--", blockIOHeader, ctx.BlockIO},
{StatsEntry{MemoryPercentage: 10.2}, "", "10.20%", memPercHeader, ctx.MemPerc},
{StatsEntry{MemoryPercentage: 10.2, IsInvalid: true}, "", "--", memPercHeader, ctx.MemPerc},
{StatsEntry{MemoryPercentage: 10.2}, "windows", "--", memPercHeader, ctx.MemPerc},
{StatsEntry{Memory: 24, MemoryLimit: 30}, "", "24B / 30B", memUseHeader, ctx.MemUsage},
{StatsEntry{Memory: 24, MemoryLimit: 30, IsInvalid: true}, "", "-- / --", memUseHeader, ctx.MemUsage},
{StatsEntry{Memory: 24, MemoryLimit: 30}, "windows", "24B", winMemUseHeader, ctx.MemUsage},
{StatsEntry{PidsCurrent: 10}, "", "10", pidsHeader, ctx.PIDs},
{StatsEntry{PidsCurrent: 10, IsInvalid: true}, "", "--", pidsHeader, ctx.PIDs},
{StatsEntry{PidsCurrent: 10}, "windows", "--", pidsHeader, ctx.PIDs},
{
name: "Container id",
stats: StatsEntry{ID: actorID, Container: actorID},
expValue: actorID,
expHeader: containerHeader,
call: ctx.Container,
},
{
name: "Container name",
stats: StatsEntry{ID: actorID, Container: "a-long-container-name"},
expValue: "a-long-container-name",
expHeader: containerHeader,
call: ctx.Container,
},
{
name: "ID",
stats: StatsEntry{ID: actorID},
expValue: actorID,
expHeader: formatter.ContainerIDHeader,
call: ctx.ID,
},
{
name: "Name",
stats: StatsEntry{Name: "/container-name"},
expValue: "container-name",
expHeader: formatter.ContainerIDHeader,
call: ctx.Name,
},
{
name: "Name empty",
stats: StatsEntry{Name: ""},
expValue: "--",
expHeader: formatter.ContainerIDHeader,
call: ctx.Name,
},
{
name: "Name prefix only",
stats: StatsEntry{Name: "/"},
expValue: "--",
expHeader: formatter.ContainerIDHeader,
call: ctx.Name,
},
{
name: "CPUPerc",
stats: StatsEntry{CPUPercentage: 5.5},
expValue: "5.50%",
expHeader: cpuPercHeader,
call: ctx.CPUPerc,
},
{
name: "CPUPerc invalid",
stats: StatsEntry{CPUPercentage: 5.5, IsInvalid: true},
expValue: "--",
expHeader: cpuPercHeader,
call: ctx.CPUPerc,
},
{
name: "NetIO",
stats: StatsEntry{NetworkRx: 0.31, NetworkTx: 12.3},
expValue: "0.31B / 12.3B",
expHeader: netIOHeader,
call: ctx.NetIO,
},
{
name: "NetIO invalid",
stats: StatsEntry{NetworkRx: 0.31, NetworkTx: 12.3, IsInvalid: true},
expValue: "--",
expHeader: netIOHeader,
call: ctx.NetIO,
},
{
name: "BlockIO",
stats: StatsEntry{BlockRead: 0.1, BlockWrite: 2.3},
expValue: "0.1B / 2.3B",
expHeader: blockIOHeader,
call: ctx.BlockIO,
},
{
name: "BlockIO invalid",
stats: StatsEntry{BlockRead: 0.1, BlockWrite: 2.3, IsInvalid: true},
expValue: "--",
expHeader: blockIOHeader,
call: ctx.BlockIO,
},
{
name: "MemPerc",
stats: StatsEntry{MemoryPercentage: 10.2},
expValue: "10.20%",
expHeader: memPercHeader,
call: ctx.MemPerc,
},
{
name: "MemPerc invalid",
stats: StatsEntry{MemoryPercentage: 10.2, IsInvalid: true},
expValue: "--",
expHeader: memPercHeader,
call: ctx.MemPerc,
},
{
name: "MemPerc windows",
stats: StatsEntry{MemoryPercentage: 10.2},
osType: "windows",
expValue: "--",
expHeader: memPercHeader,
call: ctx.MemPerc,
},
{
name: "MemUsage",
stats: StatsEntry{Memory: 24, MemoryLimit: 30},
expValue: "24B / 30B",
expHeader: memUseHeader,
call: ctx.MemUsage,
},
{
name: "MemUsage invalid",
stats: StatsEntry{Memory: 24, MemoryLimit: 30, IsInvalid: true},
expValue: "-- / --",
expHeader: memUseHeader,
call: ctx.MemUsage,
},
{
name: "MemUsage windows",
stats: StatsEntry{Memory: 24, MemoryLimit: 30},
osType: "windows",
expValue: "24B",
expHeader: winMemUseHeader,
call: ctx.MemUsage,
},
{
name: "PIDs",
stats: StatsEntry{PidsCurrent: 10},
expValue: "10",
expHeader: pidsHeader,
call: ctx.PIDs,
},
{
name: "PIDs invalid",
stats: StatsEntry{PidsCurrent: 10, IsInvalid: true},
expValue: "--",
expHeader: pidsHeader,
call: ctx.PIDs,
},
{
name: "PIDs windows",
stats: StatsEntry{PidsCurrent: 10},
osType: "windows",
expValue: "--",
expHeader: pidsHeader,
call: ctx.PIDs,
},
}
for _, te := range tt {
ctx = statsContext{s: te.stats, os: te.osType}
if v := te.call(); v != te.expValue {
t.Fatalf("Expected %q, got %q", te.expValue, v)
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx = statsContext{s: tc.stats, os: tc.osType}
if v := tc.call(); v != tc.expValue {
t.Fatalf("Expected %q, got %q", tc.expValue, v)
}
})
}
}

View File

@ -18,7 +18,13 @@ type killOptions struct {
}
// NewKillCommand creates a new cobra.Command for `docker kill`
func NewKillCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewKillCommand(dockerCLI command.Cli) *cobra.Command {
return newKillCommand(dockerCLI)
}
func newKillCommand(dockerCLI command.Cli) *cobra.Command {
var opts killOptions
cmd := &cobra.Command{
@ -27,12 +33,12 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args
return runKill(cmd.Context(), dockerCli, &opts)
return runKill(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container kill, docker kill",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
}
flags := cmd.Flags()

View File

@ -24,7 +24,7 @@ func TestRunKill(t *testing.T) {
},
})
cmd := NewKillCommand(cli)
cmd := newKillCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{
@ -56,7 +56,7 @@ func TestRunKillClientError(t *testing.T) {
},
})
cmd := NewKillCommand(cli)
cmd := newKillCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)

View File

@ -6,7 +6,6 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/formatter"
flagsHelper "github.com/docker/cli/cli/flags"
"github.com/docker/cli/opts"
@ -29,7 +28,13 @@ type psOptions struct {
}
// NewPsCommand creates a new cobra.Command for `docker ps`
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewPsCommand(dockerCLI command.Cli) *cobra.Command {
return newPsCommand(dockerCLI)
}
func newPsCommand(dockerCLI command.Cli) *cobra.Command {
options := psOptions{filter: opts.NewFilterOpt()}
cmd := &cobra.Command{
@ -44,7 +49,7 @@ func NewPsCommand(dockerCLI command.Cli) *cobra.Command {
"category-top": "3",
"aliases": "docker container ls, docker container list, docker container ps, docker ps",
},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()
@ -62,7 +67,7 @@ func NewPsCommand(dockerCLI command.Cli) *cobra.Command {
}
func newListCommand(dockerCLI command.Cli) *cobra.Command {
cmd := *NewPsCommand(dockerCLI)
cmd := *newPsCommand(dockerCLI)
cmd.Aliases = []string{"ps", "list"}
cmd.Use = "ls [OPTIONS]"
return &cmd
@ -82,7 +87,7 @@ func buildContainerListOptions(options *psOptions) (*container.ListOptions, erro
// always validate template when `--format` is used, for consistency
if len(options.format) > 0 {
tmpl, err := templates.NewParse("", options.format)
tmpl, err := templates.Parse(options.format)
if err != nil {
return nil, errors.Wrap(err, "failed to parse template")
}

View File

@ -24,7 +24,13 @@ type logsOptions struct {
}
// NewLogsCommand creates a new cobra.Command for `docker logs`
func NewLogsCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewLogsCommand(dockerCLI command.Cli) *cobra.Command {
return newLogsCommand(dockerCLI)
}
func newLogsCommand(dockerCLI command.Cli) *cobra.Command {
var opts logsOptions
cmd := &cobra.Command{
@ -33,12 +39,12 @@ func NewLogsCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0]
return runLogs(cmd.Context(), dockerCli, &opts)
return runLogs(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container logs, docker logs",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, true),
ValidArgsFunction: completion.ContainerNames(dockerCLI, true),
}
flags := cmd.Flags()

View File

@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"net"
"os"
"path"
"path/filepath"
@ -12,8 +13,8 @@ import (
"strings"
"time"
"github.com/docker/cli/cli/compose/loader"
"github.com/docker/cli/internal/lazyregexp"
"github.com/docker/cli/internal/volumespec"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
mounttypes "github.com/docker/docker/api/types/mount"
@ -141,6 +142,16 @@ type containerOptions struct {
Args []string
}
// addPlatformFlag adds "--platform" to a set of flags for API version 1.32 and
// later, using the value of "DOCKER_DEFAULT_PLATFORM" (if set) as a default.
//
// It should not be used for new uses, which may have a different API version
// requirement.
func addPlatformFlag(flags *pflag.FlagSet, target *string) {
flags.StringVar(target, "platform", os.Getenv("DOCKER_DEFAULT_PLATFORM"), "Set platform if server is multi-platform capable")
_ = flags.SetAnnotation("platform", "version", []string{"1.32"})
}
// addFlags adds all command line flags that will be used by parse to the FlagSet
func addFlags(flags *pflag.FlagSet) *containerOptions {
copts := &containerOptions{
@ -340,7 +351,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con
// Validate the input mac address
if copts.macAddress != "" {
if _, err := opts.ValidateMACAddress(copts.macAddress); err != nil {
if _, err := net.ParseMAC(strings.TrimSpace(copts.macAddress)); err != nil {
return nil, errors.Errorf("%s is not a valid mac address", copts.macAddress)
}
}
@ -364,7 +375,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con
volumes := copts.volumes.GetMap()
// add any bind targets to the list of container volumes
for bind := range copts.volumes.GetMap() {
parsed, err := loader.ParseVolume(bind)
parsed, err := volumespec.Parse(bind)
if err != nil {
return nil, err
}
@ -873,7 +884,7 @@ func parseNetworkAttachmentOpt(ep opts.NetworkAttachmentOpts) (*networktypes.End
}
}
if ep.MacAddress != "" {
if _, err := opts.ValidateMACAddress(ep.MacAddress); err != nil {
if _, err := net.ParseMAC(strings.TrimSpace(ep.MacAddress)); err != nil {
return nil, errors.Errorf("%s is not a valid mac address", ep.MacAddress)
}
epConfig.MacAddress = ep.MacAddress

View File

@ -17,7 +17,13 @@ type pauseOptions struct {
}
// NewPauseCommand creates a new cobra.Command for `docker pause`
func NewPauseCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewPauseCommand(dockerCLI command.Cli) *cobra.Command {
return newPauseCommand(dockerCLI)
}
func newPauseCommand(dockerCLI command.Cli) *cobra.Command {
var opts pauseOptions
return &cobra.Command{
@ -26,12 +32,12 @@ func NewPauseCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args
return runPause(cmd.Context(), dockerCli, &opts)
return runPause(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container pause, docker pause",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(ctr container.Summary) bool {
ValidArgsFunction: completion.ContainerNames(dockerCLI, false, func(ctr container.Summary) bool {
return ctr.State != container.StatePaused
}),
}

View File

@ -21,7 +21,7 @@ func TestRunPause(t *testing.T) {
},
)
cmd := NewPauseCommand(cli)
cmd := newPauseCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{"container-id-1", "container-id-2"})
@ -47,7 +47,7 @@ func TestRunPauseClientError(t *testing.T) {
},
)
cmd := NewPauseCommand(cli)
cmd := newPauseCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"container-id-1", "container-id-2"})

View File

@ -24,7 +24,13 @@ type portOptions struct {
}
// NewPortCommand creates a new cobra.Command for `docker port`
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewPortCommand(dockerCli command.Cli) *cobra.Command {
return newPortCommand(dockerCli)
}
func newPortCommand(dockerCli command.Cli) *cobra.Command {
var opts portOptions
cmd := &cobra.Command{

View File

@ -66,7 +66,7 @@ func TestNewPortCommandOutput(t *testing.T) {
return ci, nil
},
})
cmd := NewPortCommand(cli)
cmd := newPortCommand(cli)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"some_container", tc.port})
err := cmd.Execute()

View File

@ -6,7 +6,6 @@ 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/go-units"
@ -20,7 +19,13 @@ type pruneOptions struct {
}
// NewPruneCommand returns a new cobra prune command for containers
func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewPruneCommand(dockerCLI command.Cli) *cobra.Command {
return newPruneCommand(dockerCLI)
}
func newPruneCommand(dockerCLI command.Cli) *cobra.Command {
options := pruneOptions{filter: opts.NewFilterOpt()}
cmd := &cobra.Command{
@ -28,18 +33,18 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove all stopped containers",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options)
spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCLI, options)
if err != nil {
return err
}
if output != "" {
fmt.Fprintln(dockerCli.Out(), output)
fmt.Fprintln(dockerCLI.Out(), output)
}
fmt.Fprintln(dockerCli.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
fmt.Fprintln(dockerCLI.Out(), "Total reclaimed space:", units.HumanSize(float64(spaceReclaimed)))
return nil
},
Annotations: map[string]string{"version": "1.25"},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()

View File

@ -20,7 +20,7 @@ func TestContainerPrunePromptTermination(t *testing.T) {
return container.PruneReport{}, errors.New("fakeClient containerPruneFunc should not be called")
},
})
cmd := NewPruneCommand(cli)
cmd := newPruneCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)

View File

@ -18,7 +18,13 @@ type renameOptions struct {
}
// NewRenameCommand creates a new cobra.Command for `docker rename`
func NewRenameCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewRenameCommand(dockerCLI command.Cli) *cobra.Command {
return newRenameCommand(dockerCLI)
}
func newRenameCommand(dockerCLI command.Cli) *cobra.Command {
var opts renameOptions
cmd := &cobra.Command{
@ -28,12 +34,12 @@ func NewRenameCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
opts.oldName = args[0]
opts.newName = args[1]
return runRename(cmd.Context(), dockerCli, &opts)
return runRename(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container rename, docker rename",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, true),
ValidArgsFunction: completion.ContainerNames(dockerCLI, true),
}
return cmd
}

View File

@ -43,7 +43,7 @@ func TestRunRename(t *testing.T) {
},
})
cmd := NewRenameCommand(cli)
cmd := newRenameCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{tc.oldName, tc.newName})
@ -66,7 +66,7 @@ func TestRunRenameClientError(t *testing.T) {
},
})
cmd := NewRenameCommand(cli)
cmd := newRenameCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"oldName", "newName"})

View File

@ -21,7 +21,13 @@ type restartOptions struct {
}
// NewRestartCommand creates a new cobra.Command for `docker restart`
func NewRestartCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewRestartCommand(dockerCLI command.Cli) *cobra.Command {
return newRestartCommand(dockerCLI)
}
func newRestartCommand(dockerCLI command.Cli) *cobra.Command {
var opts restartOptions
cmd := &cobra.Command{
@ -34,12 +40,12 @@ func NewRestartCommand(dockerCli command.Cli) *cobra.Command {
}
opts.containers = args
opts.timeoutChanged = cmd.Flags().Changed("timeout") || cmd.Flags().Changed("time")
return runRestart(cmd.Context(), dockerCli, &opts)
return runRestart(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container restart, docker restart",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, true),
ValidArgsFunction: completion.ContainerNames(dockerCLI, true),
}
flags := cmd.Flags()

View File

@ -76,7 +76,7 @@ func TestRestart(t *testing.T) {
},
Version: "1.36",
})
cmd := NewRestartCommand(cli)
cmd := newRestartCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)

View File

@ -6,7 +6,7 @@ import (
"fmt"
"strings"
cerrdefs "github.com/containerd/errdefs"
"github.com/containerd/errdefs"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
@ -23,7 +23,13 @@ type rmOptions struct {
}
// NewRmCommand creates a new cobra.Command for `docker rm`
func NewRmCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewRmCommand(dockerCLI command.Cli) *cobra.Command {
return newRmCommand(dockerCLI)
}
func newRmCommand(dockerCLI command.Cli) *cobra.Command {
var opts rmOptions
cmd := &cobra.Command{
@ -32,12 +38,12 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args
return runRm(cmd.Context(), dockerCli, &opts)
return runRm(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container rm, docker container remove, docker rm",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, true, func(ctr container.Summary) bool {
ValidArgsFunction: completion.ContainerNames(dockerCLI, true, func(ctr container.Summary) bool {
return opts.force || ctr.State == container.StateExited || ctr.State == container.StateCreated
}),
}
@ -53,7 +59,7 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command {
// top-level "docker rm", it also adds a "remove" alias to support
// "docker container remove" in addition to "docker container rm".
func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
cmd := *NewRmCommand(dockerCli)
cmd := *newRmCommand(dockerCli)
cmd.Aliases = []string{"rm", "remove"}
return &cmd
}
@ -75,7 +81,7 @@ func runRm(ctx context.Context, dockerCLI command.Cli, opts *rmOptions) error {
var errs []error
for _, name := range opts.containers {
if err := <-errChan; err != nil {
if opts.force && cerrdefs.IsNotFound(err) {
if opts.force && errdefs.IsNotFound(err) {
_, _ = fmt.Fprintln(dockerCLI.Err(), err)
continue
}

View File

@ -41,7 +41,7 @@ func TestRemoveForce(t *testing.T) {
},
Version: "1.36",
})
cmd := NewRmCommand(cli)
cmd := newRmCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)

View File

@ -10,6 +10,7 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/trust"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types/container"
"github.com/moby/sys/signal"
@ -28,7 +29,13 @@ type runOptions struct {
}
// NewRunCommand create a new `docker run` command
func NewRunCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewRunCommand(dockerCLI command.Cli) *cobra.Command {
return newRunCommand(dockerCLI)
}
func newRunCommand(dockerCLI command.Cli) *cobra.Command {
var options runOptions
var copts *containerOptions
@ -41,9 +48,9 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 {
copts.Args = args[1:]
}
return runRun(cmd.Context(), dockerCli, cmd.Flags(), &options, copts)
return runRun(cmd.Context(), dockerCLI, cmd.Flags(), &options, copts)
},
ValidArgsFunction: completion.ImageNames(dockerCli, 1),
ValidArgsFunction: completion.ImageNames(dockerCLI, 1),
Annotations: map[string]string{
"category-top": "1",
"aliases": "docker container run, docker run",
@ -66,18 +73,19 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command {
// with hostname
flags.Bool("help", false, "Print usage")
command.AddPlatformFlag(flags, &options.platform)
command.AddTrustVerificationFlags(flags, &options.untrusted, dockerCli.ContentTrustEnabled())
// TODO(thaJeztah): consider adding platform as "image create option" on containerOptions
addPlatformFlag(flags, &options.platform)
flags.BoolVar(&options.untrusted, "disable-content-trust", !trust.Enabled(), "Skip image verification")
copts = addFlags(flags)
_ = cmd.RegisterFlagCompletionFunc("detach-keys", completeDetachKeys)
addCompletions(cmd, dockerCli)
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)
_ = cmd.RegisterFlagCompletionFunc(flag.Name, cobra.NoFileCompletions)
})
return cmd

View File

@ -2,9 +2,7 @@ package container
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"syscall"
@ -20,7 +18,8 @@ import (
"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/pkg/jsonmessage"
"github.com/docker/docker/pkg/progress"
"github.com/docker/docker/pkg/streamformatter"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/spf13/pflag"
"gotest.tools/v3/assert"
@ -40,7 +39,7 @@ func TestRunValidateFlags(t *testing.T) {
},
} {
t.Run(tc.name, func(t *testing.T) {
cmd := NewRunCommand(test.NewFakeCli(&fakeClient{}))
cmd := newRunCommand(test.NewFakeCli(&fakeClient{}))
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)
@ -64,7 +63,7 @@ func TestRunLabel(t *testing.T) {
},
Version: "1.36",
})
cmd := NewRunCommand(fakeCLI)
cmd := newRunCommand(fakeCLI)
cmd.SetArgs([]string{"--detach=true", "--label", "foo", "busybox"})
assert.NilError(t, cmd.Execute())
}
@ -111,7 +110,7 @@ func TestRunAttach(t *testing.T) {
fc.SetIn(streams.NewIn(tty))
})
cmd := NewRunCommand(fakeCLI)
cmd := newRunCommand(fakeCLI)
cmd.SetArgs([]string{"-it", "busybox"})
cmd.SilenceUsage = true
cmdErrC := make(chan error, 1)
@ -188,7 +187,7 @@ func TestRunAttachTermination(t *testing.T) {
fc.SetIn(streams.NewIn(tty))
})
cmd := NewRunCommand(fakeCLI)
cmd := newRunCommand(fakeCLI)
cmd.SetArgs([]string{"-it", "busybox"})
cmd.SilenceUsage = true
cmdErrC := make(chan error, 1)
@ -242,23 +241,19 @@ func TestRunPullTermination(t *testing.T) {
_ = server.Close()
})
go func() {
enc := json.NewEncoder(server)
id := test.RandomID()[:12] // short-ID
progressOutput := streamformatter.NewJSONProgressOutput(server, true)
for i := 0; i < 100; i++ {
select {
case <-ctx.Done():
assert.NilError(t, server.Close(), "failed to close imageCreateFunc server")
return
default:
assert.NilError(t, enc.Encode(jsonmessage.JSONMessage{
Status: "Downloading",
ID: fmt.Sprintf("id-%d", i),
TimeNano: time.Now().UnixNano(),
Time: time.Now().Unix(),
Progress: &jsonmessage.JSONProgress{
Current: int64(i),
Total: 100,
Start: 0,
},
assert.NilError(t, progressOutput.WriteProgress(progress.Progress{
ID: id,
Message: "Downloading",
Current: int64(i),
Total: 100,
}))
time.Sleep(100 * time.Millisecond)
}
@ -270,7 +265,7 @@ func TestRunPullTermination(t *testing.T) {
Version: "1.30",
})
cmd := NewRunCommand(fakeCLI)
cmd := newRunCommand(fakeCLI)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"--pull", "always", "foobar:latest"})
@ -328,6 +323,7 @@ func TestRunCommandWithContentTrustErrors(t *testing.T) {
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DOCKER_CONTENT_TRUST", "true")
fakeCLI := test.NewFakeCli(&fakeClient{
createContainerFunc: func(config *container.Config,
hostConfig *container.HostConfig,
@ -337,9 +333,9 @@ func TestRunCommandWithContentTrustErrors(t *testing.T) {
) (container.CreateResponse, error) {
return container.CreateResponse{}, errors.New("shouldn't try to pull image")
},
}, test.EnableContentTrust)
})
fakeCLI.SetNotaryClient(tc.notaryFunc)
cmd := NewRunCommand(fakeCLI)
cmd := newRunCommand(fakeCLI)
cmd.SetArgs(tc.args)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)

View File

@ -28,7 +28,13 @@ type StartOptions struct {
}
// NewStartCommand creates a new cobra.Command for `docker start`
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewStartCommand(dockerCli command.Cli) *cobra.Command {
return newStartCommand(dockerCli)
}
func newStartCommand(dockerCli command.Cli) *cobra.Command {
var opts StartOptions
cmd := &cobra.Command{

View File

@ -64,7 +64,13 @@ type StatsOptions struct {
}
// NewStatsCommand creates a new [cobra.Command] for "docker stats".
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewStatsCommand(dockerCLI command.Cli) *cobra.Command {
return newStatsCommand(dockerCLI)
}
func newStatsCommand(dockerCLI command.Cli) *cobra.Command {
options := StatsOptions{}
cmd := &cobra.Command{
@ -133,7 +139,7 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
eh := newEventHandler()
if options.All {
eh.setHandler(events.ActionCreate, func(e events.Message) {
s := NewStats(e.Actor.ID[:12])
s := NewStats(e.Actor.ID)
if cStats.add(s) {
waitFirst.Add(1)
go collect(ctx, s, apiClient, !options.NoStream, waitFirst)
@ -142,7 +148,7 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
}
eh.setHandler(events.ActionStart, func(e events.Message) {
s := NewStats(e.Actor.ID[:12])
s := NewStats(e.Actor.ID)
if cStats.add(s) {
waitFirst.Add(1)
go collect(ctx, s, apiClient, !options.NoStream, waitFirst)
@ -151,7 +157,7 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
if !options.All {
eh.setHandler(events.ActionDie, func(e events.Message) {
cStats.remove(e.Actor.ID[:12])
cStats.remove(e.Actor.ID)
})
}
@ -204,7 +210,7 @@ func RunStats(ctx context.Context, dockerCLI command.Cli, options *StatsOptions)
return err
}
for _, ctr := range cs {
s := NewStats(ctr.ID[:12])
s := NewStats(ctr.ID)
if cStats.add(s) {
waitFirst.Add(1)
go collect(ctx, s, apiClient, !options.NoStream, waitFirst)
@ -357,7 +363,12 @@ func (eh *eventHandler) watch(c <-chan events.Message) {
if !exists {
continue
}
logrus.Debugf("event handler: received event: %v", e)
if e.Actor.ID == "" {
logrus.WithField("event", e).Errorf("event handler: received %s event with empty ID", e.Action)
continue
}
logrus.WithField("event", e).Debugf("event handler: received %s event for: %s", e.Action, e.Actor.ID)
go h(e)
}
}

View File

@ -21,7 +21,13 @@ type stopOptions struct {
}
// NewStopCommand creates a new cobra.Command for `docker stop`
func NewStopCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewStopCommand(dockerCLI command.Cli) *cobra.Command {
return newStopCommand(dockerCLI)
}
func newStopCommand(dockerCLI command.Cli) *cobra.Command {
var opts stopOptions
cmd := &cobra.Command{
@ -34,12 +40,12 @@ func NewStopCommand(dockerCli command.Cli) *cobra.Command {
}
opts.containers = args
opts.timeoutChanged = cmd.Flags().Changed("timeout") || cmd.Flags().Changed("time")
return runStop(cmd.Context(), dockerCli, &opts)
return runStop(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container stop, docker stop",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
}
flags := cmd.Flags()

View File

@ -77,7 +77,7 @@ func TestStop(t *testing.T) {
},
Version: "1.36",
})
cmd := NewStopCommand(cli)
cmd := newStopCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(tc.args)

View File

@ -19,7 +19,13 @@ type topOptions struct {
}
// NewTopCommand creates a new cobra.Command for `docker top`
func NewTopCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewTopCommand(dockerCLI command.Cli) *cobra.Command {
return newTopCommand(dockerCLI)
}
func newTopCommand(dockerCLI command.Cli) *cobra.Command {
var opts topOptions
cmd := &cobra.Command{
@ -29,12 +35,12 @@ func NewTopCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0]
opts.args = args[1:]
return runTop(cmd.Context(), dockerCli, &opts)
return runTop(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container top, docker top",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
}
flags := cmd.Flags()

View File

@ -17,7 +17,13 @@ type unpauseOptions struct {
}
// NewUnpauseCommand creates a new cobra.Command for `docker unpause`
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewUnpauseCommand(dockerCli command.Cli) *cobra.Command {
return newUnpauseCommand(dockerCli)
}
func newUnpauseCommand(dockerCli command.Cli) *cobra.Command {
var opts unpauseOptions
cmd := &cobra.Command{

View File

@ -37,7 +37,13 @@ type updateOptions struct {
}
// NewUpdateCommand creates a new cobra.Command for `docker update`
func NewUpdateCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewUpdateCommand(dockerCLI command.Cli) *cobra.Command {
return newUpdateCommand(dockerCLI)
}
func newUpdateCommand(dockerCLI command.Cli) *cobra.Command {
var options updateOptions
cmd := &cobra.Command{
@ -47,12 +53,12 @@ func NewUpdateCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
options.containers = args
options.nFlag = cmd.Flags().NFlag()
return runUpdate(cmd.Context(), dockerCli, &options)
return runUpdate(cmd.Context(), dockerCLI, &options)
},
Annotations: map[string]string{
"aliases": "docker container update, docker update",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, true),
ValidArgsFunction: completion.ContainerNames(dockerCLI, true),
}
flags := cmd.Flags()

View File

@ -16,7 +16,13 @@ type waitOptions struct {
}
// NewWaitCommand creates a new cobra.Command for `docker wait`
func NewWaitCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewWaitCommand(dockerCLI command.Cli) *cobra.Command {
return newWaitCommand(dockerCLI)
}
func newWaitCommand(dockerCLI command.Cli) *cobra.Command {
var opts waitOptions
cmd := &cobra.Command{
@ -25,12 +31,12 @@ func NewWaitCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args
return runWait(cmd.Context(), dockerCli, &opts)
return runWait(cmd.Context(), dockerCLI, &opts)
},
Annotations: map[string]string{
"aliases": "docker container wait, docker wait",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
ValidArgsFunction: completion.ContainerNames(dockerCLI, false),
}
return cmd

View File

@ -7,23 +7,30 @@ import (
)
// NewContextCommand returns the context cli subcommand
func NewContextCommand(dockerCli command.Cli) *cobra.Command {
//
// Deprecated: Do not import commands directly. They will be removed in a future release.
func NewContextCommand(dockerCLI command.Cli) *cobra.Command {
return newContextCommand(dockerCLI)
}
// newContextCommand returns the context cli subcommand
func newContextCommand(dockerCLI command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "context",
Short: "Manage contexts",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
RunE: command.ShowHelp(dockerCLI.Err()),
}
cmd.AddCommand(
newCreateCommand(dockerCli),
newListCommand(dockerCli),
newUseCommand(dockerCli),
newExportCommand(dockerCli),
newImportCommand(dockerCli),
newRemoveCommand(dockerCli),
newUpdateCommand(dockerCli),
newInspectCommand(dockerCli),
newShowCommand(dockerCli),
newCreateCommand(dockerCLI),
newListCommand(dockerCLI),
newUseCommand(dockerCLI),
newExportCommand(dockerCLI),
newImportCommand(dockerCLI),
newRemoveCommand(dockerCLI),
newUpdateCommand(dockerCLI),
newInspectCommand(dockerCLI),
newShowCommand(dockerCLI),
)
return cmd
}

View File

@ -8,10 +8,9 @@ import (
"errors"
"fmt"
cerrdefs "github.com/containerd/errdefs"
"github.com/containerd/errdefs"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/formatter/tabwriter"
"github.com/docker/cli/cli/context/docker"
"github.com/docker/cli/cli/context/store"
@ -19,6 +18,8 @@ import (
)
// CreateOptions are the options used for creating a context
//
// Deprecated: this type was for internal use and will be removed in the next release.
type CreateOptions struct {
Name string
Description string
@ -30,6 +31,18 @@ type CreateOptions struct {
metaData map[string]any
}
// createOptions are the options used for creating a context
type createOptions struct {
name string
description string
endpoint map[string]string
from string
// Additional Metadata to store in the context. This option is not
// currently exposed to the user.
metaData map[string]any
}
func longCreateDescription() string {
buf := bytes.NewBuffer(nil)
buf.WriteString("Create a context\n\nDocker endpoint config:\n\n")
@ -44,52 +57,68 @@ func longCreateDescription() string {
}
func newCreateCommand(dockerCLI command.Cli) *cobra.Command {
opts := &CreateOptions{}
opts := createOptions{}
cmd := &cobra.Command{
Use: "create [OPTIONS] CONTEXT",
Short: "Create a context",
Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Name = args[0]
return RunCreate(dockerCLI, opts)
opts.name = args[0]
return runCreate(dockerCLI, &opts)
},
Long: longCreateDescription(),
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()
flags.StringVar(&opts.Description, "description", "", "Description of the context")
flags.StringToStringVar(&opts.Docker, "docker", nil, "set the docker endpoint")
flags.StringVar(&opts.From, "from", "", "create context from a named context")
flags.StringVar(&opts.description, "description", "", "Description of the context")
flags.StringToStringVar(&opts.endpoint, "docker", nil, "set the docker endpoint")
flags.StringVar(&opts.from, "from", "", "create context from a named context")
return cmd
}
// RunCreate creates a Docker context
// Deprecated: this function was for internal use and will be removed in the next release.
func RunCreate(dockerCLI command.Cli, o *CreateOptions) error {
if o == nil {
o = &CreateOptions{}
}
return runCreate(dockerCLI, &createOptions{
name: o.Name,
description: o.Description,
endpoint: o.Docker,
metaData: o.metaData,
})
}
// runCreate creates a Docker context
func runCreate(dockerCLI command.Cli, opts *createOptions) error {
s := dockerCLI.ContextStore()
err := checkContextNameForCreation(s, o.Name)
err := checkContextNameForCreation(s, opts.name)
if err != nil {
return err
}
switch {
case o.From == "" && o.Docker == nil:
err = createFromExistingContext(s, dockerCLI.CurrentContext(), o)
case o.From != "":
err = createFromExistingContext(s, o.From, o)
case opts.from == "" && opts.endpoint == nil:
err = createFromExistingContext(s, dockerCLI.CurrentContext(), opts)
case opts.from != "":
err = createFromExistingContext(s, opts.from, opts)
default:
err = createNewContext(s, o)
err = createNewContext(s, opts)
}
if err == nil {
_, _ = fmt.Fprintln(dockerCLI.Out(), o.Name)
_, _ = fmt.Fprintf(dockerCLI.Err(), "Successfully created context %q\n", o.Name)
_, _ = fmt.Fprintln(dockerCLI.Out(), opts.name)
_, _ = fmt.Fprintf(dockerCLI.Err(), "Successfully created context %q\n", opts.name)
}
return err
}
func createNewContext(contextStore store.ReaderWriter, o *CreateOptions) error {
if o.Docker == nil {
func createNewContext(contextStore store.ReaderWriter, opts *createOptions) error {
if opts.endpoint == nil {
return errors.New("docker endpoint configuration is required")
}
dockerEP, dockerTLS, err := getDockerEndpointMetadataAndTLS(contextStore, o.Docker)
dockerEP, dockerTLS, err := getDockerEndpointMetadataAndTLS(contextStore, opts.endpoint)
if err != nil {
return fmt.Errorf("unable to create docker endpoint config: %w", err)
}
@ -98,10 +127,10 @@ func createNewContext(contextStore store.ReaderWriter, o *CreateOptions) error {
docker.DockerEndpoint: dockerEP,
},
Metadata: command.DockerContext{
Description: o.Description,
AdditionalFields: o.metaData,
Description: opts.description,
AdditionalFields: opts.metaData,
},
Name: o.Name,
Name: opts.name,
}
contextTLSData := store.ContextTLSData{}
if dockerTLS != nil {
@ -115,14 +144,14 @@ func createNewContext(contextStore store.ReaderWriter, o *CreateOptions) error {
if err := contextStore.CreateOrUpdate(contextMetadata); err != nil {
return err
}
return contextStore.ResetTLSMaterial(o.Name, &contextTLSData)
return contextStore.ResetTLSMaterial(opts.name, &contextTLSData)
}
func checkContextNameForCreation(s store.Reader, name string) error {
if err := store.ValidateContextName(name); err != nil {
return err
}
if _, err := s.GetMetadata(name); !cerrdefs.IsNotFound(err) {
if _, err := s.GetMetadata(name); !errdefs.IsNotFound(err) {
if err != nil {
return fmt.Errorf("error while getting existing contexts: %w", err)
}
@ -131,16 +160,16 @@ func checkContextNameForCreation(s store.Reader, name string) error {
return nil
}
func createFromExistingContext(s store.ReaderWriter, fromContextName string, o *CreateOptions) error {
if len(o.Docker) != 0 {
func createFromExistingContext(s store.ReaderWriter, fromContextName string, opts *createOptions) error {
if len(opts.endpoint) != 0 {
return errors.New("cannot use --docker flag when --from is set")
}
reader := store.Export(fromContextName, &descriptionDecorator{
Reader: s,
description: o.Description,
description: opts.description,
})
defer reader.Close()
return store.Import(o.Name, s, reader)
return store.Import(opts.name, s, reader)
}
type descriptionDecorator struct {

View File

@ -60,7 +60,7 @@ func TestCreate(t *testing.T) {
assert.NilError(t, cli.ContextStore().CreateOrUpdate(store.Metadata{Name: "existing-context"}))
tests := []struct {
doc string
options CreateOptions
options createOptions
expecterErr string
}{
{
@ -69,30 +69,30 @@ func TestCreate(t *testing.T) {
},
{
doc: "reserved name",
options: CreateOptions{
Name: "default",
options: createOptions{
name: "default",
},
expecterErr: `"default" is a reserved context name`,
},
{
doc: "whitespace-only name",
options: CreateOptions{
Name: " ",
options: createOptions{
name: " ",
},
expecterErr: `context name " " is invalid`,
},
{
doc: "existing context",
options: CreateOptions{
Name: "existing-context",
options: createOptions{
name: "existing-context",
},
expecterErr: `context "existing-context" already exists`,
},
{
doc: "invalid docker host",
options: CreateOptions{
Name: "invalid-docker-host",
Docker: map[string]string{
options: createOptions{
name: "invalid-docker-host",
endpoint: map[string]string{
"host": "some///invalid/host",
},
},
@ -100,27 +100,27 @@ func TestCreate(t *testing.T) {
},
{
doc: "ssh host with skip-tls-verify=false",
options: CreateOptions{
Name: "skip-tls-verify-false",
Docker: map[string]string{
options: createOptions{
name: "skip-tls-verify-false",
endpoint: map[string]string{
"host": "ssh://example.com,skip-tls-verify=false",
},
},
},
{
doc: "ssh host with skip-tls-verify=true",
options: CreateOptions{
Name: "skip-tls-verify-true",
Docker: map[string]string{
options: createOptions{
name: "skip-tls-verify-true",
endpoint: map[string]string{
"host": "ssh://example.com,skip-tls-verify=true",
},
},
},
{
doc: "ssh host with skip-tls-verify=INVALID",
options: CreateOptions{
Name: "skip-tls-verify-invalid",
Docker: map[string]string{
options: createOptions{
name: "skip-tls-verify-invalid",
endpoint: map[string]string{
"host": "ssh://example.com",
"skip-tls-verify": "INVALID",
},
@ -129,9 +129,9 @@ func TestCreate(t *testing.T) {
},
{
doc: "unknown option",
options: CreateOptions{
Name: "unknown-option",
Docker: map[string]string{
options: createOptions{
name: "unknown-option",
endpoint: map[string]string{
"UNKNOWN": "value",
},
},
@ -140,7 +140,7 @@ func TestCreate(t *testing.T) {
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
err := RunCreate(cli, &tc.options)
err := runCreate(cli, &tc.options)
if tc.expecterErr == "" {
assert.NilError(t, err)
} else {
@ -159,9 +159,9 @@ func assertContextCreateLogging(t *testing.T, cli *test.FakeCli, n string) {
func TestCreateOrchestratorEmpty(t *testing.T) {
cli := makeFakeCli(t)
err := RunCreate(cli, &CreateOptions{
Name: "test",
Docker: map[string]string{},
err := runCreate(cli, &createOptions{
name: "test",
endpoint: map[string]string{},
})
assert.NilError(t, err)
assertContextCreateLogging(t, cli, "test")
@ -187,20 +187,20 @@ func TestCreateFromContext(t *testing.T) {
cli := makeFakeCli(t)
cli.ResetOutputBuffers()
assert.NilError(t, RunCreate(cli, &CreateOptions{
Name: "original",
Description: "original description",
Docker: map[string]string{
assert.NilError(t, runCreate(cli, &createOptions{
name: "original",
description: "original description",
endpoint: map[string]string{
keyHost: "tcp://42.42.42.42:2375",
},
}))
assertContextCreateLogging(t, cli, "original")
cli.ResetOutputBuffers()
assert.NilError(t, RunCreate(cli, &CreateOptions{
Name: "dummy",
Description: "dummy description",
Docker: map[string]string{
assert.NilError(t, runCreate(cli, &createOptions{
name: "dummy",
description: "dummy description",
endpoint: map[string]string{
keyHost: "tcp://24.24.24.24:2375",
},
}))
@ -211,11 +211,11 @@ func TestCreateFromContext(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cli.ResetOutputBuffers()
err := RunCreate(cli, &CreateOptions{
From: "original",
Name: tc.name,
Description: tc.description,
Docker: tc.docker,
err := runCreate(cli, &createOptions{
from: "original",
name: tc.name,
description: tc.description,
endpoint: tc.docker,
})
assert.NilError(t, err)
assertContextCreateLogging(t, cli, tc.name)
@ -251,10 +251,10 @@ func TestCreateFromCurrent(t *testing.T) {
cli := makeFakeCli(t)
cli.ResetOutputBuffers()
assert.NilError(t, RunCreate(cli, &CreateOptions{
Name: "original",
Description: "original description",
Docker: map[string]string{
assert.NilError(t, runCreate(cli, &createOptions{
name: "original",
description: "original description",
endpoint: map[string]string{
keyHost: "tcp://42.42.42.42:2375",
},
}))
@ -265,9 +265,9 @@ func TestCreateFromCurrent(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cli.ResetOutputBuffers()
err := RunCreate(cli, &CreateOptions{
Name: tc.name,
Description: tc.description,
err := runCreate(cli, &createOptions{
name: tc.name,
description: tc.description,
})
assert.NilError(t, err)
assertContextCreateLogging(t, cli, tc.name)

View File

@ -21,14 +21,11 @@ func TestExportImportWithFile(t *testing.T) {
"MyCustomMetadata": t.Name(),
})
cli.ErrBuffer().Reset()
assert.NilError(t, RunExport(cli, &ExportOptions{
ContextName: "test",
Dest: contextFile,
}))
assert.NilError(t, runExport(cli, "test", contextFile))
assert.Equal(t, cli.ErrBuffer().String(), fmt.Sprintf("Written file %q\n", contextFile))
cli.OutBuffer().Reset()
cli.ErrBuffer().Reset()
assert.NilError(t, RunImport(cli, "test2", contextFile))
assert.NilError(t, runImport(cli, "test2", contextFile))
context1, err := cli.ContextStore().GetMetadata("test")
assert.NilError(t, err)
context2, err := cli.ContextStore().GetMetadata("test2")
@ -55,15 +52,12 @@ func TestExportImportPipe(t *testing.T) {
})
cli.ErrBuffer().Reset()
cli.OutBuffer().Reset()
assert.NilError(t, RunExport(cli, &ExportOptions{
ContextName: "test",
Dest: "-",
}))
assert.NilError(t, runExport(cli, "test", "-"))
assert.Equal(t, cli.ErrBuffer().String(), "")
cli.SetIn(streams.NewIn(io.NopCloser(bytes.NewBuffer(cli.OutBuffer().Bytes()))))
cli.OutBuffer().Reset()
cli.ErrBuffer().Reset()
assert.NilError(t, RunImport(cli, "test2", "-"))
assert.NilError(t, runImport(cli, "test2", "-"))
context1, err := cli.ContextStore().GetMetadata("test")
assert.NilError(t, err)
context2, err := cli.ContextStore().GetMetadata("test2")
@ -88,6 +82,6 @@ func TestExportExistingFile(t *testing.T) {
cli := makeFakeCli(t)
cli.ErrBuffer().Reset()
assert.NilError(t, os.WriteFile(contextFile, []byte{}, 0o644))
err := RunExport(cli, &ExportOptions{ContextName: "test", Dest: contextFile})
err := runExport(cli, "test", contextFile)
assert.Assert(t, os.IsExist(err))
}

View File

@ -13,6 +13,8 @@ import (
)
// ExportOptions are the options used for exporting a context
//
// Deprecated: this type was for internal use and will be removed in the next release.
type ExportOptions struct {
ContextName string
Dest string
@ -24,15 +26,14 @@ func newExportCommand(dockerCLI command.Cli) *cobra.Command {
Short: "Export a context to a tar archive FILE or a tar stream on STDOUT.",
Args: cli.RequiresRangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
opts := &ExportOptions{
ContextName: args[0],
}
contextName := args[0]
var dest string
if len(args) == 2 {
opts.Dest = args[1]
dest = args[1]
} else {
opts.Dest = opts.ContextName + ".dockercontext"
dest = contextName + ".dockercontext"
}
return RunExport(dockerCLI, opts)
return runExport(dockerCLI, contextName, dest)
},
ValidArgsFunction: completeContextNames(dockerCLI, 1, true),
}
@ -65,11 +66,21 @@ func writeTo(dockerCli command.Cli, reader io.Reader, dest string) error {
}
// RunExport exports a Docker context
//
// Deprecated: this function was for internal use and will be removed in the next release.
func RunExport(dockerCli command.Cli, opts *ExportOptions) error {
if err := store.ValidateContextName(opts.ContextName); err != nil && opts.ContextName != command.DefaultContextName {
if opts == nil {
opts = &ExportOptions{}
}
return runExport(dockerCli, opts.ContextName, opts.Dest)
}
// runExport exports a Docker context.
func runExport(dockerCLI command.Cli, contextName string, dest string) error {
if err := store.ValidateContextName(contextName); err != nil && contextName != command.DefaultContextName {
return err
}
reader := store.Export(opts.ContextName, dockerCli.ContextStore())
reader := store.Export(contextName, dockerCLI.ContextStore())
defer reader.Close()
return writeTo(dockerCli, reader, opts.Dest)
return writeTo(dockerCLI, reader, dest)
}

View File

@ -18,7 +18,7 @@ func newImportCommand(dockerCli command.Cli) *cobra.Command {
Short: "Import a context from a tar or zip file",
Args: cli.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return RunImport(dockerCli, args[0], args[1])
return runImport(dockerCli, args[0], args[1])
},
// TODO(thaJeztah): this should also include "-"
ValidArgsFunction: completion.FileNames,
@ -27,14 +27,21 @@ func newImportCommand(dockerCli command.Cli) *cobra.Command {
}
// RunImport imports a Docker context
func RunImport(dockerCli command.Cli, name string, source string) error {
if err := checkContextNameForCreation(dockerCli.ContextStore(), name); err != nil {
//
// Deprecated: this function was for internal use and will be removed in the next release.
func RunImport(dockerCLI command.Cli, name string, source string) error {
return runImport(dockerCLI, name, source)
}
// runImport imports a Docker context.
func runImport(dockerCLI command.Cli, name string, source string) error {
if err := checkContextNameForCreation(dockerCLI.ContextStore(), name); err != nil {
return err
}
var reader io.Reader
if source == "-" {
reader = dockerCli.In()
reader = dockerCLI.In()
} else {
f, err := os.Open(source)
if err != nil {
@ -44,11 +51,11 @@ func RunImport(dockerCli command.Cli, name string, source string) error {
reader = f
}
if err := store.Import(name, dockerCli.ContextStore(), reader); err != nil {
if err := store.Import(name, dockerCLI.ContextStore(), reader); err != nil {
return err
}
_, _ = fmt.Fprintln(dockerCli.Out(), name)
_, _ = fmt.Fprintf(dockerCli.Err(), "Successfully imported context %q\n", name)
_, _ = fmt.Fprintln(dockerCLI.Out(), name)
_, _ = fmt.Fprintf(dockerCLI.Err(), "Successfully imported context %q\n", name)
return nil
}

View File

@ -10,7 +10,6 @@ import (
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/cli/cli/context/docker"
flagsHelper "github.com/docker/cli/cli/flags"
@ -34,7 +33,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCli, opts)
},
ValidArgsFunction: completion.NoComplete,
ValidArgsFunction: cobra.NoFileCompletions,
}
flags := cmd.Flags()

Some files were not shown because too many files have changed in this diff Show More