Merge pull request #4700 from thaJeztah/wire_up_contexts

Plumb contexts through commands
This commit is contained in:
Sebastiaan van Stijn 2023-12-13 22:29:51 +01:00 committed by GitHub
commit ae2b58fd98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
146 changed files with 409 additions and 470 deletions

View File

@ -30,7 +30,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove build cache", Short: "Remove build cache",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
spaceReclaimed, output, err := runPrune(dockerCli, options) spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options)
if err != nil { if err != nil {
return err return err
} }
@ -58,7 +58,7 @@ const (
allCacheWarning = `WARNING! This will remove all build cache. Are you sure you want to continue?` allCacheWarning = `WARNING! This will remove all build cache. Are you sure you want to continue?`
) )
func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
pruneFilters := options.filter.Value() pruneFilters := options.filter.Value()
pruneFilters = command.PruneFilters(dockerCli, pruneFilters) pruneFilters = command.PruneFilters(dockerCli, pruneFilters)
@ -70,7 +70,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6
return 0, "", nil return 0, "", nil
} }
report, err := dockerCli.Client().BuildCachePrune(context.Background(), types.BuildCachePruneOptions{ report, err := dockerCli.Client().BuildCachePrune(ctx, types.BuildCachePruneOptions{
All: options.all, All: options.all,
KeepStorage: options.keepStorage.Value(), KeepStorage: options.keepStorage.Value(),
Filters: pruneFilters, Filters: pruneFilters,
@ -93,6 +93,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6
} }
// CachePrune executes a prune command for build cache // CachePrune executes a prune command for build cache
func CachePrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { func CachePrune(ctx context.Context, dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
return runPrune(dockerCli, pruneOptions{force: true, all: all, filter: filter}) return runPrune(ctx, dockerCli, pruneOptions{force: true, all: all, filter: filter})
} }

View File

@ -28,7 +28,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0] opts.container = args[0]
opts.checkpoint = args[1] opts.checkpoint = args[1]
return runCreate(dockerCli, opts) return runCreate(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -40,8 +40,8 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runCreate(dockerCli command.Cli, opts createOptions) error { func runCreate(ctx context.Context, dockerCli command.Cli, opts createOptions) error {
err := dockerCli.Client().CheckpointCreate(context.Background(), opts.container, checkpoint.CreateOptions{ err := dockerCli.Client().CheckpointCreate(ctx, opts.container, checkpoint.CreateOptions{
CheckpointID: opts.checkpoint, CheckpointID: opts.checkpoint,
CheckpointDir: opts.checkpointDir, CheckpointDir: opts.checkpointDir,
Exit: !opts.leaveRunning, Exit: !opts.leaveRunning,

View File

@ -24,7 +24,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List checkpoints for a container", Short: "List checkpoints for a container",
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCli, args[0], opts) return runList(cmd.Context(), dockerCli, args[0], opts)
}, },
ValidArgsFunction: completion.ContainerNames(dockerCli, false), ValidArgsFunction: completion.ContainerNames(dockerCli, false),
} }
@ -35,8 +35,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runList(dockerCli command.Cli, container string, opts listOptions) error { func runList(ctx context.Context, dockerCli command.Cli, container string, opts listOptions) error {
checkpoints, err := dockerCli.Client().CheckpointList(context.Background(), container, checkpoint.ListOptions{ checkpoints, err := dockerCli.Client().CheckpointList(ctx, container, checkpoint.ListOptions{
CheckpointDir: opts.checkpointDir, CheckpointDir: opts.checkpointDir,
}) })
if err != nil { if err != nil {

View File

@ -22,7 +22,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove a checkpoint", Short: "Remove a checkpoint",
Args: cli.ExactArgs(2), Args: cli.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRemove(dockerCli, args[0], args[1], opts) return runRemove(cmd.Context(), dockerCli, args[0], args[1], opts)
}, },
} }
@ -32,8 +32,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRemove(dockerCli command.Cli, container string, checkpointID string, opts removeOptions) error { func runRemove(ctx context.Context, dockerCli command.Cli, container string, checkpointID string, opts removeOptions) error {
return dockerCli.Client().CheckpointDelete(context.Background(), container, checkpoint.DeleteOptions{ return dockerCli.Client().CheckpointDelete(ctx, container, checkpoint.DeleteOptions{
CheckpointID: checkpointID, CheckpointID: checkpointID,
CheckpointDir: opts.checkpointDir, CheckpointDir: opts.checkpointDir,
}) })

View File

@ -82,6 +82,11 @@ type DockerCli struct {
dockerEndpoint docker.Endpoint dockerEndpoint docker.Endpoint
contextStoreConfig store.Config contextStoreConfig store.Config
initTimeout time.Duration initTimeout time.Duration
// baseCtx is the base context used for internal operations. In the future
// this may be replaced by explicitly passing a context to functions that
// need it.
baseCtx context.Context
} }
// DefaultVersion returns api.defaultVersion. // DefaultVersion returns api.defaultVersion.
@ -320,8 +325,7 @@ func (cli *DockerCli) getInitTimeout() time.Duration {
} }
func (cli *DockerCli) initializeFromClient() { func (cli *DockerCli) initializeFromClient() {
ctx := context.Background() ctx, cancel := context.WithTimeout(cli.baseCtx, cli.getInitTimeout())
ctx, cancel := context.WithTimeout(ctx, cli.getInitTimeout())
defer cancel() defer cancel()
ping, err := cli.client.Ping(ctx) ping, err := cli.client.Ping(ctx)
@ -441,6 +445,9 @@ func (cli *DockerCli) initialize() error {
return return
} }
} }
if cli.baseCtx == nil {
cli.baseCtx = context.Background()
}
cli.initializeFromClient() cli.initializeFromClient()
}) })
return cli.initErr return cli.initErr
@ -484,7 +491,7 @@ func NewDockerCli(ops ...CLIOption) (*DockerCli, error) {
} }
ops = append(defaultOps, ops...) ops = append(defaultOps, ops...)
cli := &DockerCli{} cli := &DockerCli{baseCtx: context.Background()}
if err := cli.Apply(ops...); err != nil { if err := cli.Apply(ops...); err != nil {
return nil, err return nil, err
} }

View File

@ -1,6 +1,7 @@
package command package command
import ( import (
"context"
"io" "io"
"os" "os"
"strconv" "strconv"
@ -35,6 +36,15 @@ func WithStandardStreams() CLIOption {
} }
} }
// WithBaseContext sets the base context of a cli. It is used to propagate
// the context from the command line to the client.
func WithBaseContext(ctx context.Context) CLIOption {
return func(cli *DockerCli) error {
cli.baseCtx = ctx
return nil
}
}
// WithCombinedStreams uses the same stream for the output and error streams. // WithCombinedStreams uses the same stream for the output and error streams.
func WithCombinedStreams(combined io.Writer) CLIOption { func WithCombinedStreams(combined io.Writer) CLIOption {
return func(cli *DockerCli) error { return func(cli *DockerCli) error {

View File

@ -35,7 +35,7 @@ func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
createOpts.Name = args[0] createOpts.Name = args[0]
createOpts.File = args[1] createOpts.File = args[1]
return RunConfigCreate(dockerCli, createOpts) return RunConfigCreate(cmd.Context(), dockerCli, createOpts)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -48,9 +48,8 @@ func newConfigCreateCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunConfigCreate creates a config with the given options. // RunConfigCreate creates a config with the given options.
func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error { func RunConfigCreate(ctx context.Context, dockerCli command.Cli, options CreateOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
var in io.Reader = dockerCli.In() var in io.Reader = dockerCli.In()
if options.File != "-" { if options.File != "-" {

View File

@ -27,7 +27,7 @@ func newConfigInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.Names = args opts.Names = args
return RunConfigInspect(dockerCli, opts) return RunConfigInspect(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete) return completeNames(dockerCli)(cmd, args, toComplete)
@ -40,9 +40,8 @@ func newConfigInspectCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunConfigInspect inspects the given Swarm config. // RunConfigInspect inspects the given Swarm config.
func RunConfigInspect(dockerCli command.Cli, opts InspectOptions) error { func RunConfigInspect(ctx context.Context, dockerCli command.Cli, opts InspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
if opts.Pretty { if opts.Pretty {
opts.Format = "pretty" opts.Format = "pretty"

View File

@ -31,7 +31,7 @@ func newConfigListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List configs", Short: "List configs",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return RunConfigList(dockerCli, listOpts) return RunConfigList(cmd.Context(), dockerCli, listOpts)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -45,9 +45,8 @@ func newConfigListCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunConfigList lists Swarm configs. // RunConfigList lists Swarm configs.
func RunConfigList(dockerCli command.Cli, options ListOptions) error { func RunConfigList(ctx context.Context, dockerCli command.Cli, options ListOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
configs, err := client.ConfigList(ctx, types.ConfigListOptions{Filters: options.Filter.Value()}) configs, err := client.ConfigList(ctx, types.ConfigListOptions{Filters: options.Filter.Value()})
if err != nil { if err != nil {

View File

@ -26,7 +26,7 @@ func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command {
opts := RemoveOptions{ opts := RemoveOptions{
Names: args, Names: args,
} }
return RunConfigRemove(dockerCli, opts) return RunConfigRemove(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete) return completeNames(dockerCli)(cmd, args, toComplete)
@ -35,9 +35,8 @@ func newConfigRemoveCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunConfigRemove removes the given Swarm configs. // RunConfigRemove removes the given Swarm configs.
func RunConfigRemove(dockerCli command.Cli, opts RemoveOptions) error { func RunConfigRemove(ctx context.Context, dockerCli command.Cli, opts RemoveOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
var errs []string var errs []string

View File

@ -53,7 +53,7 @@ func NewAttachCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
ctr = args[0] ctr = args[0]
return RunAttach(context.Background(), dockerCli, ctr, &opts) return RunAttach(cmd.Context(), dockerCli, ctr, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container attach, docker attach", "aliases": "docker container attach, docker attach",

View File

@ -35,7 +35,7 @@ func NewCommitCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
options.reference = args[1] options.reference = args[1]
} }
return runCommit(dockerCli, &options) return runCommit(cmd.Context(), dockerCli, &options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container commit, docker commit", "aliases": "docker container commit, docker commit",
@ -56,9 +56,7 @@ func NewCommitCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runCommit(dockerCli command.Cli, options *commitOptions) error { func runCommit(ctx context.Context, dockerCli command.Cli, options *commitOptions) error {
ctx := context.Background()
response, err := dockerCli.Client().ContainerCommit(ctx, options.container, container.CommitOptions{ response, err := dockerCli.Client().ContainerCommit(ctx, options.container, container.CommitOptions{
Reference: options.reference, Reference: options.reference,
Comment: options.comment, Comment: options.comment,

View File

@ -151,7 +151,7 @@ func NewCopyCommand(dockerCli command.Cli) *cobra.Command {
// User did not specify "quiet" flag; suppress output if no terminal is attached // 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(dockerCli, opts) return runCopy(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container cp, docker cp", "aliases": "docker container cp, docker cp",
@ -169,7 +169,7 @@ func progressHumanSize(n int64) string {
return units.HumanSizeWithPrecision(float64(n), 3) return units.HumanSizeWithPrecision(float64(n), 3)
} }
func runCopy(dockerCli command.Cli, opts copyOptions) error { func runCopy(ctx context.Context, dockerCli command.Cli, opts copyOptions) error {
srcContainer, srcPath := splitCpArg(opts.source) srcContainer, srcPath := splitCpArg(opts.source)
destContainer, destPath := splitCpArg(opts.destination) destContainer, destPath := splitCpArg(opts.destination)
@ -191,8 +191,6 @@ func runCopy(dockerCli command.Cli, opts copyOptions) error {
copyConfig.container = destContainer copyConfig.container = destContainer
} }
ctx := context.Background()
switch direction { switch direction {
case fromContainer: case fromContainer:
return copyFromContainer(ctx, dockerCli, copyConfig) return copyFromContainer(ctx, dockerCli, copyConfig)

View File

@ -1,6 +1,7 @@
package container package container
import ( import (
"context"
"io" "io"
"os" "os"
"runtime" "runtime"
@ -41,7 +42,7 @@ func TestRunCopyWithInvalidArguments(t *testing.T) {
} }
for _, testcase := range testcases { for _, testcase := range testcases {
t.Run(testcase.doc, func(t *testing.T) { t.Run(testcase.doc, func(t *testing.T) {
err := runCopy(test.NewFakeCli(nil), testcase.options) err := runCopy(context.TODO(), test.NewFakeCli(nil), testcase.options)
assert.Error(t, err, testcase.expectedErr) assert.Error(t, err, testcase.expectedErr)
}) })
} }
@ -58,7 +59,7 @@ func TestRunCopyFromContainerToStdout(t *testing.T) {
} }
options := copyOptions{source: "container:/path", destination: "-"} options := copyOptions{source: "container:/path", destination: "-"}
cli := test.NewFakeCli(fakeClient) cli := test.NewFakeCli(fakeClient)
err := runCopy(cli, options) err := runCopy(context.TODO(), cli, options)
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal(tarContent, cli.OutBuffer().String())) assert.Check(t, is.Equal(tarContent, cli.OutBuffer().String()))
assert.Check(t, is.Equal("", cli.ErrBuffer().String())) assert.Check(t, is.Equal("", cli.ErrBuffer().String()))
@ -78,7 +79,7 @@ func TestRunCopyFromContainerToFilesystem(t *testing.T) {
} }
options := copyOptions{source: "container:/path", destination: destDir.Path(), quiet: true} options := copyOptions{source: "container:/path", destination: destDir.Path(), quiet: true}
cli := test.NewFakeCli(fakeClient) cli := test.NewFakeCli(fakeClient)
err := runCopy(cli, options) err := runCopy(context.TODO(), cli, options)
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal("", cli.OutBuffer().String())) assert.Check(t, is.Equal("", cli.OutBuffer().String()))
assert.Check(t, is.Equal("", cli.ErrBuffer().String())) assert.Check(t, is.Equal("", cli.ErrBuffer().String()))
@ -106,7 +107,7 @@ func TestRunCopyFromContainerToFilesystemMissingDestinationDirectory(t *testing.
destination: destDir.Join("missing", "foo"), destination: destDir.Join("missing", "foo"),
} }
cli := test.NewFakeCli(fakeClient) cli := test.NewFakeCli(fakeClient)
err := runCopy(cli, options) err := runCopy(context.TODO(), cli, options)
assert.ErrorContains(t, err, destDir.Join("missing")) assert.ErrorContains(t, err, destDir.Join("missing"))
} }
@ -119,7 +120,7 @@ func TestRunCopyToContainerFromFileWithTrailingSlash(t *testing.T) {
destination: "container:/path", destination: "container:/path",
} }
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
err := runCopy(cli, options) err := runCopy(context.TODO(), cli, options)
expectedError := "not a directory" expectedError := "not a directory"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
@ -134,7 +135,7 @@ func TestRunCopyToContainerSourceDoesNotExist(t *testing.T) {
destination: "container:/path", destination: "container:/path",
} }
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
err := runCopy(cli, options) err := runCopy(context.TODO(), cli, options)
expected := "no such file or directory" expected := "no such file or directory"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
expected = "cannot find the file specified" expected = "cannot find the file specified"
@ -193,7 +194,7 @@ func TestSplitCpArg(t *testing.T) {
func TestRunCopyFromContainerToFilesystemIrregularDestination(t *testing.T) { func TestRunCopyFromContainerToFilesystemIrregularDestination(t *testing.T) {
options := copyOptions{source: "container:/dev/null", destination: "/dev/random"} options := copyOptions{source: "container:/dev/null", destination: "/dev/random"}
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
err := runCopy(cli, options) err := runCopy(context.TODO(), cli, options)
assert.Assert(t, err != nil) assert.Assert(t, err != nil)
expected := `"/dev/random" must be a directory or a regular file` expected := `"/dev/random" must be a directory or a regular file`
assert.ErrorContains(t, err, expected) assert.ErrorContains(t, err, expected)

View File

@ -55,7 +55,7 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
copts.Args = args[1:] copts.Args = args[1:]
} }
return runCreate(dockerCli, cmd.Flags(), &options, copts) return runCreate(cmd.Context(), dockerCli, cmd.Flags(), &options, copts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container create, docker create", "aliases": "docker container create, docker create",
@ -80,7 +80,7 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error { func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, options *createOptions, copts *containerOptions) error {
if err := validatePullOpt(options.pull); err != nil { if err := validatePullOpt(options.pull); err != nil {
reportError(dockerCli.Err(), "create", err.Error(), true) reportError(dockerCli.Err(), "create", err.Error(), true)
return cli.StatusError{StatusCode: 125} return cli.StatusError{StatusCode: 125}
@ -104,7 +104,7 @@ func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, options *createOptio
reportError(dockerCli.Err(), "create", err.Error(), true) reportError(dockerCli.Err(), "create", err.Error(), true)
return cli.StatusError{StatusCode: 125} return cli.StatusError{StatusCode: 125}
} }
id, err := createContainer(context.Background(), dockerCli, containerCfg, options) id, err := createContainer(ctx, dockerCli, containerCfg, options)
if err != nil { if err != nil {
return err return err
} }

View File

@ -181,6 +181,7 @@ func TestCreateContainerImagePullPolicyInvalid(t *testing.T) {
t.Run(tc.PullPolicy, func(t *testing.T) { t.Run(tc.PullPolicy, func(t *testing.T) {
dockerCli := test.NewFakeCli(&fakeClient{}) dockerCli := test.NewFakeCli(&fakeClient{})
err := runCreate( err := runCreate(
context.TODO(),
dockerCli, dockerCli,
&pflag.FlagSet{}, &pflag.FlagSet{},
&createOptions{pull: tc.PullPolicy}, &createOptions{pull: tc.PullPolicy},

View File

@ -25,7 +25,7 @@ func NewDiffCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0] opts.container = args[0]
return runDiff(dockerCli, &opts) return runDiff(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container diff, docker diff", "aliases": "docker container diff, docker diff",
@ -34,12 +34,10 @@ func NewDiffCommand(dockerCli command.Cli) *cobra.Command {
} }
} }
func runDiff(dockerCli command.Cli, opts *diffOptions) error { func runDiff(ctx context.Context, dockerCli command.Cli, opts *diffOptions) error {
if opts.container == "" { if opts.container == "" {
return errors.New("Container name cannot be empty") return errors.New("Container name cannot be empty")
} }
ctx := context.Background()
changes, err := dockerCli.Client().ContainerDiff(ctx, opts.container) changes, err := dockerCli.Client().ContainerDiff(ctx, opts.container)
if err != nil { if err != nil {
return err return err

View File

@ -52,7 +52,7 @@ func NewExecCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
container = args[0] container = args[0]
options.Command = args[1:] options.Command = args[1:]
return RunExec(context.Background(), dockerCli, container, options) return RunExec(cmd.Context(), dockerCli, container, options)
}, },
ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool { ValidArgsFunction: completion.ContainerNames(dockerCli, false, func(container types.Container) bool {
return container.State != "paused" return container.State != "paused"

View File

@ -192,16 +192,16 @@ func TestRunExec(t *testing.T) {
for _, testcase := range testcases { for _, testcase := range testcases {
t.Run(testcase.doc, func(t *testing.T) { t.Run(testcase.doc, func(t *testing.T) {
cli := test.NewFakeCli(&testcase.client) fakeCLI := test.NewFakeCli(&testcase.client)
err := RunExec(context.Background(), cli, "thecontainer", testcase.options) err := RunExec(context.TODO(), fakeCLI, "thecontainer", testcase.options)
if testcase.expectedError != "" { if testcase.expectedError != "" {
assert.ErrorContains(t, err, testcase.expectedError) assert.ErrorContains(t, err, testcase.expectedError)
} else if !assert.Check(t, err) { } else if !assert.Check(t, err) {
return return
} }
assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String())) assert.Check(t, is.Equal(testcase.expectedOut, fakeCLI.OutBuffer().String()))
assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String())) assert.Check(t, is.Equal(testcase.expectedErr, fakeCLI.ErrBuffer().String()))
}) })
} }
} }

View File

@ -26,7 +26,7 @@ func NewExportCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0] opts.container = args[0]
return runExport(dockerCli, opts) return runExport(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container export, docker export", "aliases": "docker container export, docker export",
@ -41,7 +41,7 @@ func NewExportCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runExport(dockerCli command.Cli, opts exportOptions) error { func runExport(ctx context.Context, dockerCli command.Cli, opts exportOptions) error {
if opts.output == "" && dockerCli.Out().IsTerminal() { if opts.output == "" && dockerCli.Out().IsTerminal() {
return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect")
} }
@ -52,7 +52,7 @@ func runExport(dockerCli command.Cli, opts exportOptions) error {
clnt := dockerCli.Client() clnt := dockerCli.Client()
responseBody, err := clnt.ContainerExport(context.Background(), opts.container) responseBody, err := clnt.ContainerExport(ctx, opts.container)
if err != nil { if err != nil {
return err return err
} }

View File

@ -27,7 +27,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.refs = args opts.refs = args
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: completion.ContainerNames(dockerCli, true), ValidArgsFunction: completion.ContainerNames(dockerCli, true),
} }
@ -39,9 +39,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
getRefFunc := func(ref string) (any, []byte, error) { getRefFunc := func(ref string) (any, []byte, error) {
return client.ContainerInspectWithRaw(ctx, ref, opts.size) return client.ContainerInspectWithRaw(ctx, ref, opts.size)

View File

@ -28,7 +28,7 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
return runKill(dockerCli, &opts) return runKill(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container kill, docker kill", "aliases": "docker container kill, docker kill",
@ -41,9 +41,8 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runKill(dockerCli command.Cli, opts *killOptions) error { func runKill(ctx context.Context, dockerCli command.Cli, opts *killOptions) error {
var errs []string var errs []string
ctx := context.Background()
errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error { errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
return dockerCli.Client().ContainerKill(ctx, container, opts.signal) return dockerCli.Client().ContainerKill(ctx, container, opts.signal)
}) })

View File

@ -38,7 +38,7 @@ func NewPsCommand(dockerCLI command.Cli) *cobra.Command {
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.sizeChanged = cmd.Flags().Changed("size") options.sizeChanged = cmd.Flags().Changed("size")
return runPs(dockerCLI, &options) return runPs(cmd.Context(), dockerCLI, &options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "3", "category-top": "3",
@ -114,9 +114,7 @@ func buildContainerListOptions(options *psOptions) (*container.ListOptions, erro
return listOptions, nil return listOptions, nil
} }
func runPs(dockerCLI command.Cli, options *psOptions) error { func runPs(ctx context.Context, dockerCLI command.Cli, options *psOptions) error {
ctx := context.Background()
if len(options.format) == 0 { if len(options.format) == 0 {
// load custom psFormat from CLI config (if any) // load custom psFormat from CLI config (if any)
options.format = dockerCLI.ConfigFile().PsFormat options.format = dockerCLI.ConfigFile().PsFormat

View File

@ -33,7 +33,7 @@ func NewLogsCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0] opts.container = args[0]
return runLogs(dockerCli, &opts) return runLogs(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container logs, docker logs", "aliases": "docker container logs, docker logs",
@ -52,9 +52,7 @@ func NewLogsCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runLogs(dockerCli command.Cli, opts *logsOptions) error { func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) error {
ctx := context.Background()
c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
if err != nil { if err != nil {
return err return err

View File

@ -1,6 +1,7 @@
package container package container
import ( import (
"context"
"io" "io"
"strings" "strings"
"testing" "testing"
@ -46,7 +47,7 @@ func TestRunLogs(t *testing.T) {
t.Run(testcase.doc, func(t *testing.T) { t.Run(testcase.doc, func(t *testing.T) {
cli := test.NewFakeCli(&testcase.client) cli := test.NewFakeCli(&testcase.client)
err := runLogs(cli, testcase.options) err := runLogs(context.TODO(), cli, testcase.options)
if testcase.expectedError != "" { if testcase.expectedError != "" {
assert.ErrorContains(t, err, testcase.expectedError) assert.ErrorContains(t, err, testcase.expectedError)
} else if !assert.Check(t, err) { } else if !assert.Check(t, err) {

View File

@ -27,7 +27,7 @@ func NewPauseCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
return runPause(dockerCli, &opts) return runPause(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container pause, docker pause", "aliases": "docker container pause, docker pause",
@ -38,9 +38,7 @@ func NewPauseCommand(dockerCli command.Cli) *cobra.Command {
} }
} }
func runPause(dockerCli command.Cli, opts *pauseOptions) error { func runPause(ctx context.Context, dockerCli command.Cli, opts *pauseOptions) error {
ctx := context.Background()
var errs []string var errs []string
errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerPause) errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerPause)
for _, container := range opts.containers { for _, container := range opts.containers {

View File

@ -36,7 +36,7 @@ func NewPortCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
opts.port = args[1] opts.port = args[1]
} }
return runPort(dockerCli, &opts) return runPort(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container port, docker port", "aliases": "docker container port, docker port",
@ -52,9 +52,7 @@ func NewPortCommand(dockerCli command.Cli) *cobra.Command {
// TODO(thaJeztah): currently this defaults to show the TCP port if no // TODO(thaJeztah): currently this defaults to show the TCP port if no
// proto is specified. We should consider changing this to "any" protocol // proto is specified. We should consider changing this to "any" protocol
// for the given private port. // for the given private port.
func runPort(dockerCli command.Cli, opts *portOptions) error { func runPort(ctx context.Context, dockerCli command.Cli, opts *portOptions) error {
ctx := context.Background()
c, err := dockerCli.Client().ContainerInspect(ctx, opts.container) c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
if err != nil { if err != nil {
return err return err

View File

@ -26,7 +26,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove all stopped containers", Short: "Remove all stopped containers",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
spaceReclaimed, output, err := runPrune(dockerCli, options) spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options)
if err != nil { if err != nil {
return err return err
} }
@ -50,14 +50,14 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
const warning = `WARNING! This will remove all stopped containers. const warning = `WARNING! This will remove all stopped containers.
Are you sure you want to continue?` Are you sure you want to continue?`
func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
return 0, "", nil return 0, "", nil
} }
report, err := dockerCli.Client().ContainersPrune(context.Background(), pruneFilters) report, err := dockerCli.Client().ContainersPrune(ctx, pruneFilters)
if err != nil { if err != nil {
return 0, "", err return 0, "", err
} }
@ -75,6 +75,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6
// RunPrune calls the Container Prune API // RunPrune calls the Container Prune API
// This returns the amount of space reclaimed and a detailed output string // This returns the amount of space reclaimed and a detailed output string
func RunPrune(dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { func RunPrune(ctx context.Context, dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) {
return runPrune(dockerCli, pruneOptions{force: true, filter: filter}) return runPrune(ctx, dockerCli, pruneOptions{force: true, filter: filter})
} }

View File

@ -28,7 +28,7 @@ func NewRenameCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.oldName = args[0] opts.oldName = args[0]
opts.newName = args[1] opts.newName = args[1]
return runRename(dockerCli, &opts) return runRename(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container rename, docker rename", "aliases": "docker container rename, docker rename",
@ -38,9 +38,7 @@ func NewRenameCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRename(dockerCli command.Cli, opts *renameOptions) error { func runRename(ctx context.Context, dockerCli command.Cli, opts *renameOptions) error {
ctx := context.Background()
oldName := strings.TrimSpace(opts.oldName) oldName := strings.TrimSpace(opts.oldName)
newName := strings.TrimSpace(opts.newName) newName := strings.TrimSpace(opts.newName)

View File

@ -32,7 +32,7 @@ func NewRestartCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
opts.timeoutChanged = cmd.Flags().Changed("time") opts.timeoutChanged = cmd.Flags().Changed("time")
return runRestart(dockerCli, &opts) return runRestart(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container restart, docker restart", "aliases": "docker container restart, docker restart",
@ -46,8 +46,7 @@ func NewRestartCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRestart(dockerCli command.Cli, opts *restartOptions) error { func runRestart(ctx context.Context, dockerCli command.Cli, opts *restartOptions) error {
ctx := context.Background()
var errs []string var errs []string
var timeout *int var timeout *int
if opts.timeoutChanged { if opts.timeoutChanged {

View File

@ -33,7 +33,7 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
return runRm(dockerCli, &opts) return runRm(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container rm, docker container remove, docker rm", "aliases": "docker container rm, docker container remove, docker rm",
@ -48,9 +48,7 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRm(dockerCli command.Cli, opts *rmOptions) error { func runRm(ctx context.Context, dockerCli command.Cli, opts *rmOptions) error {
ctx := context.Background()
var errs []string var errs []string
errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, ctrID string) error { errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, ctrID string) error {
ctrID = strings.Trim(ctrID, "/") ctrID = strings.Trim(ctrID, "/")

View File

@ -42,7 +42,7 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
copts.Args = args[1:] copts.Args = args[1:]
} }
return runRun(dockerCli, cmd.Flags(), &options, copts) return runRun(cmd.Context(), dockerCli, cmd.Flags(), &options, copts)
}, },
ValidArgsFunction: completion.ImageNames(dockerCli), ValidArgsFunction: completion.ImageNames(dockerCli),
Annotations: map[string]string{ Annotations: map[string]string{
@ -89,7 +89,7 @@ func NewRunCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error { func runRun(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copts *containerOptions) error {
if err := validatePullOpt(ropts.pull); err != nil { if err := validatePullOpt(ropts.pull); err != nil {
reportError(dockerCli.Err(), "run", err.Error(), true) reportError(dockerCli.Err(), "run", err.Error(), true)
return cli.StatusError{StatusCode: 125} return cli.StatusError{StatusCode: 125}
@ -114,11 +114,11 @@ func runRun(dockerCli command.Cli, flags *pflag.FlagSet, ropts *runOptions, copt
reportError(dockerCli.Err(), "run", err.Error(), true) reportError(dockerCli.Err(), "run", err.Error(), true)
return cli.StatusError{StatusCode: 125} return cli.StatusError{StatusCode: 125}
} }
return runContainer(dockerCli, ropts, copts, containerCfg) return runContainer(ctx, dockerCli, ropts, copts, containerCfg)
} }
//nolint:gocyclo //nolint:gocyclo
func runContainer(dockerCli command.Cli, runOpts *runOptions, copts *containerOptions, containerCfg *containerConfig) error { func runContainer(ctx context.Context, dockerCli command.Cli, runOpts *runOptions, copts *containerOptions, containerCfg *containerConfig) error {
config := containerCfg.Config config := containerCfg.Config
stdout, stderr := dockerCli.Out(), dockerCli.Err() stdout, stderr := dockerCli.Out(), dockerCli.Err()
apiClient := dockerCli.Client() apiClient := dockerCli.Client()
@ -140,7 +140,7 @@ func runContainer(dockerCli command.Cli, runOpts *runOptions, copts *containerOp
config.StdinOnce = false config.StdinOnce = false
} }
ctx, cancelFun := context.WithCancel(context.Background()) ctx, cancelFun := context.WithCancel(ctx)
defer cancelFun() defer cancelFun()
containerID, err := createContainer(ctx, dockerCli, containerCfg, &runOpts.createOptions) containerID, err := createContainer(ctx, dockerCli, containerCfg, &runOpts.createOptions)

View File

@ -1,6 +1,7 @@
package container package container
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -97,6 +98,7 @@ func TestRunContainerImagePullPolicyInvalid(t *testing.T) {
t.Run(tc.PullPolicy, func(t *testing.T) { t.Run(tc.PullPolicy, func(t *testing.T) {
dockerCli := test.NewFakeCli(&fakeClient{}) dockerCli := test.NewFakeCli(&fakeClient{})
err := runRun( err := runRun(
context.TODO(),
dockerCli, dockerCli,
&pflag.FlagSet{}, &pflag.FlagSet{},
&runOptions{createOptions: createOptions{pull: tc.PullPolicy}}, &runOptions{createOptions: createOptions{pull: tc.PullPolicy}},

View File

@ -45,7 +45,7 @@ func NewStartCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.Containers = args opts.Containers = args
return RunStart(dockerCli, &opts) return RunStart(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container start, docker start", "aliases": "docker container start, docker start",
@ -72,8 +72,8 @@ func NewStartCommand(dockerCli command.Cli) *cobra.Command {
// RunStart executes a `start` command // RunStart executes a `start` command
// //
//nolint:gocyclo //nolint:gocyclo
func RunStart(dockerCli command.Cli, opts *StartOptions) error { func RunStart(ctx context.Context, dockerCli command.Cli, opts *StartOptions) error {
ctx, cancelFun := context.WithCancel(context.Background()) ctx, cancelFun := context.WithCancel(ctx)
defer cancelFun() defer cancelFun()
switch { switch {

View File

@ -39,7 +39,7 @@ func NewStatsCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(0), Args: cli.RequiresMinArgs(0),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
return runStats(dockerCli, &opts) return runStats(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container stats, docker stats", "aliases": "docker container stats, docker stats",
@ -59,12 +59,10 @@ func NewStatsCommand(dockerCli command.Cli) *cobra.Command {
// This shows real-time information on CPU usage, memory usage, and network I/O. // This shows real-time information on CPU usage, memory usage, and network I/O.
// //
//nolint:gocyclo //nolint:gocyclo
func runStats(dockerCli command.Cli, opts *statsOptions) error { func runStats(ctx context.Context, dockerCli command.Cli, opts *statsOptions) error {
showAll := len(opts.containers) == 0 showAll := len(opts.containers) == 0
closeChan := make(chan error) closeChan := make(chan error)
ctx := context.Background()
// monitorContainerEvents watches for container creation and removal (only // monitorContainerEvents watches for container creation and removal (only
// used when calling `docker stats` without arguments). // used when calling `docker stats` without arguments).
monitorContainerEvents := func(started chan<- struct{}, c chan events.Message, stopped <-chan struct{}) { monitorContainerEvents := func(started chan<- struct{}, c chan events.Message, stopped <-chan struct{}) {
@ -96,8 +94,7 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error {
// Get the daemonOSType if not set already // Get the daemonOSType if not set already
if daemonOSType == "" { if daemonOSType == "" {
svctx := context.Background() sv, err := dockerCli.Client().ServerVersion(ctx)
sv, err := dockerCli.Client().ServerVersion(svctx)
if err != nil { if err != nil {
return err return err
} }

View File

@ -32,7 +32,7 @@ func NewStopCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
opts.timeoutChanged = cmd.Flags().Changed("time") opts.timeoutChanged = cmd.Flags().Changed("time")
return runStop(dockerCli, &opts) return runStop(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container stop, docker stop", "aliases": "docker container stop, docker stop",
@ -46,13 +46,13 @@ func NewStopCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runStop(dockerCli command.Cli, opts *stopOptions) error { func runStop(ctx context.Context, dockerCli command.Cli, opts *stopOptions) error {
var timeout *int var timeout *int
if opts.timeoutChanged { if opts.timeoutChanged {
timeout = &opts.timeout timeout = &opts.timeout
} }
errChan := parallelOperation(context.Background(), opts.containers, func(ctx context.Context, id string) error { errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error {
return dockerCli.Client().ContainerStop(ctx, id, container.StopOptions{ return dockerCli.Client().ContainerStop(ctx, id, container.StopOptions{
Signal: opts.signal, Signal: opts.signal,
Timeout: timeout, Timeout: timeout,

View File

@ -29,7 +29,7 @@ func NewTopCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.container = args[0] opts.container = args[0]
opts.args = args[1:] opts.args = args[1:]
return runTop(dockerCli, &opts) return runTop(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container top, docker top", "aliases": "docker container top, docker top",
@ -43,9 +43,7 @@ func NewTopCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runTop(dockerCli command.Cli, opts *topOptions) error { func runTop(ctx context.Context, dockerCli command.Cli, opts *topOptions) error {
ctx := context.Background()
procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args) procList, err := dockerCli.Client().ContainerTop(ctx, opts.container, opts.args)
if err != nil { if err != nil {
return err return err

View File

@ -27,7 +27,7 @@ func NewUnpauseCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
return runUnpause(dockerCli, &opts) return runUnpause(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container unpause, docker unpause", "aliases": "docker container unpause, docker unpause",
@ -39,9 +39,7 @@ func NewUnpauseCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runUnpause(dockerCli command.Cli, opts *unpauseOptions) error { func runUnpause(ctx context.Context, dockerCli command.Cli, opts *unpauseOptions) error {
ctx := context.Background()
var errs []string var errs []string
errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerUnpause) errChan := parallelOperation(ctx, opts.containers, dockerCli.Client().ContainerUnpause)
for _, container := range opts.containers { for _, container := range opts.containers {

View File

@ -47,7 +47,7 @@ func NewUpdateCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.containers = args options.containers = args
options.nFlag = cmd.Flags().NFlag() options.nFlag = cmd.Flags().NFlag()
return runUpdate(dockerCli, &options) return runUpdate(cmd.Context(), dockerCli, &options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container update, docker update", "aliases": "docker container update, docker update",
@ -86,7 +86,7 @@ func NewUpdateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runUpdate(dockerCli command.Cli, options *updateOptions) error { func runUpdate(ctx context.Context, dockerCli command.Cli, options *updateOptions) error {
var err error var err error
if options.nFlag == 0 { if options.nFlag == 0 {
@ -126,8 +126,6 @@ func runUpdate(dockerCli command.Cli, options *updateOptions) error {
RestartPolicy: restartPolicy, RestartPolicy: restartPolicy,
} }
ctx := context.Background()
var ( var (
warns []string warns []string
errs []string errs []string

View File

@ -26,7 +26,7 @@ func NewWaitCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args opts.containers = args
return runWait(dockerCli, &opts) return runWait(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker container wait, docker wait", "aliases": "docker container wait, docker wait",
@ -37,9 +37,7 @@ func NewWaitCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runWait(dockerCli command.Cli, opts *waitOptions) error { func runWait(ctx context.Context, dockerCli command.Cli, opts *waitOptions) error {
ctx := context.Background()
var errs []string var errs []string
for _, container := range opts.containers { for _, container := range opts.containers {
resultC, errC := dockerCli.Client().ContainerWait(ctx, container, "") resultC, errC := dockerCli.Client().ContainerWait(ctx, container, "")

View File

@ -101,7 +101,7 @@ func NewBuildCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.context = args[0] options.context = args[0]
return runBuild(dockerCli, options) return runBuild(cmd.Context(), dockerCli, options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "4", "category-top": "4",
@ -172,7 +172,7 @@ func (out *lastProgressOutput) WriteProgress(prog progress.Progress) error {
} }
//nolint:gocyclo //nolint:gocyclo
func runBuild(dockerCli command.Cli, options buildOptions) error { func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) error {
var ( var (
err error err error
buildCtx io.ReadCloser buildCtx io.ReadCloser
@ -272,7 +272,7 @@ func runBuild(dockerCli command.Cli, options buildOptions) error {
} }
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(ctx)
defer cancel() defer cancel()
var resolvedTags []*resolvedTag var resolvedTags []*resolvedTag

View File

@ -48,7 +48,7 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) {
options.dockerfileName = "-" options.dockerfileName = "-"
options.context = dir.Path() options.context = dir.Path()
options.untrusted = true options.untrusted = true
assert.NilError(t, runBuild(cli, options)) assert.NilError(t, runBuild(context.TODO(), cli, options))
expected := []string{fakeBuild.options.Dockerfile, ".dockerignore", "foo"} expected := []string{fakeBuild.options.Dockerfile, ".dockerignore", "foo"}
assert.DeepEqual(t, expected, fakeBuild.filenames(t)) assert.DeepEqual(t, expected, fakeBuild.filenames(t))
@ -75,7 +75,7 @@ func TestRunBuildResetsUidAndGidInContext(t *testing.T) {
options := newBuildOptions() options := newBuildOptions()
options.context = dir.Path() options.context = dir.Path()
options.untrusted = true options.untrusted = true
assert.NilError(t, runBuild(cli, options)) assert.NilError(t, runBuild(context.TODO(), cli, options))
headers := fakeBuild.headers(t) headers := fakeBuild.headers(t)
expected := []*tar.Header{ expected := []*tar.Header{
@ -110,7 +110,7 @@ COPY data /data
options.context = dir.Path() options.context = dir.Path()
options.dockerfileName = df.Path() options.dockerfileName = df.Path()
options.untrusted = true options.untrusted = true
assert.NilError(t, runBuild(cli, options)) assert.NilError(t, runBuild(context.TODO(), cli, options))
expected := []string{fakeBuild.options.Dockerfile, ".dockerignore", "data"} expected := []string{fakeBuild.options.Dockerfile, ".dockerignore", "data"}
assert.DeepEqual(t, expected, fakeBuild.filenames(t)) assert.DeepEqual(t, expected, fakeBuild.filenames(t))
@ -170,7 +170,7 @@ RUN echo hello world
options := newBuildOptions() options := newBuildOptions()
options.context = tmpDir.Join("context-link") options.context = tmpDir.Join("context-link")
options.untrusted = true options.untrusted = true
assert.NilError(t, runBuild(cli, options)) assert.NilError(t, runBuild(context.TODO(), cli, options))
assert.DeepEqual(t, fakeBuild.filenames(t), []string{"Dockerfile"}) assert.DeepEqual(t, fakeBuild.filenames(t), []string{"Dockerfile"})
} }

View File

@ -29,7 +29,7 @@ func NewHistoryCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.image = args[0] opts.image = args[0]
return runHistory(dockerCli, opts) return runHistory(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker image history, docker history", "aliases": "docker image history, docker history",
@ -46,9 +46,7 @@ func NewHistoryCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runHistory(dockerCli command.Cli, opts historyOptions) error { func runHistory(ctx context.Context, dockerCli command.Cli, opts historyOptions) error {
ctx := context.Background()
history, err := dockerCli.Client().ImageHistory(ctx, opts.image) history, err := dockerCli.Client().ImageHistory(ctx, opts.image)
if err != nil { if err != nil {
return err return err

View File

@ -34,7 +34,7 @@ func NewImportCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
options.reference = args[1] options.reference = args[1]
} }
return runImport(dockerCli, options) return runImport(cmd.Context(), dockerCli, options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker image import, docker import", "aliases": "docker image import, docker import",
@ -51,7 +51,7 @@ func NewImportCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runImport(dockerCli command.Cli, options importOptions) error { func runImport(ctx context.Context, dockerCli command.Cli, options importOptions) error {
var source types.ImageImportSource var source types.ImageImportSource
switch { switch {
case options.source == "-": case options.source == "-":
@ -78,7 +78,7 @@ func runImport(dockerCli command.Cli, options importOptions) error {
} }
} }
responseBody, err := dockerCli.Client().ImageImport(context.Background(), source, options.reference, types.ImageImportOptions{ responseBody, err := dockerCli.Client().ImageImport(ctx, source, options.reference, types.ImageImportOptions{
Message: options.message, Message: options.message,
Changes: options.changes.GetAll(), Changes: options.changes.GetAll(),
Platform: options.platform, Platform: options.platform,

View File

@ -25,7 +25,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.refs = args opts.refs = args
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
} }
@ -34,10 +34,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
getRefFunc := func(ref string) (any, []byte, error) { getRefFunc := func(ref string) (any, []byte, error) {
return client.ImageInspectWithRaw(ctx, ref) return client.ImageInspectWithRaw(ctx, ref)
} }

View File

@ -35,7 +35,7 @@ func NewImagesCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 0 { if len(args) > 0 {
options.matchName = args[0] options.matchName = args[0]
} }
return runImages(dockerCli, options) return runImages(cmd.Context(), dockerCli, options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "7", "category-top": "7",
@ -62,9 +62,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
return &cmd return &cmd
} }
func runImages(dockerCli command.Cli, options imagesOptions) error { func runImages(ctx context.Context, dockerCli command.Cli, options imagesOptions) error {
ctx := context.Background()
filters := options.filter.Value() filters := options.filter.Value()
if options.matchName != "" { if options.matchName != "" {
filters.Add("reference", options.matchName) filters.Add("reference", options.matchName)

View File

@ -27,7 +27,7 @@ func NewLoadCommand(dockerCli command.Cli) *cobra.Command {
Short: "Load an image from a tar archive or STDIN", Short: "Load an image from a tar archive or STDIN",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runLoad(dockerCli, opts) return runLoad(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker image load, docker load", "aliases": "docker image load, docker load",
@ -43,7 +43,7 @@ func NewLoadCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runLoad(dockerCli command.Cli, opts loadOptions) error { func runLoad(ctx context.Context, dockerCli command.Cli, opts loadOptions) error {
var input io.Reader = dockerCli.In() var input io.Reader = dockerCli.In()
if opts.input != "" { if opts.input != "" {
// We use sequential.Open to use sequential file access on Windows, avoiding // We use sequential.Open to use sequential file access on Windows, avoiding
@ -65,7 +65,7 @@ func runLoad(dockerCli command.Cli, opts loadOptions) error {
if !dockerCli.Out().IsTerminal() { if !dockerCli.Out().IsTerminal() {
opts.quiet = true opts.quiet = true
} }
response, err := dockerCli.Client().ImageLoad(context.Background(), input, opts.quiet) response, err := dockerCli.Client().ImageLoad(ctx, input, opts.quiet)
if err != nil { if err != nil {
return err return err
} }

View File

@ -29,7 +29,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove unused images", Short: "Remove unused images",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
spaceReclaimed, output, err := runPrune(dockerCli, options) spaceReclaimed, output, err := runPrune(cmd.Context(), dockerCli, options)
if err != nil { if err != nil {
return err return err
} }
@ -58,7 +58,7 @@ Are you sure you want to continue?`
Are you sure you want to continue?` Are you sure you want to continue?`
) )
func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) { func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint64, output string, err error) {
pruneFilters := options.filter.Value().Clone() pruneFilters := options.filter.Value().Clone()
pruneFilters.Add("dangling", strconv.FormatBool(!options.all)) pruneFilters.Add("dangling", strconv.FormatBool(!options.all))
pruneFilters = command.PruneFilters(dockerCli, pruneFilters) pruneFilters = command.PruneFilters(dockerCli, pruneFilters)
@ -71,7 +71,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6
return 0, "", nil return 0, "", nil
} }
report, err := dockerCli.Client().ImagesPrune(context.Background(), pruneFilters) report, err := dockerCli.Client().ImagesPrune(ctx, pruneFilters)
if err != nil { if err != nil {
return 0, "", err return 0, "", err
} }
@ -99,6 +99,6 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (spaceReclaimed uint6
// RunPrune calls the Image Prune API // RunPrune calls the Image Prune API
// This returns the amount of space reclaimed and a detailed output string // This returns the amount of space reclaimed and a detailed output string
func RunPrune(dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) { func RunPrune(ctx context.Context, dockerCli command.Cli, all bool, filter opts.FilterOpt) (uint64, string, error) {
return runPrune(dockerCli, pruneOptions{force: true, all: all, filter: filter}) return runPrune(ctx, dockerCli, pruneOptions{force: true, all: all, filter: filter})
} }

View File

@ -33,7 +33,7 @@ func NewPullCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.remote = args[0] opts.remote = args[0]
return RunPull(dockerCli, opts) return RunPull(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "5", "category-top": "5",
@ -54,7 +54,7 @@ func NewPullCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunPull performs a pull against the engine based on the specified options // RunPull performs a pull against the engine based on the specified options
func RunPull(dockerCLI command.Cli, opts PullOptions) error { func RunPull(ctx context.Context, dockerCLI command.Cli, opts PullOptions) error {
distributionRef, err := reference.ParseNormalizedNamed(opts.remote) distributionRef, err := reference.ParseNormalizedNamed(opts.remote)
switch { switch {
case err != nil: case err != nil:
@ -68,7 +68,6 @@ func RunPull(dockerCLI command.Cli, opts PullOptions) error {
} }
} }
ctx := context.Background()
imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, AuthResolver(dockerCLI), distributionRef.String()) imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, AuthResolver(dockerCLI), distributionRef.String())
if err != nil { if err != nil {
return err return err

View File

@ -35,7 +35,7 @@ func NewPushCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.remote = args[0] opts.remote = args[0]
return RunPush(dockerCli, opts) return RunPush(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "6", "category-top": "6",
@ -53,7 +53,7 @@ func NewPushCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunPush performs a push against the engine based on the specified options // RunPush performs a push against the engine based on the specified options
func RunPush(dockerCli command.Cli, opts pushOptions) error { func RunPush(ctx context.Context, dockerCli command.Cli, opts pushOptions) error {
ref, err := reference.ParseNormalizedNamed(opts.remote) ref, err := reference.ParseNormalizedNamed(opts.remote)
switch { switch {
case err != nil: case err != nil:
@ -73,8 +73,6 @@ func RunPush(dockerCli command.Cli, opts pushOptions) error {
return err return err
} }
ctx := context.Background()
// Resolve the Auth config relevant for this server // Resolve the Auth config relevant for this server
authConfig := command.ResolveAuthConfig(dockerCli.ConfigFile(), repoInfo.Index) authConfig := command.ResolveAuthConfig(dockerCli.ConfigFile(), repoInfo.Index)
encodedAuth, err := registrytypes.EncodeAuthConfig(authConfig) encodedAuth, err := registrytypes.EncodeAuthConfig(authConfig)

View File

@ -27,7 +27,7 @@ func NewRemoveCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove one or more images", Short: "Remove one or more images",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRemove(dockerCli, opts, args) return runRemove(cmd.Context(), dockerCli, opts, args)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker image rm, docker image remove, docker rmi", "aliases": "docker image rm, docker image remove, docker rmi",
@ -49,9 +49,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
return &cmd return &cmd
} }
func runRemove(dockerCli command.Cli, opts removeOptions, images []string) error { func runRemove(ctx context.Context, dockerCli command.Cli, opts removeOptions, images []string) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
options := types.ImageRemoveOptions{ options := types.ImageRemoveOptions{
Force: opts.force, Force: opts.force,

View File

@ -26,7 +26,7 @@ func NewSaveCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.images = args opts.images = args
return RunSave(dockerCli, opts) return RunSave(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker image save, docker save", "aliases": "docker image save, docker save",
@ -42,7 +42,7 @@ func NewSaveCommand(dockerCli command.Cli) *cobra.Command {
} }
// RunSave performs a save against the engine based on the specified options // RunSave performs a save against the engine based on the specified options
func RunSave(dockerCli command.Cli, opts saveOptions) error { func RunSave(ctx context.Context, dockerCli command.Cli, opts saveOptions) error {
if opts.output == "" && dockerCli.Out().IsTerminal() { if opts.output == "" && dockerCli.Out().IsTerminal() {
return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect")
} }
@ -51,7 +51,7 @@ func RunSave(dockerCli command.Cli, opts saveOptions) error {
return errors.Wrap(err, "failed to save image") return errors.Wrap(err, "failed to save image")
} }
responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images) responseBody, err := dockerCli.Client().ImageSave(ctx, opts.images)
if err != nil { if err != nil {
return err return err
} }

View File

@ -25,7 +25,7 @@ func NewTagCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.image = args[0] opts.image = args[0]
opts.name = args[1] opts.name = args[1]
return runTag(dockerCli, opts) return runTag(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"aliases": "docker image tag, docker tag", "aliases": "docker image tag, docker tag",
@ -39,8 +39,6 @@ func NewTagCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runTag(dockerCli command.Cli, opts tagOptions) error { func runTag(ctx context.Context, dockerCli command.Cli, opts tagOptions) error {
ctx := context.Background()
return dockerCli.Client().ImageTag(ctx, opts.image, opts.name) return dockerCli.Client().ImageTag(ctx, opts.image, opts.name)
} }

View File

@ -25,7 +25,7 @@ func newCreateListCommand(dockerCli command.Cli) *cobra.Command {
Short: "Create a local manifest list for annotating and pushing to a registry", Short: "Create a local manifest list for annotating and pushing to a registry",
Args: cli.RequiresMinArgs(2), Args: cli.RequiresMinArgs(2),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return createManifestList(dockerCli, args, opts) return createManifestList(cmd.Context(), dockerCli, args, opts)
}, },
} }
@ -35,7 +35,7 @@ func newCreateListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func createManifestList(dockerCli command.Cli, args []string, opts createOpts) error { func createManifestList(ctx context.Context, dockerCli command.Cli, args []string, opts createOpts) error {
newRef := args[0] newRef := args[0]
targetRef, err := normalizeReference(newRef) targetRef, err := normalizeReference(newRef)
if err != nil { if err != nil {
@ -58,7 +58,6 @@ func createManifestList(dockerCli command.Cli, args []string, opts createOpts) e
return errors.Errorf("refusing to amend an existing manifest list with no --amend flag") return errors.Errorf("refusing to amend an existing manifest list with no --amend flag")
} }
ctx := context.Background()
// Now create the local manifest list transaction by looking up the manifest schemas // Now create the local manifest list transaction by looking up the manifest schemas
// for the constituent images: // for the constituent images:
manifests := args[1:] manifests := args[1:]

View File

@ -39,7 +39,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
opts.list = args[0] opts.list = args[0]
opts.ref = args[1] opts.ref = args[1]
} }
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
} }
@ -49,7 +49,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
namedRef, err := normalizeReference(opts.ref) namedRef, err := normalizeReference(opts.ref)
if err != nil { if err != nil {
return err return err
@ -76,7 +76,6 @@ func runInspect(dockerCli command.Cli, opts inspectOptions) error {
} }
// Next try a remote manifest // Next try a remote manifest
ctx := context.Background()
registryClient := dockerCli.RegistryClient(opts.insecure) registryClient := dockerCli.RegistryClient(opts.insecure)
imageManifest, err := registryClient.GetManifest(ctx, namedRef) imageManifest, err := registryClient.GetManifest(ctx, namedRef)
if err == nil { if err == nil {

View File

@ -53,7 +53,7 @@ func newPushListCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.target = args[0] opts.target = args[0]
return runPush(dockerCli, opts) return runPush(cmd.Context(), dockerCli, opts)
}, },
} }
@ -63,7 +63,7 @@ func newPushListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runPush(dockerCli command.Cli, opts pushOpts) error { func runPush(ctx context.Context, dockerCli command.Cli, opts pushOpts) error {
targetRef, err := normalizeReference(opts.target) targetRef, err := normalizeReference(opts.target)
if err != nil { if err != nil {
return err return err
@ -82,7 +82,6 @@ func runPush(dockerCli command.Cli, opts pushOpts) error {
return err return err
} }
ctx := context.Background()
if err := pushList(ctx, dockerCli, req); err != nil { if err := pushList(ctx, dockerCli, req); err != nil {
return err return err
} }

View File

@ -1,6 +1,7 @@
package manifest package manifest
import ( import (
"context"
"strings" "strings"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
@ -15,14 +16,14 @@ func newRmManifestListCommand(dockerCli command.Cli) *cobra.Command {
Short: "Delete one or more manifest lists from local storage", Short: "Delete one or more manifest lists from local storage",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRm(dockerCli, args) return runRm(cmd.Context(), dockerCli, args)
}, },
} }
return cmd return cmd
} }
func runRm(dockerCli command.Cli, targets []string) error { func runRm(_ context.Context, dockerCli command.Cli, targets []string) error {
var errs []string var errs []string
for _, target := range targets { for _, target := range targets {
targetRef, refErr := normalizeReference(target) targetRef, refErr := normalizeReference(target)

View File

@ -36,7 +36,7 @@ func newConnectCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.network = args[0] options.network = args[0]
options.container = args[1] options.container = args[1]
return runConnect(dockerCli, options) return runConnect(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 { if len(args) == 0 {
@ -57,7 +57,7 @@ func newConnectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runConnect(dockerCli command.Cli, options connectOptions) error { func runConnect(ctx context.Context, dockerCli command.Cli, options connectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
driverOpts, err := convertDriverOpt(options.driverOpts) driverOpts, err := convertDriverOpt(options.driverOpts)
@ -75,7 +75,7 @@ func runConnect(dockerCli command.Cli, options connectOptions) error {
DriverOpts: driverOpts, DriverOpts: driverOpts,
} }
return client.NetworkConnect(context.Background(), options.network, options.container, epConfig) return client.NetworkConnect(ctx, options.network, options.container, epConfig)
} }
func convertDriverOpt(options []string) (map[string]string, error) { func convertDriverOpt(options []string) (map[string]string, error) {

View File

@ -51,7 +51,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.name = args[0] options.name = args[0]
return runCreate(dockerCli, options) return runCreate(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -84,7 +84,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runCreate(dockerCli command.Cli, options createOptions) error { func runCreate(ctx context.Context, dockerCli command.Cli, options createOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ipamCfg, err := consolidateIpam(options.ipamSubnet, options.ipamIPRange, options.ipamGateway, options.ipamAux.GetAll()) ipamCfg, err := consolidateIpam(options.ipamSubnet, options.ipamIPRange, options.ipamGateway, options.ipamAux.GetAll())
@ -98,7 +98,7 @@ func runCreate(dockerCli command.Cli, options createOptions) error {
Network: options.configFrom, Network: options.configFrom,
} }
} }
resp, err := client.NetworkCreate(context.Background(), options.name, types.NetworkCreate{ resp, err := client.NetworkCreate(ctx, options.name, types.NetworkCreate{
Driver: options.driver, Driver: options.driver,
Options: options.driverOpts.GetAll(), Options: options.driverOpts.GetAll(),
IPAM: &network.IPAM{ IPAM: &network.IPAM{

View File

@ -26,7 +26,7 @@ func newDisconnectCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.network = args[0] opts.network = args[0]
opts.container = args[1] opts.container = args[1]
return runDisconnect(dockerCli, opts) return runDisconnect(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 { if len(args) == 0 {
@ -43,10 +43,10 @@ func newDisconnectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runDisconnect(dockerCli command.Cli, opts disconnectOptions) error { func runDisconnect(ctx context.Context, dockerCli command.Cli, opts disconnectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
return client.NetworkDisconnect(context.Background(), opts.network, opts.container, opts.force) return client.NetworkDisconnect(ctx, opts.network, opts.container, opts.force)
} }
func isConnected(network string) func(types.Container) bool { func isConnected(network string) func(types.Container) bool {

View File

@ -27,7 +27,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.names = args opts.names = args
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: completion.NetworkNames(dockerCli), ValidArgsFunction: completion.NetworkNames(dockerCli),
} }
@ -38,11 +38,9 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
getNetFunc := func(name string) (any, []byte, error) { getNetFunc := func(name string) (any, []byte, error) {
return client.NetworkInspectWithRaw(ctx, name, types.NetworkInspectOptions{Verbose: opts.verbose}) return client.NetworkInspectWithRaw(ctx, name, types.NetworkInspectOptions{Verbose: opts.verbose})
} }

View File

@ -31,7 +31,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List networks", Short: "List networks",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCli, options) return runList(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -45,10 +45,10 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runList(dockerCli command.Cli, options listOptions) error { func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
listOptions := types.NetworkListOptions{Filters: options.filter.Value()} listOptions := types.NetworkListOptions{Filters: options.filter.Value()}
networkResources, err := client.NetworkList(context.Background(), listOptions) networkResources, err := client.NetworkList(ctx, listOptions)
if err != nil { if err != nil {
return err return err
} }

View File

@ -24,7 +24,7 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove all unused networks", Short: "Remove all unused networks",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
output, err := runPrune(dockerCli, options) output, err := runPrune(cmd.Context(), dockerCli, options)
if err != nil { if err != nil {
return err return err
} }
@ -46,14 +46,14 @@ func NewPruneCommand(dockerCli command.Cli) *cobra.Command {
const warning = `WARNING! This will remove all custom networks not used by at least one container. const warning = `WARNING! This will remove all custom networks not used by at least one container.
Are you sure you want to continue?` Are you sure you want to continue?`
func runPrune(dockerCli command.Cli, options pruneOptions) (output string, err error) { func runPrune(ctx context.Context, dockerCli command.Cli, options pruneOptions) (output string, err error) {
pruneFilters := command.PruneFilters(dockerCli, options.filter.Value()) pruneFilters := command.PruneFilters(dockerCli, options.filter.Value())
if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) { if !options.force && !command.PromptForConfirmation(dockerCli.In(), dockerCli.Out(), warning) {
return "", nil return "", nil
} }
report, err := dockerCli.Client().NetworksPrune(context.Background(), pruneFilters) report, err := dockerCli.Client().NetworksPrune(ctx, pruneFilters)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -70,7 +70,7 @@ func runPrune(dockerCli command.Cli, options pruneOptions) (output string, err e
// RunPrune calls the Network Prune API // RunPrune calls the Network Prune API
// This returns the amount of space reclaimed and a detailed output string // This returns the amount of space reclaimed and a detailed output string
func RunPrune(dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) { func RunPrune(ctx context.Context, dockerCli command.Cli, _ bool, filter opts.FilterOpt) (uint64, string, error) {
output, err := runPrune(dockerCli, pruneOptions{force: true, filter: filter}) output, err := runPrune(ctx, dockerCli, pruneOptions{force: true, filter: filter})
return 0, output, err return 0, output, err
} }

View File

@ -25,7 +25,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove one or more networks", Short: "Remove one or more networks",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRemove(dockerCli, args, &opts) return runRemove(cmd.Context(), dockerCli, args, &opts)
}, },
ValidArgsFunction: completion.NetworkNames(dockerCli), ValidArgsFunction: completion.NetworkNames(dockerCli),
} }
@ -40,9 +40,9 @@ const ingressWarning = "WARNING! Before removing the routing-mesh network, " +
"Otherwise, removal may not be effective and functionality of newly create " + "Otherwise, removal may not be effective and functionality of newly create " +
"ingress networks will be impaired.\nAre you sure you want to continue?" "ingress networks will be impaired.\nAre you sure you want to continue?"
func runRemove(dockerCli command.Cli, networks []string, opts *removeOptions) error { func runRemove(ctx context.Context, dockerCli command.Cli, networks []string, opts *removeOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
status := 0 status := 0
for _, name := range networks { for _, name := range networks {

View File

@ -1,6 +1,7 @@
package node package node
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
@ -15,12 +16,12 @@ func newDemoteCommand(dockerCli command.Cli) *cobra.Command {
Short: "Demote one or more nodes from manager in the swarm", Short: "Demote one or more nodes from manager in the swarm",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runDemote(dockerCli, args) return runDemote(cmd.Context(), dockerCli, args)
}, },
} }
} }
func runDemote(dockerCli command.Cli, nodes []string) error { func runDemote(ctx context.Context, dockerCli command.Cli, nodes []string) error {
demote := func(node *swarm.Node) error { demote := func(node *swarm.Node) error {
if node.Spec.Role == swarm.NodeRoleWorker { if node.Spec.Role == swarm.NodeRoleWorker {
fmt.Fprintf(dockerCli.Out(), "Node %s is already a worker.\n", node.ID) fmt.Fprintf(dockerCli.Out(), "Node %s is already a worker.\n", node.ID)
@ -32,5 +33,5 @@ func runDemote(dockerCli command.Cli, nodes []string) error {
success := func(nodeID string) { success := func(nodeID string) {
fmt.Fprintf(dockerCli.Out(), "Manager %s demoted in the swarm.\n", nodeID) fmt.Fprintf(dockerCli.Out(), "Manager %s demoted in the swarm.\n", nodeID)
} }
return updateNodes(dockerCli, nodes, demote, success) return updateNodes(ctx, dockerCli, nodes, demote, success)
} }

View File

@ -27,7 +27,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.nodeIds = args opts.nodeIds = args
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
} }
@ -37,9 +37,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
if opts.pretty { if opts.pretty {
opts.format = "pretty" opts.format = "pretty"

View File

@ -31,7 +31,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List nodes in the swarm", Short: "List nodes in the swarm",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCli, options) return runList(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -43,9 +43,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runList(dockerCli command.Cli, options listOptions) error { func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
nodes, err := client.NodeList( nodes, err := client.NodeList(
ctx, ctx,

View File

@ -1,6 +1,7 @@
package node package node
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
@ -15,12 +16,12 @@ func newPromoteCommand(dockerCli command.Cli) *cobra.Command {
Short: "Promote one or more nodes to manager in the swarm", Short: "Promote one or more nodes to manager in the swarm",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runPromote(dockerCli, args) return runPromote(cmd.Context(), dockerCli, args)
}, },
} }
} }
func runPromote(dockerCli command.Cli, nodes []string) error { func runPromote(ctx context.Context, dockerCli command.Cli, nodes []string) error {
promote := func(node *swarm.Node) error { promote := func(node *swarm.Node) error {
if node.Spec.Role == swarm.NodeRoleManager { if node.Spec.Role == swarm.NodeRoleManager {
fmt.Fprintf(dockerCli.Out(), "Node %s is already a manager.\n", node.ID) fmt.Fprintf(dockerCli.Out(), "Node %s is already a manager.\n", node.ID)
@ -32,5 +33,5 @@ func runPromote(dockerCli command.Cli, nodes []string) error {
success := func(nodeID string) { success := func(nodeID string) {
fmt.Fprintf(dockerCli.Out(), "Node %s promoted to a manager in the swarm.\n", nodeID) fmt.Fprintf(dockerCli.Out(), "Node %s promoted to a manager in the swarm.\n", nodeID)
} }
return updateNodes(dockerCli, nodes, promote, success) return updateNodes(ctx, dockerCli, nodes, promote, success)
} }

View File

@ -39,7 +39,7 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command {
options.nodeIDs = args options.nodeIDs = args
} }
return runPs(dockerCli, options) return runPs(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -53,9 +53,8 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runPs(dockerCli command.Cli, options psOptions) error { func runPs(ctx context.Context, dockerCli command.Cli, options psOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
var ( var (
errs []string errs []string

View File

@ -25,7 +25,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove one or more nodes from the swarm", Short: "Remove one or more nodes from the swarm",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRemove(dockerCli, args, opts) return runRemove(cmd.Context(), dockerCli, args, opts)
}, },
} }
flags := cmd.Flags() flags := cmd.Flags()
@ -33,9 +33,8 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRemove(dockerCli command.Cli, args []string, opts removeOptions) error { func runRemove(ctx context.Context, dockerCli command.Cli, args []string, opts removeOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
var errs []string var errs []string

View File

@ -23,7 +23,7 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command {
Short: "Update a node", Short: "Update a node",
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runUpdate(dockerCli, cmd.Flags(), args[0]) return runUpdate(cmd.Context(), dockerCli, cmd.Flags(), args[0])
}, },
} }
@ -36,16 +36,15 @@ func newUpdateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, nodeID string) error { func runUpdate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, nodeID string) error {
success := func(_ string) { success := func(_ string) {
fmt.Fprintln(dockerCli.Out(), nodeID) fmt.Fprintln(dockerCli.Out(), nodeID)
} }
return updateNodes(dockerCli, []string{nodeID}, mergeNodeUpdate(flags), success) return updateNodes(ctx, dockerCli, []string{nodeID}, mergeNodeUpdate(flags), success)
} }
func updateNodes(dockerCli command.Cli, nodes []string, mergeNode func(node *swarm.Node) error, success func(nodeID string)) error { func updateNodes(ctx context.Context, dockerCli command.Cli, nodes []string, mergeNode func(node *swarm.Node) error, success func(nodeID string)) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
for _, nodeID := range nodes { for _, nodeID := range nodes {
node, _, err := client.NodeInspectWithRaw(ctx, nodeID) node, _, err := client.NodeInspectWithRaw(ctx, nodeID)

View File

@ -74,7 +74,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.repoName = args[0] options.repoName = args[0]
options.context = args[1] options.context = args[1]
return runCreate(dockerCli, options) return runCreate(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -86,7 +86,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runCreate(dockerCli command.Cli, options pluginCreateOptions) error { func runCreate(ctx context.Context, dockerCli command.Cli, options pluginCreateOptions) error {
var ( var (
createCtx io.ReadCloser createCtx io.ReadCloser
err error err error
@ -119,8 +119,6 @@ func runCreate(dockerCli command.Cli, options pluginCreateOptions) error {
return err return err
} }
ctx := context.Background()
createOptions := types.PluginCreateOptions{RepoName: options.repoName} createOptions := types.PluginCreateOptions{RepoName: options.repoName}
if err = dockerCli.Client().PluginCreate(ctx, createCtx, createOptions); err != nil { if err = dockerCli.Client().PluginCreate(ctx, createCtx, createOptions); err != nil {
return err return err

View File

@ -18,7 +18,7 @@ func newDisableCommand(dockerCli command.Cli) *cobra.Command {
Short: "Disable a plugin", Short: "Disable a plugin",
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runDisable(dockerCli, args[0], force) return runDisable(cmd.Context(), dockerCli, args[0], force)
}, },
} }
@ -27,8 +27,8 @@ func newDisableCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runDisable(dockerCli command.Cli, name string, force bool) error { func runDisable(ctx context.Context, dockerCli command.Cli, name string, force bool) error {
if err := dockerCli.Client().PluginDisable(context.Background(), name, types.PluginDisableOptions{Force: force}); err != nil { if err := dockerCli.Client().PluginDisable(ctx, name, types.PluginDisableOptions{Force: force}); err != nil {
return err return err
} }
fmt.Fprintln(dockerCli.Out(), name) fmt.Fprintln(dockerCli.Out(), name)

View File

@ -25,7 +25,7 @@ func newEnableCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.name = args[0] opts.name = args[0]
return runEnable(dockerCli, &opts) return runEnable(cmd.Context(), dockerCli, &opts)
}, },
} }
@ -34,13 +34,13 @@ func newEnableCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runEnable(dockerCli command.Cli, opts *enableOpts) error { func runEnable(ctx context.Context, dockerCli command.Cli, opts *enableOpts) error {
name := opts.name name := opts.name
if opts.timeout < 0 { if opts.timeout < 0 {
return errors.Errorf("negative timeout %d is invalid", opts.timeout) return errors.Errorf("negative timeout %d is invalid", opts.timeout)
} }
if err := dockerCli.Client().PluginEnable(context.Background(), name, types.PluginEnableOptions{Timeout: opts.timeout}); err != nil { if err := dockerCli.Client().PluginEnable(ctx, name, types.PluginEnableOptions{Timeout: opts.timeout}); err != nil {
return err return err
} }
fmt.Fprintln(dockerCli.Out(), name) fmt.Fprintln(dockerCli.Out(), name)

View File

@ -24,7 +24,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.pluginNames = args opts.pluginNames = args
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
} }
@ -33,9 +33,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
getRef := func(ref string) (any, []byte, error) { getRef := func(ref string) (any, []byte, error) {
return client.PluginInspectWithRaw(ctx, ref) return client.PluginInspectWithRaw(ctx, ref)
} }

View File

@ -44,7 +44,7 @@ func newInstallCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
options.args = args[1:] options.args = args[1:]
} }
return runInstall(dockerCli, options) return runInstall(cmd.Context(), dockerCli, options)
}, },
} }
@ -104,7 +104,7 @@ func buildPullConfig(ctx context.Context, dockerCli command.Cli, opts pluginOpti
return options, nil return options, nil
} }
func runInstall(dockerCli command.Cli, opts pluginOptions) error { func runInstall(ctx context.Context, dockerCli command.Cli, opts pluginOptions) error {
var localName string var localName string
if opts.localName != "" { if opts.localName != "" {
aref, err := reference.ParseNormalizedNamed(opts.localName) aref, err := reference.ParseNormalizedNamed(opts.localName)
@ -117,7 +117,6 @@ func runInstall(dockerCli command.Cli, opts pluginOptions) error {
localName = reference.FamiliarString(reference.TagNameOnly(aref)) localName = reference.FamiliarString(reference.TagNameOnly(aref))
} }
ctx := context.Background()
options, err := buildPullConfig(ctx, dockerCli, opts, "plugin install") options, err := buildPullConfig(ctx, dockerCli, opts, "plugin install")
if err != nil { if err != nil {
return err return err

View File

@ -30,7 +30,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
Aliases: []string{"list"}, Aliases: []string{"list"},
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCli, options) return runList(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -45,8 +45,8 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runList(dockerCli command.Cli, options listOptions) error { func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error {
plugins, err := dockerCli.Client().PluginList(context.Background(), options.filter.Value()) plugins, err := dockerCli.Client().PluginList(ctx, options.filter.Value())
if err != nil { if err != nil {
return err return err
} }

View File

@ -27,7 +27,7 @@ func newPushCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.name = args[0] opts.name = args[0]
return runPush(dockerCli, opts) return runPush(cmd.Context(), dockerCli, opts)
}, },
} }
@ -38,7 +38,7 @@ func newPushCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runPush(dockerCli command.Cli, opts pushOptions) error { func runPush(ctx context.Context, dockerCli command.Cli, opts pushOptions) error {
named, err := reference.ParseNormalizedNamed(opts.name) named, err := reference.ParseNormalizedNamed(opts.name)
if err != nil { if err != nil {
return err return err
@ -49,8 +49,6 @@ func runPush(dockerCli command.Cli, opts pushOptions) error {
named = reference.TagNameOnly(named) named = reference.TagNameOnly(named)
ctx := context.Background()
repoInfo, err := registry.ParseRepositoryInfo(named) repoInfo, err := registry.ParseRepositoryInfo(named)
if err != nil { if err != nil {
return err return err

View File

@ -26,7 +26,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.plugins = args opts.plugins = args
return runRemove(dockerCli, &opts) return runRemove(cmd.Context(), dockerCli, &opts)
}, },
} }
@ -35,9 +35,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRemove(dockerCli command.Cli, opts *rmOptions) error { func runRemove(ctx context.Context, dockerCli command.Cli, opts *rmOptions) error {
ctx := context.Background()
var errs cli.Errors var errs cli.Errors
for _, name := range opts.plugins { for _, name := range opts.plugins {
if err := dockerCli.Client().PluginRemove(ctx, name, types.PluginRemoveOptions{Force: opts.force}); err != nil { if err := dockerCli.Client().PluginRemove(ctx, name, types.PluginRemoveOptions{Force: opts.force}); err != nil {

View File

@ -1,8 +1,6 @@
package plugin package plugin
import ( import (
"context"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -14,7 +12,7 @@ func newSetCommand(dockerCli command.Cli) *cobra.Command {
Short: "Change settings for a plugin", Short: "Change settings for a plugin",
Args: cli.RequiresMinArgs(2), Args: cli.RequiresMinArgs(2),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return dockerCli.Client().PluginSet(context.Background(), args[0], args[1:]) return dockerCli.Client().PluginSet(cmd.Context(), args[0], args[1:])
}, },
} }

View File

@ -24,7 +24,7 @@ func newUpgradeCommand(dockerCli command.Cli) *cobra.Command {
if len(args) == 2 { if len(args) == 2 {
options.remote = args[1] options.remote = args[1]
} }
return runUpgrade(dockerCli, options) return runUpgrade(cmd.Context(), dockerCli, options)
}, },
Annotations: map[string]string{"version": "1.26"}, Annotations: map[string]string{"version": "1.26"},
} }
@ -35,8 +35,7 @@ func newUpgradeCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runUpgrade(dockerCli command.Cli, opts pluginOptions) error { func runUpgrade(ctx context.Context, dockerCli command.Cli, opts pluginOptions) error {
ctx := context.Background()
p, _, err := dockerCli.Client().PluginInspectWithRaw(ctx, opts.localName) p, _, err := dockerCli.Client().PluginInspectWithRaw(ctx, opts.localName)
if err != nil { if err != nil {
return errors.Errorf("error reading plugin data: %v", err) return errors.Errorf("error reading plugin data: %v", err)

View File

@ -43,7 +43,7 @@ func NewLoginCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 0 { if len(args) > 0 {
opts.serverAddress = args[0] opts.serverAddress = args[0]
} }
return runLogin(dockerCli, opts) return runLogin(cmd.Context(), dockerCli, opts)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "8", "category-top": "8",
@ -100,8 +100,7 @@ func verifyloginOptions(dockerCli command.Cli, opts *loginOptions) error {
return nil return nil
} }
func runLogin(dockerCli command.Cli, opts loginOptions) error { //nolint:gocyclo func runLogin(ctx context.Context, dockerCli command.Cli, opts loginOptions) error { //nolint:gocyclo
ctx := context.Background()
clnt := dockerCli.Client() clnt := dockerCli.Client()
if err := verifyloginOptions(dockerCli, &opts); err != nil { if err := verifyloginOptions(dockerCli, &opts); err != nil {
return err return err

View File

@ -171,7 +171,7 @@ func TestRunLogin(t *testing.T) {
cred := *tc.inputStoredCred cred := *tc.inputStoredCred
assert.NilError(t, configfile.GetCredentialsStore(cred.ServerAddress).Store(cred)) assert.NilError(t, configfile.GetCredentialsStore(cred.ServerAddress).Store(cred))
} }
loginErr := runLogin(cli, tc.inputLoginOption) loginErr := runLogin(context.Background(), cli, tc.inputLoginOption)
if tc.expectedErr != "" { if tc.expectedErr != "" {
assert.Error(t, loginErr, tc.expectedErr) assert.Error(t, loginErr, tc.expectedErr)
return return

View File

@ -1,6 +1,7 @@
package registry package registry
import ( import (
"context"
"fmt" "fmt"
"github.com/docker/cli/cli" "github.com/docker/cli/cli"
@ -21,7 +22,7 @@ func NewLogoutCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 0 { if len(args) > 0 {
serverAddress = args[0] serverAddress = args[0]
} }
return runLogout(dockerCli, serverAddress) return runLogout(cmd.Context(), dockerCli, serverAddress)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "9", "category-top": "9",
@ -32,7 +33,7 @@ func NewLogoutCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runLogout(dockerCli command.Cli, serverAddress string) error { func runLogout(_ context.Context, dockerCli command.Cli, serverAddress string) error {
var isDefaultRegistry bool var isDefaultRegistry bool
if serverAddress == "" { if serverAddress == "" {

View File

@ -32,7 +32,7 @@ func NewSearchCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.term = args[0] options.term = args[0]
return runSearch(dockerCli, options) return runSearch(cmd.Context(), dockerCli, options)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
"category-top": "10", "category-top": "10",
@ -49,7 +49,7 @@ func NewSearchCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runSearch(dockerCli command.Cli, options searchOptions) error { func runSearch(ctx context.Context, dockerCli command.Cli, options searchOptions) error {
if options.filter.Value().Contains("is-automated") { if options.filter.Value().Contains("is-automated") {
_, _ = fmt.Fprintln(dockerCli.Err(), `WARNING: the "is-automated" filter is deprecated, and searching for "is-automated=true" will not yield any results in future.`) _, _ = fmt.Fprintln(dockerCli.Err(), `WARNING: the "is-automated" filter is deprecated, and searching for "is-automated=true" will not yield any results in future.`)
} }
@ -64,7 +64,6 @@ func runSearch(dockerCli command.Cli, options searchOptions) error {
return err return err
} }
ctx := context.Background()
requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, indexInfo, "search") requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, indexInfo, "search")
results, err := dockerCli.Client().ImageSearch(ctx, options.term, types.ImageSearchOptions{ results, err := dockerCli.Client().ImageSearch(ctx, options.term, types.ImageSearchOptions{
RegistryAuth: encodedAuth, RegistryAuth: encodedAuth,

View File

@ -36,7 +36,7 @@ func newSecretCreateCommand(dockerCli command.Cli) *cobra.Command {
if len(args) == 2 { if len(args) == 2 {
options.file = args[1] options.file = args[1]
} }
return runSecretCreate(dockerCli, options) return runSecretCreate(cmd.Context(), dockerCli, options)
}, },
} }
flags := cmd.Flags() flags := cmd.Flags()
@ -49,9 +49,8 @@ func newSecretCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runSecretCreate(dockerCli command.Cli, options createOptions) error { func runSecretCreate(ctx context.Context, dockerCli command.Cli, options createOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
if options.driver != "" && options.file != "" { if options.driver != "" && options.file != "" {
return errors.Errorf("When using secret driver secret data must be empty") return errors.Errorf("When using secret driver secret data must be empty")

View File

@ -26,7 +26,7 @@ func newSecretInspectCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.names = args opts.names = args
return runSecretInspect(dockerCli, opts) return runSecretInspect(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete) return completeNames(dockerCli)(cmd, args, toComplete)
@ -38,9 +38,8 @@ func newSecretInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runSecretInspect(dockerCli command.Cli, opts inspectOptions) error { func runSecretInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
if opts.pretty { if opts.pretty {
opts.format = "pretty" opts.format = "pretty"

View File

@ -29,7 +29,7 @@ func newSecretListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List secrets", Short: "List secrets",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runSecretList(dockerCli, options) return runSecretList(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete) return completeNames(dockerCli)(cmd, args, toComplete)
@ -44,9 +44,8 @@ func newSecretListCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runSecretList(dockerCli command.Cli, options listOptions) error { func runSecretList(ctx context.Context, dockerCli command.Cli, options listOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
secrets, err := client.SecretList(ctx, types.SecretListOptions{Filters: options.filter.Value()}) secrets, err := client.SecretList(ctx, types.SecretListOptions{Filters: options.filter.Value()})
if err != nil { if err != nil {

View File

@ -25,7 +25,7 @@ func newSecretRemoveCommand(dockerCli command.Cli) *cobra.Command {
opts := removeOptions{ opts := removeOptions{
names: args, names: args,
} }
return runSecretRemove(dockerCli, opts) return runSecretRemove(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completeNames(dockerCli)(cmd, args, toComplete) return completeNames(dockerCli)(cmd, args, toComplete)
@ -33,9 +33,8 @@ func newSecretRemoveCommand(dockerCli command.Cli) *cobra.Command {
} }
} }
func runSecretRemove(dockerCli command.Cli, opts removeOptions) error { func runSecretRemove(ctx context.Context, dockerCli command.Cli, opts removeOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
var errs []string var errs []string

View File

@ -28,7 +28,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
if len(args) > 1 { if len(args) > 1 {
opts.args = args[1:] opts.args = args[1:]
} }
return runCreate(dockerCli, cmd.Flags(), opts) return runCreate(cmd.Context(), dockerCli, cmd.Flags(), opts)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -76,12 +76,10 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions) error { func runCreate(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions) error {
apiClient := dockerCli.Client() apiClient := dockerCli.Client()
createOpts := types.ServiceCreateOptions{} createOpts := types.ServiceCreateOptions{}
ctx := context.Background()
service, err := opts.ToService(ctx, apiClient, flags) service, err := opts.ToService(ctx, apiClient, flags)
if err != nil { if err != nil {
return err return err
@ -94,14 +92,14 @@ func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions
specifiedSecrets := opts.secrets.Value() specifiedSecrets := opts.secrets.Value()
if len(specifiedSecrets) > 0 { if len(specifiedSecrets) > 0 {
// parse and validate secrets // parse and validate secrets
secrets, err := ParseSecrets(apiClient, specifiedSecrets) secrets, err := ParseSecrets(ctx, apiClient, specifiedSecrets)
if err != nil { if err != nil {
return err return err
} }
service.TaskTemplate.ContainerSpec.Secrets = secrets service.TaskTemplate.ContainerSpec.Secrets = secrets
} }
if err := setConfigs(apiClient, &service, opts); err != nil { if err := setConfigs(ctx, apiClient, &service, opts); err != nil {
return err return err
} }
@ -145,7 +143,7 @@ func runCreate(dockerCli command.Cli, flags *pflag.FlagSet, opts *serviceOptions
// setConfigs does double duty: it both sets the ConfigReferences of the // setConfigs does double duty: it both sets the ConfigReferences of the
// service, and it sets the service CredentialSpec. This is because there is an // service, and it sets the service CredentialSpec. This is because there is an
// interplay between the CredentialSpec and the Config it depends on. // interplay between the CredentialSpec and the Config it depends on.
func setConfigs(apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, opts *serviceOptions) error { func setConfigs(ctx context.Context, apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, opts *serviceOptions) error {
specifiedConfigs := opts.configs.Value() specifiedConfigs := opts.configs.Value()
// if the user has requested to use a Config, for the CredentialSpec add it // if the user has requested to use a Config, for the CredentialSpec add it
// to the specifiedConfigs as a RuntimeTarget. // to the specifiedConfigs as a RuntimeTarget.
@ -157,7 +155,7 @@ func setConfigs(apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, op
} }
if len(specifiedConfigs) > 0 { if len(specifiedConfigs) > 0 {
// parse and validate configs // parse and validate configs
configs, err := ParseConfigs(apiClient, specifiedConfigs) configs, err := ParseConfigs(ctx, apiClient, specifiedConfigs)
if err != nil { if err != nil {
return err return err
} }

View File

@ -96,8 +96,10 @@ func TestSetConfigsWithCredSpecAndConfigs(t *testing.T) {
}, nil }, nil
} }
ctx := context.Background()
// now call setConfigs // now call setConfigs
err := setConfigs(fakeClient, service, opts) err := setConfigs(ctx, fakeClient, service, opts)
// verify no error is returned // verify no error is returned
assert.NilError(t, err) assert.NilError(t, err)
@ -166,7 +168,8 @@ func TestSetConfigsOnlyCredSpec(t *testing.T) {
} }
// now call setConfigs // now call setConfigs
err := setConfigs(fakeClient, service, opts) ctx := context.Background()
err := setConfigs(ctx, fakeClient, service, opts)
// verify no error is returned // verify no error is returned
assert.NilError(t, err) assert.NilError(t, err)
@ -216,7 +219,8 @@ func TestSetConfigsOnlyConfigs(t *testing.T) {
} }
// now call setConfigs // now call setConfigs
err := setConfigs(fakeClient, service, opts) ctx := context.Background()
err := setConfigs(ctx, fakeClient, service, opts)
// verify no error is returned // verify no error is returned
assert.NilError(t, err) assert.NilError(t, err)
@ -262,7 +266,8 @@ func TestSetConfigsNoConfigs(t *testing.T) {
return nil, nil return nil, nil
} }
err := setConfigs(fakeClient, service, opts) ctx := context.Background()
err := setConfigs(ctx, fakeClient, service, opts)
assert.NilError(t, err) assert.NilError(t, err)
// ensure that the value of the credentialspec has not changed // ensure that the value of the credentialspec has not changed

View File

@ -33,7 +33,7 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
if opts.pretty && len(opts.format) > 0 { if opts.pretty && len(opts.format) > 0 {
return errors.Errorf("--format is incompatible with human friendly format") return errors.Errorf("--format is incompatible with human friendly format")
} }
return runInspect(dockerCli, opts) return runInspect(cmd.Context(), dockerCli, opts)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return CompletionFn(dockerCli)(cmd, args, toComplete) return CompletionFn(dockerCli)(cmd, args, toComplete)
@ -46,9 +46,8 @@ func newInspectCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runInspect(dockerCli command.Cli, opts inspectOptions) error { func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
if opts.pretty { if opts.pretty {
opts.format = "pretty" opts.format = "pretty"

View File

@ -31,7 +31,7 @@ func newListCommand(dockerCLI command.Cli) *cobra.Command {
Short: "List services", Short: "List services",
Args: cli.NoArgs, Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runList(dockerCLI, options) return runList(cmd.Context(), dockerCLI, options)
}, },
ValidArgsFunction: completion.NoComplete, ValidArgsFunction: completion.NoComplete,
} }
@ -44,10 +44,9 @@ func newListCommand(dockerCLI command.Cli) *cobra.Command {
return cmd return cmd
} }
func runList(dockerCLI command.Cli, options listOptions) error { func runList(ctx context.Context, dockerCLI command.Cli, options listOptions) error {
var ( var (
apiClient = dockerCLI.Client() apiClient = dockerCLI.Client()
ctx = context.Background()
err error err error
) )

View File

@ -47,7 +47,7 @@ func newLogsCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.target = args[0] opts.target = args[0]
return runLogs(dockerCli, &opts) return runLogs(cmd.Context(), dockerCli, &opts)
}, },
Annotations: map[string]string{"version": "1.29"}, Annotations: map[string]string{"version": "1.29"},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
@ -72,9 +72,7 @@ func newLogsCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runLogs(dockerCli command.Cli, opts *logsOptions) error { func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) error {
ctx := context.Background()
apiClient := dockerCli.Client() apiClient := dockerCli.Client()
var ( var (

View File

@ -12,13 +12,12 @@ import (
// ParseSecrets retrieves the secrets with the requested names and fills // ParseSecrets retrieves the secrets with the requested names and fills
// secret IDs into the secret references. // secret IDs into the secret references.
func ParseSecrets(apiClient client.SecretAPIClient, requestedSecrets []*swarmtypes.SecretReference) ([]*swarmtypes.SecretReference, error) { func ParseSecrets(ctx context.Context, apiClient client.SecretAPIClient, requestedSecrets []*swarmtypes.SecretReference) ([]*swarmtypes.SecretReference, error) {
if len(requestedSecrets) == 0 { if len(requestedSecrets) == 0 {
return []*swarmtypes.SecretReference{}, nil return []*swarmtypes.SecretReference{}, nil
} }
secretRefs := make(map[string]*swarmtypes.SecretReference) secretRefs := make(map[string]*swarmtypes.SecretReference)
ctx := context.Background()
for _, secret := range requestedSecrets { for _, secret := range requestedSecrets {
if _, exists := secretRefs[secret.File.Name]; exists { if _, exists := secretRefs[secret.File.Name]; exists {
@ -65,7 +64,7 @@ func ParseSecrets(apiClient client.SecretAPIClient, requestedSecrets []*swarmtyp
// ParseConfigs retrieves the configs from the requested names and converts // ParseConfigs retrieves the configs from the requested names and converts
// them to config references to use with the spec // them to config references to use with the spec
func ParseConfigs(apiClient client.ConfigAPIClient, requestedConfigs []*swarmtypes.ConfigReference) ([]*swarmtypes.ConfigReference, error) { func ParseConfigs(ctx context.Context, apiClient client.ConfigAPIClient, requestedConfigs []*swarmtypes.ConfigReference) ([]*swarmtypes.ConfigReference, error) {
if len(requestedConfigs) == 0 { if len(requestedConfigs) == 0 {
return []*swarmtypes.ConfigReference{}, nil return []*swarmtypes.ConfigReference{}, nil
} }
@ -83,7 +82,6 @@ func ParseConfigs(apiClient client.ConfigAPIClient, requestedConfigs []*swarmtyp
// it is only needed to be referenced once. // it is only needed to be referenced once.
configRefs := make(map[string]*swarmtypes.ConfigReference) configRefs := make(map[string]*swarmtypes.ConfigReference)
runtimeRefs := make(map[string]*swarmtypes.ConfigReference) runtimeRefs := make(map[string]*swarmtypes.ConfigReference)
ctx := context.Background()
for _, config := range requestedConfigs { for _, config := range requestedConfigs {
// copy the config, so we don't mutate the args // copy the config, so we don't mutate the args

View File

@ -35,7 +35,7 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command {
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
options.services = args options.services = args
return runPS(dockerCli, options) return runPS(cmd.Context(), dockerCli, options)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return CompletionFn(dockerCli)(cmd, args, toComplete) return CompletionFn(dockerCli)(cmd, args, toComplete)
@ -51,9 +51,8 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runPS(dockerCli command.Cli, options psOptions) error { func runPS(ctx context.Context, dockerCli command.Cli, options psOptions) error {
apiClient := dockerCli.Client() apiClient := dockerCli.Client()
ctx := context.Background()
filter, notfound, err := createFilter(ctx, apiClient, options) filter, notfound, err := createFilter(ctx, apiClient, options)
if err != nil { if err != nil {

View File

@ -89,7 +89,9 @@ func TestRunPSWarnsOnNotFound(t *testing.T) {
filter: opts.NewFilterOpt(), filter: opts.NewFilterOpt(),
format: "{{.ID}}", format: "{{.ID}}",
} }
err := runPS(cli, options)
ctx := context.Background()
err := runPS(ctx, cli, options)
assert.Error(t, err, "no such service: bar") assert.Error(t, err, "no such service: bar")
} }
@ -104,7 +106,8 @@ func TestRunPSQuiet(t *testing.T) {
} }
cli := test.NewFakeCli(client) cli := test.NewFakeCli(client)
err := runPS(cli, psOptions{services: []string{"foo"}, quiet: true, filter: opts.NewFilterOpt()}) ctx := context.Background()
err := runPS(ctx, cli, psOptions{services: []string{"foo"}, quiet: true, filter: opts.NewFilterOpt()})
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Equal("sxabyp0obqokwekpun4rjo0b3\n", cli.OutBuffer().String())) assert.Check(t, is.Equal("sxabyp0obqokwekpun4rjo0b3\n", cli.OutBuffer().String()))
} }

View File

@ -18,7 +18,7 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
Short: "Remove one or more services", Short: "Remove one or more services",
Args: cli.RequiresMinArgs(1), Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRemove(dockerCli, args) return runRemove(cmd.Context(), dockerCli, args)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return CompletionFn(dockerCli)(cmd, args, toComplete) return CompletionFn(dockerCli)(cmd, args, toComplete)
@ -29,11 +29,9 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRemove(dockerCli command.Cli, sids []string) error { func runRemove(ctx context.Context, dockerCli command.Cli, sids []string) error {
client := dockerCli.Client() client := dockerCli.Client()
ctx := context.Background()
var errs []string var errs []string
for _, sid := range sids { for _, sid := range sids {
err := client.ServiceRemove(ctx, sid) err := client.ServiceRemove(ctx, sid)

View File

@ -19,7 +19,7 @@ func newRollbackCommand(dockerCli command.Cli) *cobra.Command {
Short: "Revert changes to a service's configuration", Short: "Revert changes to a service's configuration",
Args: cli.ExactArgs(1), Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runRollback(dockerCli, options, args[0]) return runRollback(cmd.Context(), dockerCli, options, args[0])
}, },
Annotations: map[string]string{"version": "1.31"}, Annotations: map[string]string{"version": "1.31"},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
@ -34,9 +34,8 @@ func newRollbackCommand(dockerCli command.Cli) *cobra.Command {
return cmd return cmd
} }
func runRollback(dockerCli command.Cli, options *serviceOptions, serviceID string) error { func runRollback(ctx context.Context, dockerCli command.Cli, options *serviceOptions, serviceID string) error {
apiClient := dockerCli.Client() apiClient := dockerCli.Client()
ctx := context.Background()
service, _, err := apiClient.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) service, _, err := apiClient.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
if err != nil { if err != nil {

View File

@ -26,7 +26,7 @@ func newScaleCommand(dockerCli command.Cli) *cobra.Command {
Short: "Scale one or multiple replicated services", Short: "Scale one or multiple replicated services",
Args: scaleArgs, Args: scaleArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
return runScale(dockerCli, options, args) return runScale(cmd.Context(), dockerCli, options, args)
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return CompletionFn(dockerCli)(cmd, args, toComplete) return CompletionFn(dockerCli)(cmd, args, toComplete)
@ -56,10 +56,9 @@ func scaleArgs(cmd *cobra.Command, args []string) error {
return nil return nil
} }
func runScale(dockerCli command.Cli, options *scaleOptions, args []string) error { func runScale(ctx context.Context, dockerCli command.Cli, options *scaleOptions, args []string) error {
var errs []string var errs []string
var serviceIDs []string var serviceIDs []string
ctx := context.Background()
for _, arg := range args { for _, arg := range args {
serviceID, scaleStr, _ := strings.Cut(arg, "=") serviceID, scaleStr, _ := strings.Cut(arg, "=")

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