diff --git a/cli/command/container/exec.go b/cli/command/container/exec.go index 3d3a8595ab89..48c8d5f30ff3 100644 --- a/cli/command/container/exec.go +++ b/cli/command/container/exec.go @@ -2,6 +2,7 @@ package container import ( "context" + "errors" "fmt" "io" @@ -12,7 +13,6 @@ import ( "github.com/docker/cli/opts" "github.com/moby/moby/api/types/container" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) diff --git a/cli/command/container/export.go b/cli/command/container/export.go index 8c295847ae54..1b73e3eae1e0 100644 --- a/cli/command/container/export.go +++ b/cli/command/container/export.go @@ -2,13 +2,14 @@ package container import ( "context" + "errors" + "fmt" "io" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command/completion" "github.com/moby/sys/atomicwriter" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -53,7 +54,7 @@ func runExport(ctx context.Context, dockerCLI command.Cli, opts exportOptions) e } else { writer, err := atomicwriter.New(opts.output, 0o600) if err != nil { - return errors.Wrap(err, "failed to export container") + return fmt.Errorf("failed to export container: %w", err) } defer writer.Close() output = writer diff --git a/cli/command/container/list.go b/cli/command/container/list.go index 88b4170778db..6decdd3bdf99 100644 --- a/cli/command/container/list.go +++ b/cli/command/container/list.go @@ -2,6 +2,7 @@ package container import ( "context" + "fmt" "io" "github.com/docker/cli/cli" @@ -11,7 +12,6 @@ import ( "github.com/docker/cli/opts" "github.com/docker/cli/templates" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -84,7 +84,7 @@ func buildContainerListOptions(options *psOptions) (*client.ContainerListOptions if len(options.format) > 0 { tmpl, err := templates.Parse(options.format) if err != nil { - return nil, errors.Wrap(err, "failed to parse template") + return nil, fmt.Errorf("failed to parse template: %w", err) } optionsProcessor := formatter.NewContainerContext() @@ -92,7 +92,7 @@ func buildContainerListOptions(options *psOptions) (*client.ContainerListOptions // This shouldn't error out but swallowing the error makes it harder // to track down if preProcessor issues come up. if err := tmpl.Execute(io.Discard, optionsProcessor); err != nil { - return nil, errors.Wrap(err, "failed to execute template") + return nil, fmt.Errorf("failed to execute template: %w", err) } // if `size` was not explicitly set to false (with `--size=false`) diff --git a/cli/command/container/opts.go b/cli/command/container/opts.go index 2db794247d1b..d1faa7a88cc8 100644 --- a/cli/command/container/opts.go +++ b/cli/command/container/opts.go @@ -3,6 +3,7 @@ package container import ( "bytes" "encoding/json" + "errors" "fmt" "os" "path" @@ -19,7 +20,6 @@ import ( "github.com/moby/moby/api/types/container" "github.com/moby/moby/api/types/mount" "github.com/moby/moby/api/types/network" - "github.com/pkg/errors" "github.com/spf13/pflag" cdi "tags.cncf.io/container-device-interface/pkg/parser" ) @@ -351,7 +351,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con // Validate the input mac address if copts.macAddress != "" { if _, err := opts.ValidateMACAddress(copts.macAddress); err != nil { - return nil, errors.Errorf("%s is not a valid mac address", copts.macAddress) + return nil, fmt.Errorf("%s is not a valid mac address", copts.macAddress) } } if copts.stdin { @@ -367,7 +367,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con swappiness := copts.swappiness if swappiness != -1 && (swappiness < 0 || swappiness > 100) { - return nil, errors.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness) + return nil, fmt.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness) } var binds []string @@ -442,7 +442,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con // Merge in exposed ports to the map of published ports for _, e := range copts.expose.GetSlice() { if strings.Contains(e, ":") { - return nil, errors.Errorf("invalid port format for --expose: %s", e) + return nil, fmt.Errorf("invalid port format for --expose: %s", e) } // support two formats for expose, original format /[] // or /[] @@ -451,7 +451,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con // if expose a port, the start and end port are the same start, end, err := nat.ParsePortRange(port) if err != nil { - return nil, errors.Errorf("invalid range format for --expose: %s, error: %s", e, err) + return nil, fmt.Errorf("invalid range format for --expose: %s, error: %w", e, err) } for i := start; i <= end; i++ { p, err := nat.NewPort(proto, strconv.FormatUint(i, 10)) @@ -505,22 +505,22 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con pidMode := container.PidMode(copts.pidMode) if !pidMode.Valid() { - return nil, errors.Errorf("--pid: invalid PID mode") + return nil, errors.New("--pid: invalid PID mode") } utsMode := container.UTSMode(copts.utsMode) if !utsMode.Valid() { - return nil, errors.Errorf("--uts: invalid UTS mode") + return nil, errors.New("--uts: invalid UTS mode") } usernsMode := container.UsernsMode(copts.usernsMode) if !usernsMode.Valid() { - return nil, errors.Errorf("--userns: invalid USER mode") + return nil, errors.New("--userns: invalid USER mode") } cgroupnsMode := container.CgroupnsMode(copts.cgroupnsMode) if !cgroupnsMode.Valid() { - return nil, errors.Errorf("--cgroupns: invalid CGROUP mode") + return nil, errors.New("--cgroupns: invalid CGROUP mode") } restartPolicy, err := opts.ParseRestartPolicy(copts.restartPolicy) @@ -555,7 +555,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con copts.healthStartInterval != 0 if copts.noHealthcheck { if haveHealthSettings { - return nil, errors.Errorf("--no-healthcheck conflicts with --health-* options") + return nil, errors.New("--no-healthcheck conflicts with --health-* options") } healthConfig = &container.HealthConfig{Test: []string{"NONE"}} } else if haveHealthSettings { @@ -564,13 +564,13 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con probe = []string{"CMD-SHELL", copts.healthCmd} } if copts.healthInterval < 0 { - return nil, errors.Errorf("--health-interval cannot be negative") + return nil, errors.New("--health-interval cannot be negative") } if copts.healthTimeout < 0 { - return nil, errors.Errorf("--health-timeout cannot be negative") + return nil, errors.New("--health-timeout cannot be negative") } if copts.healthRetries < 0 { - return nil, errors.Errorf("--health-retries cannot be negative") + return nil, errors.New("--health-retries cannot be negative") } if copts.healthStartPeriod < 0 { return nil, errors.New("--health-start-period cannot be negative") @@ -703,7 +703,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con } if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() { - return nil, errors.Errorf("conflicting options: cannot specify both --restart and --rm") + return nil, errors.New("conflicting options: cannot specify both --restart and --rm") } // only set this value if the user provided the flag, else it should default to nil @@ -786,7 +786,7 @@ func parseNetworkOpts(copts *containerOptions) (map[string]*network.EndpointSett return nil, err } if _, ok := endpoints[n.Target]; ok { - return nil, invalidParameter(errors.Errorf("network %q is specified multiple times", n.Target)) + return nil, invalidParameter(fmt.Errorf("network %q is specified multiple times", n.Target)) } // For backward compatibility: if no custom options are provided for the network, @@ -884,7 +884,7 @@ func parseNetworkAttachmentOpt(ep opts.NetworkAttachmentOpts) (*network.Endpoint } if ep.MacAddress != "" { if _, err := opts.ValidateMACAddress(ep.MacAddress); err != nil { - return nil, errors.Errorf("%s is not a valid mac address", ep.MacAddress) + return nil, fmt.Errorf("%s is not a valid mac address", ep.MacAddress) } epConfig.MacAddress = ep.MacAddress } @@ -899,7 +899,7 @@ func convertToStandardNotation(ports []string) ([]string, error) { for _, param := range strings.Split(publish, ",") { k, v, ok := strings.Cut(param, "=") if !ok || k == "" { - return optsList, errors.Errorf("invalid publish opts format (should be name=value but got '%s')", param) + return optsList, fmt.Errorf("invalid publish opts format (should be name=value but got '%s')", param) } params[k] = v } @@ -914,7 +914,7 @@ func convertToStandardNotation(ports []string) ([]string, error) { func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) { loggingOptsMap := opts.ConvertKVStringsToMap(loggingOpts) if loggingDriver == "none" && len(loggingOpts) > 0 { - return map[string]string{}, errors.Errorf("invalid logging opts for driver %s", loggingDriver) + return map[string]string{}, fmt.Errorf("invalid logging opts for driver %s", loggingDriver) } return loggingOptsMap, nil } @@ -928,7 +928,7 @@ func parseSecurityOpts(securityOpts []string) ([]string, error) { } if (!ok || v == "") && k != "no-new-privileges" { // "no-new-privileges" is the only option that does not require a value. - return securityOpts, errors.Errorf("Invalid --security-opt: %q", opt) + return securityOpts, fmt.Errorf("invalid --security-opt: %q", opt) } if k == "seccomp" { switch v { @@ -939,11 +939,11 @@ func parseSecurityOpts(securityOpts []string) ([]string, error) { // content if it's valid JSON. f, err := os.ReadFile(v) if err != nil { - return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", v, err) + return securityOpts, fmt.Errorf("opening seccomp profile (%s) failed: %w", v, err) } b := bytes.NewBuffer(nil) if err := json.Compact(b, f); err != nil { - return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", v, err) + return securityOpts, fmt.Errorf("compacting json for seccomp profile (%s) failed: %w", v, err) } securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes()) } @@ -978,7 +978,7 @@ func parseStorageOpts(storageOpts []string) (map[string]string, error) { for _, option := range storageOpts { k, v, ok := strings.Cut(option, "=") if !ok { - return nil, errors.Errorf("invalid storage option") + return nil, errors.New("invalid storage option") } m[k] = v } @@ -993,7 +993,7 @@ func parseDevice(device, serverOS string) (container.DeviceMapping, error) { case "windows": return parseWindowsDevice(device) } - return container.DeviceMapping{}, errors.Errorf("unknown server OS: %s", serverOS) + return container.DeviceMapping{}, fmt.Errorf("unknown server OS: %s", serverOS) } // parseLinuxDevice parses a device mapping string to a container.DeviceMapping struct @@ -1017,7 +1017,7 @@ func parseLinuxDevice(device string) (container.DeviceMapping, error) { case 1: src = arr[0] default: - return container.DeviceMapping{}, errors.Errorf("invalid device specification: %s", device) + return container.DeviceMapping{}, fmt.Errorf("invalid device specification: %s", device) } if dst == "" { @@ -1047,7 +1047,7 @@ func validateDeviceCgroupRule(val string) (string, error) { return val, nil } - return val, errors.Errorf("invalid device cgroup format '%s'", val) + return val, fmt.Errorf("invalid device cgroup format '%s'", val) } // validDeviceMode checks if the mode for device is valid or not. @@ -1079,7 +1079,7 @@ func validateDevice(val string, serverOS string) (string, error) { // Windows does validation entirely server-side return val, nil } - return "", errors.Errorf("unknown server OS: %s", serverOS) + return "", fmt.Errorf("unknown server OS: %s", serverOS) } // validateLinuxPath is the implementation of validateDevice knowing that the @@ -1094,12 +1094,12 @@ func validateLinuxPath(val string, validator func(string) bool) (string, error) var mode string if strings.Count(val, ":") > 2 { - return val, errors.Errorf("bad format for path: %s", val) + return val, fmt.Errorf("bad format for path: %s", val) } split := strings.SplitN(val, ":", 3) if split[0] == "" { - return val, errors.Errorf("bad format for path: %s", val) + return val, fmt.Errorf("bad format for path: %s", val) } switch len(split) { case 1: @@ -1118,13 +1118,13 @@ func validateLinuxPath(val string, validator func(string) bool) (string, error) containerPath = split[1] mode = split[2] if isValid := validator(split[2]); !isValid { - return val, errors.Errorf("bad mode specified: %s", mode) + return val, fmt.Errorf("bad mode specified: %s", mode) } val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode) } if !path.IsAbs(containerPath) { - return val, errors.Errorf("%s is not an absolute path", containerPath) + return val, fmt.Errorf("%s is not an absolute path", containerPath) } return val, nil } @@ -1137,5 +1137,5 @@ func validateAttach(val string) (string, error) { return s, nil } } - return val, errors.Errorf("valid streams are STDIN, STDOUT and STDERR") + return val, errors.New("valid streams are STDIN, STDOUT and STDERR") } diff --git a/cli/command/container/port.go b/cli/command/container/port.go index af9a596680ca..1df09417df9a 100644 --- a/cli/command/container/port.go +++ b/cli/command/container/port.go @@ -13,7 +13,6 @@ import ( "github.com/docker/cli/cli/command/completion" "github.com/fvbommel/sortorder" "github.com/moby/moby/api/types/container" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -66,11 +65,11 @@ func runPort(ctx context.Context, dockerCli command.Cli, opts *portOptions) erro proto = "tcp" } if _, err = strconv.ParseUint(port, 10, 16); err != nil { - return errors.Wrapf(err, "Error: invalid port (%s)", port) + return fmt.Errorf("invalid port (%s): %w", port, err) } frontends, exists := c.NetworkSettings.Ports[container.PortRangeProto(port+"/"+proto)] if !exists || len(frontends) == 0 { - return errors.Errorf("Error: No public port '%s' published for %s", opts.port, opts.container) + return fmt.Errorf("no public port '%s' published for %s", opts.port, opts.container) } for _, frontend := range frontends { out = append(out, net.JoinHostPort(frontend.HostIP, frontend.HostPort)) diff --git a/cli/command/container/prune.go b/cli/command/container/prune.go index 68fa8516b378..ef11836bdbe0 100644 --- a/cli/command/container/prune.go +++ b/cli/command/container/prune.go @@ -2,6 +2,7 @@ package container import ( "context" + "errors" "fmt" "github.com/docker/cli/cli" @@ -10,7 +11,6 @@ import ( "github.com/docker/cli/internal/prompt" "github.com/docker/cli/opts" "github.com/docker/go-units" - "github.com/pkg/errors" "github.com/spf13/cobra" ) diff --git a/cli/command/container/rename.go b/cli/command/container/rename.go index 53020d1ef5c8..a4367c086792 100644 --- a/cli/command/container/rename.go +++ b/cli/command/container/rename.go @@ -2,33 +2,24 @@ package container import ( "context" + "errors" "fmt" "strings" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command/completion" - "github.com/pkg/errors" "github.com/spf13/cobra" ) -type renameOptions struct { - oldName string - newName string -} - // newRenameCommand creates a new cobra.Command for "docker container rename". func newRenameCommand(dockerCLI command.Cli) *cobra.Command { - var opts renameOptions - cmd := &cobra.Command{ Use: "rename CONTAINER NEW_NAME", Short: "Rename a container", Args: cli.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - opts.oldName = args[0] - opts.newName = args[1] - return runRename(cmd.Context(), dockerCLI, &opts) + return runRename(cmd.Context(), dockerCLI, args[0], args[1]) }, Annotations: map[string]string{ "aliases": "docker container rename, docker rename", @@ -39,17 +30,15 @@ func newRenameCommand(dockerCLI command.Cli) *cobra.Command { return cmd } -func runRename(ctx context.Context, dockerCli command.Cli, opts *renameOptions) error { - oldName := strings.TrimSpace(opts.oldName) - newName := strings.TrimSpace(opts.newName) - - if oldName == "" || newName == "" { - return errors.New("Error: Neither old nor new names may be empty") +func runRename(ctx context.Context, dockerCLI command.Cli, oldName, newName string) error { + newName = strings.TrimSpace(newName) + if newName == "" { + // TODO(thaJeztah): improve validation in ContainerRename and daemon; the daemon returns an obscure error when providing whitespace-only new-name: + // Error response from daemon: Error when allocating new name: Invalid container name (/ ), only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed + return errors.New("new name cannot be blank") } - - if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil { - fmt.Fprintln(dockerCli.Err(), err) - return errors.Errorf("Error: failed to rename container named %s", oldName) + if err := dockerCLI.Client().ContainerRename(ctx, oldName, newName); err != nil { + return fmt.Errorf("failed to rename container: %w", err) } return nil } diff --git a/cli/command/container/rename_test.go b/cli/command/container/rename_test.go index 2e14e771e534..4ca80c70f131 100644 --- a/cli/command/container/rename_test.go +++ b/cli/command/container/rename_test.go @@ -8,7 +8,6 @@ import ( "github.com/docker/cli/internal/test" "gotest.tools/v3/assert" - is "gotest.tools/v3/assert/cmp" ) func TestRunRename(t *testing.T) { @@ -25,13 +24,13 @@ func TestRunRename(t *testing.T) { doc: "empty old name", oldName: "", newName: "newName", - expectedErr: "Error: Neither old nor new names may be empty", + expectedErr: "invalid container name or ID: value is empty", }, { doc: "empty new name", oldName: "oldName", newName: "", - expectedErr: "Error: Neither old nor new names may be empty", + expectedErr: "new name cannot be blank", }, } @@ -39,6 +38,9 @@ func TestRunRename(t *testing.T) { t.Run(tc.doc, func(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ containerRenameFunc: func(ctx context.Context, oldName, newName string) error { + if oldName == "" { + return errors.New("invalid container name or ID: value is empty") + } return nil }, }) @@ -58,20 +60,3 @@ func TestRunRename(t *testing.T) { }) } } - -func TestRunRenameClientError(t *testing.T) { - cli := test.NewFakeCli(&fakeClient{ - containerRenameFunc: func(ctx context.Context, oldName, newName string) error { - return errors.New("client error") - }, - }) - - cmd := newRenameCommand(cli) - cmd.SetOut(io.Discard) - cmd.SetErr(io.Discard) - cmd.SetArgs([]string{"oldName", "newName"}) - - err := cmd.Execute() - - assert.Check(t, is.Error(err, "Error: failed to rename container named oldName")) -} diff --git a/cli/command/container/run.go b/cli/command/container/run.go index 2df0e90eb7ec..0500928a3f3b 100644 --- a/cli/command/container/run.go +++ b/cli/command/container/run.go @@ -2,6 +2,7 @@ package container import ( "context" + "errors" "fmt" "io" "strings" @@ -15,7 +16,6 @@ import ( "github.com/moby/moby/client" "github.com/moby/sys/signal" "github.com/moby/term" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" diff --git a/cli/command/container/start.go b/cli/command/container/start.go index 5af07f72b57d..5e4d61298773 100644 --- a/cli/command/container/start.go +++ b/cli/command/container/start.go @@ -2,6 +2,7 @@ package container import ( "context" + "errors" "fmt" "io" "strings" @@ -13,7 +14,6 @@ import ( "github.com/moby/moby/client" "github.com/moby/sys/signal" "github.com/moby/term" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -162,7 +162,7 @@ func RunStart(ctx context.Context, dockerCli command.Cli, opts *StartOptions) er // 5. Wait for attachment to break. if c.Config.Tty && dockerCli.Out().IsTerminal() { if err := MonitorTtySize(ctx, dockerCli, c.ID, false); err != nil { - fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err) + _, _ = fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err) } } if attachErr := <-cErr; attachErr != nil { @@ -197,15 +197,15 @@ func startContainersWithoutAttachments(ctx context.Context, dockerCli command.Cl var failedContainers []string for _, ctr := range containers { if err := dockerCli.Client().ContainerStart(ctx, ctr, client.ContainerStartOptions{}); err != nil { - fmt.Fprintln(dockerCli.Err(), err) + _, _ = fmt.Fprintln(dockerCli.Err(), err) failedContainers = append(failedContainers, ctr) continue } - fmt.Fprintln(dockerCli.Out(), ctr) + _, _ = fmt.Fprintln(dockerCli.Out(), ctr) } if len(failedContainers) > 0 { - return errors.Errorf("Error: failed to start containers: %s", strings.Join(failedContainers, ", ")) + return fmt.Errorf("failed to start containers: %s", strings.Join(failedContainers, ", ")) } return nil } diff --git a/cli/command/container/stats_helpers.go b/cli/command/container/stats_helpers.go index ffef30d7a2da..e80bcb97bfc3 100644 --- a/cli/command/container/stats_helpers.go +++ b/cli/command/container/stats_helpers.go @@ -3,13 +3,13 @@ package container import ( "context" "encoding/json" + "errors" "io" "sync" "time" "github.com/moby/moby/api/types/container" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/cli/command/container/update.go b/cli/command/container/update.go index 98344bab75ee..09f13057cae3 100644 --- a/cli/command/container/update.go +++ b/cli/command/container/update.go @@ -104,28 +104,28 @@ func runUpdate(ctx context.Context, dockerCli command.Cli, options *updateOption } } - resources := containertypes.Resources{ - BlkioWeight: options.blkioWeight, - CpusetCpus: options.cpusetCpus, - CpusetMems: options.cpusetMems, - CPUShares: options.cpuShares, - Memory: options.memory.Value(), - MemoryReservation: options.memoryReservation.Value(), - MemorySwap: options.memorySwap.Value(), - KernelMemory: options.kernelMemory.Value(), - CPUPeriod: options.cpuPeriod, - CPUQuota: options.cpuQuota, - CPURealtimePeriod: options.cpuRealtimePeriod, - CPURealtimeRuntime: options.cpuRealtimeRuntime, - NanoCPUs: options.cpus.Value(), - } - + var pidsLimit *int64 if options.pidsLimit != 0 { - resources.PidsLimit = &options.pidsLimit + pidsLimit = &options.pidsLimit } updateConfig := containertypes.UpdateConfig{ - Resources: resources, + Resources: containertypes.Resources{ + BlkioWeight: options.blkioWeight, + CpusetCpus: options.cpusetCpus, + CpusetMems: options.cpusetMems, + CPUShares: options.cpuShares, + Memory: options.memory.Value(), + MemoryReservation: options.memoryReservation.Value(), + MemorySwap: options.memorySwap.Value(), + KernelMemory: options.kernelMemory.Value(), + CPUPeriod: options.cpuPeriod, + CPUQuota: options.cpuQuota, + CPURealtimePeriod: options.cpuRealtimePeriod, + CPURealtimeRuntime: options.cpuRealtimeRuntime, + NanoCPUs: options.cpus.Value(), + PidsLimit: pidsLimit, + }, RestartPolicy: restartPolicy, } diff --git a/cli/command/image/build.go b/cli/command/image/build.go index 5357c2d9733f..b2340168e5be 100644 --- a/cli/command/image/build.go +++ b/cli/command/image/build.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -26,7 +27,6 @@ import ( "github.com/moby/moby/api/types/container" registrytypes "github.com/moby/moby/api/types/registry" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -212,7 +212,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) if options.imageIDFile != "" { // Avoid leaving a stale file if we eventually fail if err := os.Remove(options.imageIDFile); err != nil && !os.IsNotExist(err) { - return errors.Wrap(err, "Removing image ID file") + return fmt.Errorf("removing image ID file: %w", err) } } @@ -226,13 +226,13 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) case build.ContextTypeLocal: contextDir, relDockerfile, err = build.GetContextFromLocalDir(options.context, options.dockerfileName) if err != nil { - return errors.Errorf("unable to prepare context: %s", err) + return fmt.Errorf("unable to prepare context: %s", err) } if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { - // Dockerfile is outside of build-context; read the Dockerfile and pass it as dockerfileCtx + // Dockerfile is outside build-context; read the Dockerfile and pass it as dockerfileCtx dockerfileCtx, err = os.Open(options.dockerfileName) if err != nil { - return errors.Errorf("unable to open Dockerfile: %v", err) + return fmt.Errorf("unable to open Dockerfile: %w", err) } defer dockerfileCtx.Close() } @@ -240,7 +240,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) var tempDir string tempDir, relDockerfile, err = build.GetContextFromGitURL(options.context, options.dockerfileName) if err != nil { - return errors.Errorf("unable to prepare context: %s", err) + return fmt.Errorf("unable to prepare context: %w", err) } defer func() { _ = os.RemoveAll(tempDir) @@ -252,7 +252,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) _, _ = fmt.Fprintln(dockerCli.Err(), progBuff) } default: - return errors.Errorf("unable to prepare context: path %q not found", options.context) + return fmt.Errorf("unable to prepare context: path %q not found", options.context) } // read from a directory into tar archive @@ -263,7 +263,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) } if err := build.ValidateContextDirectory(contextDir, excludes); err != nil { - return errors.Wrap(err, "error checking context") + return fmt.Errorf("error checking context: %w", err) } // And canonicalize dockerfile name to a platform-independent one @@ -370,7 +370,7 @@ func runBuild(ctx context.Context, dockerCli command.Cli, options buildOptions) if options.imageIDFile != "" { if imageID == "" { - return errors.Errorf("Server did not provide an image ID. Cannot write %s", options.imageIDFile) + return fmt.Errorf("server did not provide an image ID. Cannot write %s", options.imageIDFile) } if err := os.WriteFile(options.imageIDFile, []byte(imageID), 0o666); err != nil { return err diff --git a/cli/command/image/build/context.go b/cli/command/image/build/context.go index 2f514018a573..fb524c36cc9e 100644 --- a/cli/command/image/build/context.go +++ b/cli/command/image/build/context.go @@ -6,6 +6,7 @@ import ( "bytes" "crypto/rand" "encoding/hex" + "errors" "fmt" "io" "net/http" @@ -22,7 +23,6 @@ import ( "github.com/moby/moby/api/pkg/progress" "github.com/moby/moby/api/pkg/streamformatter" "github.com/moby/patternmatcher" - "github.com/pkg/errors" ) const ( @@ -49,10 +49,10 @@ func ValidateContextDirectory(srcPath string, excludes []string) error { return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error { if err != nil { if os.IsPermission(err) { - return errors.Errorf("can't stat '%s'", filePath) + return fmt.Errorf("can't stat '%s'", filePath) } if os.IsNotExist(err) { - return errors.Errorf("file ('%s') not found or excluded by .dockerignore", filePath) + return fmt.Errorf("file ('%s') not found or excluded by .dockerignore", filePath) } return err } @@ -78,7 +78,7 @@ func ValidateContextDirectory(srcPath string, excludes []string) error { if !f.IsDir() { currentFile, err := os.Open(filePath) if err != nil && os.IsPermission(err) { - return errors.Errorf("no permission to read from '%s'", filePath) + return fmt.Errorf("no permission to read from '%s'", filePath) } currentFile.Close() } @@ -105,7 +105,7 @@ func DetectArchiveReader(input io.ReadCloser) (rc io.ReadCloser, isArchive bool, magic, err := buf.Peek(archiveHeaderSize * 2) if err != nil && err != io.EOF { - return nil, false, errors.Errorf("failed to peek context header from STDIN: %v", err) + return nil, false, fmt.Errorf("failed to peek context header from STDIN: %w", err) } return newReadCloserWrapper(buf, func() error { return input.Close() }), IsArchive(magic), nil @@ -118,7 +118,7 @@ func WriteTempDockerfile(rc io.ReadCloser) (dockerfileDir string, err error) { // err is a named return value, due to the defer call below. dockerfileDir, err = os.MkdirTemp("", "docker-build-tempdockerfile-") if err != nil { - return "", errors.Errorf("unable to create temporary context directory: %v", err) + return "", fmt.Errorf("unable to create temporary context directory: %w", err) } defer func() { if err != nil { @@ -194,11 +194,11 @@ func IsArchive(header []byte) bool { // success. func GetContextFromGitURL(gitURL, dockerfileName string) (string, string, error) { if _, err := exec.LookPath("git"); err != nil { - return "", "", errors.Wrapf(err, "unable to find 'git'") + return "", "", fmt.Errorf("unable to find 'git': %w", err) } absContextDir, err := git.Clone(gitURL) if err != nil { - return "", "", errors.Wrapf(err, "unable to 'git clone' to temporary context directory") + return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %w", err) } absContextDir, err = ResolveAndValidateContextPath(absContextDir) @@ -207,7 +207,7 @@ func GetContextFromGitURL(gitURL, dockerfileName string) (string, string, error) } relDockerfile, err := getDockerfileRelPath(absContextDir, dockerfileName) if err == nil && strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { - return "", "", errors.Errorf("the Dockerfile (%s) must be within the build context", dockerfileName) + return "", "", fmt.Errorf("the Dockerfile (%s) must be within the build context", dockerfileName) } return absContextDir, relDockerfile, err @@ -220,7 +220,7 @@ func GetContextFromGitURL(gitURL, dockerfileName string) (string, string, error) func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) { response, err := getWithStatusError(remoteURL) if err != nil { - return nil, "", errors.Errorf("unable to download remote context %s: %v", remoteURL, err) + return nil, "", fmt.Errorf("unable to download remote context %s: %w", remoteURL, err) } progressOutput := streamformatter.NewProgressOutput(out) @@ -244,9 +244,9 @@ func getWithStatusError(url string) (resp *http.Response, err error) { body, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { - return nil, errors.Wrapf(err, "%s: error reading body", msg) + return nil, fmt.Errorf("%s: error reading body: %w", msg, err) } - return nil, errors.Errorf("%s: %s", msg, bytes.TrimSpace(body)) + return nil, fmt.Errorf("%s: %s", msg, bytes.TrimSpace(body)) } // GetContextFromLocalDir uses the given local directory as context for a @@ -264,7 +264,7 @@ func GetContextFromLocalDir(localDir, dockerfileName string) (string, string, er // current directory and not the context directory. if dockerfileName != "" && dockerfileName != "-" { if dockerfileName, err = filepath.Abs(dockerfileName); err != nil { - return "", "", errors.Errorf("unable to get absolute path to Dockerfile: %v", err) + return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %w", err) } } @@ -277,7 +277,7 @@ func GetContextFromLocalDir(localDir, dockerfileName string) (string, string, er func ResolveAndValidateContextPath(givenContextDir string) (string, error) { absContextDir, err := filepath.Abs(givenContextDir) if err != nil { - return "", errors.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err) + return "", fmt.Errorf("unable to get absolute context directory of given context directory %q: %w", givenContextDir, err) } // The context dir might be a symbolic link, so follow it to the actual @@ -290,17 +290,17 @@ func ResolveAndValidateContextPath(givenContextDir string) (string, error) { if !isUNC(absContextDir) { absContextDir, err = filepath.EvalSymlinks(absContextDir) if err != nil { - return "", errors.Errorf("unable to evaluate symlinks in context path: %v", err) + return "", fmt.Errorf("unable to evaluate symlinks in context path: %w", err) } } stat, err := os.Lstat(absContextDir) if err != nil { - return "", errors.Errorf("unable to stat context directory %q: %v", absContextDir, err) + return "", fmt.Errorf("unable to stat context directory %q: %w", absContextDir, err) } if !stat.IsDir() { - return "", errors.Errorf("context must be a directory: %s", absContextDir) + return "", fmt.Errorf("context must be a directory: %s", absContextDir) } return absContextDir, err } @@ -345,20 +345,20 @@ func getDockerfileRelPath(absContextDir, givenDockerfile string) (string, error) if !isUNC(absDockerfile) { absDockerfile, err = filepath.EvalSymlinks(absDockerfile) if err != nil { - return "", errors.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err) + return "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %w", err) } } if _, err := os.Lstat(absDockerfile); err != nil { if os.IsNotExist(err) { - return "", errors.Errorf("Cannot locate Dockerfile: %q", absDockerfile) + return "", fmt.Errorf("cannot locate Dockerfile: %q", absDockerfile) } - return "", errors.Errorf("unable to stat Dockerfile: %v", err) + return "", fmt.Errorf("unable to stat Dockerfile: %w", err) } relDockerfile, err := filepath.Rel(absContextDir, absDockerfile) if err != nil { - return "", errors.Errorf("unable to get relative Dockerfile path: %v", err) + return "", fmt.Errorf("unable to get relative Dockerfile path: %w", err) } return relDockerfile, nil @@ -443,7 +443,7 @@ func Compress(buildCtx io.ReadCloser) (io.ReadCloser, error) { defer buildCtx.Close() if _, err := io.Copy(compressWriter, buildCtx); err != nil { - pipeWriter.CloseWithError(errors.Wrap(err, "failed to compress context")) + pipeWriter.CloseWithError(fmt.Errorf("failed to compress context: %w", err)) compressWriter.Close() return } diff --git a/cli/command/image/history.go b/cli/command/image/history.go index 4f166144ef0d..a8a4de8be11e 100644 --- a/cli/command/image/history.go +++ b/cli/command/image/history.go @@ -2,6 +2,7 @@ package image import ( "context" + "fmt" "github.com/containerd/platforms" "github.com/docker/cli/cli" @@ -10,7 +11,6 @@ import ( "github.com/docker/cli/cli/command/formatter" flagsHelper "github.com/docker/cli/cli/flags" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -61,7 +61,7 @@ func runHistory(ctx context.Context, dockerCli command.Cli, opts historyOptions) if opts.platform != "" { p, err := platforms.Parse(opts.platform) if err != nil { - return errors.Wrap(err, "invalid platform") + return fmt.Errorf("invalid platform: %w", err) } options = append(options, client.ImageHistoryWithPlatform(p)) } diff --git a/cli/command/image/load.go b/cli/command/image/load.go index 0abca52fb8cf..664d1fea56f5 100644 --- a/cli/command/image/load.go +++ b/cli/command/image/load.go @@ -2,6 +2,8 @@ package image import ( "context" + "errors" + "fmt" "io" "github.com/containerd/platforms" @@ -12,7 +14,6 @@ import ( "github.com/moby/moby/client" "github.com/moby/sys/sequential" ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -60,7 +61,7 @@ func runLoad(ctx context.Context, dockerCli command.Cli, opts loadOptions) error // To avoid getting stuck, verify that a tar file is given either in // the input flag or through stdin and if not display an error message and exit. if dockerCli.In().IsTerminal() { - return errors.Errorf("requested load from stdin, but stdin is empty") + return errors.New("requested load from stdin, but stdin is empty") } default: // We use sequential.Open to use sequential file access on Windows, avoiding @@ -82,7 +83,7 @@ func runLoad(ctx context.Context, dockerCli command.Cli, opts loadOptions) error for _, p := range opts.platform { pp, err := platforms.Parse(p) if err != nil { - return errors.Wrap(err, "invalid platform") + return fmt.Errorf("invalid platform: %w", err) } platformList = append(platformList, pp) } diff --git a/cli/command/image/prune.go b/cli/command/image/prune.go index e02b006e9c14..2c6d322a3e48 100644 --- a/cli/command/image/prune.go +++ b/cli/command/image/prune.go @@ -2,6 +2,7 @@ package image import ( "context" + "errors" "fmt" "strconv" "strings" @@ -12,7 +13,6 @@ import ( "github.com/docker/cli/internal/prompt" "github.com/docker/cli/opts" "github.com/docker/go-units" - "github.com/pkg/errors" "github.com/spf13/cobra" ) diff --git a/cli/command/image/push.go b/cli/command/image/push.go index 6fcea53c3a5f..4ec8cd76e812 100644 --- a/cli/command/image/push.go +++ b/cli/command/image/push.go @@ -6,6 +6,7 @@ package image import ( "context" "encoding/json" + "errors" "fmt" "io" @@ -23,7 +24,6 @@ import ( "github.com/moby/moby/client" "github.com/morikuni/aec" ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" "github.com/spf13/cobra" ) diff --git a/cli/command/image/save.go b/cli/command/image/save.go index 11986feb3190..1309b4c95500 100644 --- a/cli/command/image/save.go +++ b/cli/command/image/save.go @@ -2,6 +2,8 @@ package image import ( "context" + "errors" + "fmt" "io" "github.com/containerd/platforms" @@ -11,7 +13,6 @@ import ( "github.com/moby/moby/client" "github.com/moby/sys/atomicwriter" ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -58,7 +59,7 @@ func runSave(ctx context.Context, dockerCLI command.Cli, opts saveOptions) error for _, p := range opts.platform { pp, err := platforms.Parse(p) if err != nil { - return errors.Wrap(err, "invalid platform") + return fmt.Errorf("invalid platform: %w", err) } platformList = append(platformList, pp) } @@ -75,7 +76,7 @@ func runSave(ctx context.Context, dockerCLI command.Cli, opts saveOptions) error } else { writer, err := atomicwriter.New(opts.output, 0o600) if err != nil { - return errors.Wrap(err, "failed to save image") + return fmt.Errorf("failed to save image: %w", err) } defer writer.Close() output = writer diff --git a/cli/command/image/trust.go b/cli/command/image/trust.go index d613486f73d5..80afa3252dbf 100644 --- a/cli/command/image/trust.go +++ b/cli/command/image/trust.go @@ -3,6 +3,7 @@ package image import ( "context" "encoding/hex" + "errors" "fmt" "io" @@ -16,7 +17,6 @@ import ( registrytypes "github.com/moby/moby/api/types/registry" "github.com/moby/moby/client" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" "github.com/sirupsen/logrus" notaryclient "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/tuf/data" @@ -102,7 +102,7 @@ func trustedPull(ctx context.Context, cli command.Cli, imgRefAndAuth trust.Image func getTrustedPullTargets(cli command.Cli, imgRefAndAuth trust.ImageRefAndAuth) ([]target, error) { notaryRepo, err := newNotaryClient(cli, imgRefAndAuth) if err != nil { - return nil, errors.Wrap(err, "error establishing connection to trust repository") + return nil, fmt.Errorf("error establishing connection to trust repository: %w", err) } ref := imgRefAndAuth.Reference() @@ -128,7 +128,7 @@ func getTrustedPullTargets(cli command.Cli, imgRefAndAuth trust.ImageRefAndAuth) refs = append(refs, t) } if len(refs) == 0 { - return nil, trust.NotaryError(ref.Name(), errors.Errorf("No trusted tags for %s", ref.Name())) + return nil, trust.NotaryError(ref.Name(), fmt.Errorf("no trusted tags for %s", ref.Name())) } return refs, nil } @@ -140,7 +140,7 @@ func getTrustedPullTargets(cli command.Cli, imgRefAndAuth trust.ImageRefAndAuth) // Only get the tag if it's in the top level targets role or the releases delegation role // ignore it if it's in any other delegation roles if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { - return nil, trust.NotaryError(ref.Name(), errors.Errorf("No trust data for %s", tagged.Tag())) + return nil, trust.NotaryError(ref.Name(), fmt.Errorf("no trust data for %s", tagged.Tag())) } logrus.Debugf("retrieving target for %s role", t.Role) @@ -181,7 +181,7 @@ func TrustedReference(ctx context.Context, cli command.Cli, ref reference.NamedT notaryRepo, err := newNotaryClient(cli, imgRefAndAuth) if err != nil { - return nil, errors.Wrap(err, "error establishing connection to trust repository") + return nil, fmt.Errorf("error establishing connection to trust repository: %w", err) } t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole) diff --git a/cli/command/node/update.go b/cli/command/node/update.go index 63a66a41932d..ffcd426ffca5 100644 --- a/cli/command/node/update.go +++ b/cli/command/node/update.go @@ -2,6 +2,7 @@ package node import ( "context" + "errors" "fmt" "github.com/docker/cli/cli" @@ -10,7 +11,6 @@ import ( "github.com/docker/cli/opts" "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -64,7 +64,7 @@ func updateNodes(ctx context.Context, apiClient client.NodeAPIClient, nodes []st err = mergeNode(&node) if err != nil { - if err == errNoRoleChange { + if errors.Is(err, errNoRoleChange) { continue } return err @@ -110,7 +110,7 @@ func mergeNodeUpdate(flags *pflag.FlagSet) func(*swarm.Node) error { for _, k := range keys { // if a key doesn't exist, fail the command explicitly if _, exists := spec.Annotations.Labels[k]; !exists { - return errors.Errorf("key %s doesn't exist in node's labels", k) + return fmt.Errorf("key %s doesn't exist in node's labels", k) } delete(spec.Annotations.Labels, k) } diff --git a/cli/command/plugin/create.go b/cli/command/plugin/create.go index eb618758ada5..90ee99d31752 100644 --- a/cli/command/plugin/create.go +++ b/cli/command/plugin/create.go @@ -3,6 +3,7 @@ package plugin import ( "context" "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -14,7 +15,6 @@ import ( "github.com/moby/go-archive/compression" "github.com/moby/moby/api/types/plugin" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -52,7 +52,7 @@ func validateContextDir(contextDir string) (string, error) { } if !stat.IsDir() { - return "", errors.Errorf("context must be a directory") + return "", errors.New("context must be a directory") } return absContextDir, nil diff --git a/cli/command/plugin/enable.go b/cli/command/plugin/enable.go index 03ea9d56c1bb..ac61ba2c892d 100644 --- a/cli/command/plugin/enable.go +++ b/cli/command/plugin/enable.go @@ -7,7 +7,6 @@ import ( "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -36,7 +35,7 @@ func newEnableCommand(dockerCLI command.Cli) *cobra.Command { func runEnable(ctx context.Context, dockerCli command.Cli, name string, opts client.PluginEnableOptions) error { if opts.Timeout < 0 { - return errors.Errorf("negative timeout %d is invalid", opts.Timeout) + return fmt.Errorf("negative timeout %d is invalid", opts.Timeout) } return dockerCli.Client().PluginEnable(ctx, name, opts) } diff --git a/cli/command/plugin/install.go b/cli/command/plugin/install.go index db9ed0f4a266..21ed74782a71 100644 --- a/cli/command/plugin/install.go +++ b/cli/command/plugin/install.go @@ -11,7 +11,6 @@ import ( "github.com/docker/cli/internal/prompt" "github.com/moby/moby/api/types/plugin" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -82,7 +81,7 @@ func runInstall(ctx context.Context, dockerCLI command.Cli, opts pluginOptions) return err } if _, ok := aref.(reference.Canonical); ok { - return errors.Errorf("invalid name: %s", opts.localName) + return fmt.Errorf("invalid name: %s", opts.localName) } localName = reference.FamiliarString(reference.TagNameOnly(aref)) } diff --git a/cli/command/plugin/upgrade.go b/cli/command/plugin/upgrade.go index 62924dcc8ba5..1fddf7913121 100644 --- a/cli/command/plugin/upgrade.go +++ b/cli/command/plugin/upgrade.go @@ -2,6 +2,7 @@ package plugin import ( "context" + "errors" "fmt" "github.com/distribution/reference" @@ -9,7 +10,6 @@ import ( "github.com/docker/cli/cli/command" "github.com/docker/cli/internal/jsonstream" "github.com/docker/cli/internal/prompt" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -41,11 +41,11 @@ func newUpgradeCommand(dockerCLI command.Cli) *cobra.Command { func runUpgrade(ctx context.Context, dockerCLI command.Cli, opts pluginOptions) error { p, _, err := dockerCLI.Client().PluginInspectWithRaw(ctx, opts.localName) if err != nil { - return errors.Errorf("error reading plugin data: %v", err) + return fmt.Errorf("error reading plugin data: %w", err) } if p.Enabled { - return errors.Errorf("the plugin must be disabled before upgrading") + return errors.New("the plugin must be disabled before upgrading") } opts.localName = p.Name @@ -54,13 +54,13 @@ func runUpgrade(ctx context.Context, dockerCLI command.Cli, opts pluginOptions) } remote, err := reference.ParseNormalizedNamed(opts.remote) if err != nil { - return errors.Wrap(err, "error parsing remote upgrade image reference") + return fmt.Errorf("error parsing remote upgrade image reference: %w", err) } remote = reference.TagNameOnly(remote) old, err := reference.ParseNormalizedNamed(p.PluginReference) if err != nil { - return errors.Wrap(err, "error parsing current image reference") + return fmt.Errorf("error parsing current image reference: %w", err) } old = reference.TagNameOnly(old) diff --git a/cli/command/secret/create.go b/cli/command/secret/create.go index 6216d5ee17a6..5efaf717d329 100644 --- a/cli/command/secret/create.go +++ b/cli/command/secret/create.go @@ -2,6 +2,7 @@ package secret import ( "context" + "errors" "fmt" "io" @@ -10,7 +11,6 @@ import ( "github.com/docker/cli/opts" "github.com/moby/moby/api/types/swarm" "github.com/moby/sys/sequential" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -56,7 +56,7 @@ func runSecretCreate(ctx context.Context, dockerCLI command.Cli, options createO var secretData []byte if options.driver != "" { if options.file != "" { - return errors.Errorf("When using secret driver secret data must be empty") + return errors.New("when using secret driver secret data must be empty") } } else { var err error diff --git a/cli/command/service/formatter.go b/cli/command/service/formatter.go index bb15ff16df43..ba00600a995c 100644 --- a/cli/command/service/formatter.go +++ b/cli/command/service/formatter.go @@ -1,6 +1,7 @@ package service import ( + "errors" "fmt" "sort" "strconv" @@ -16,7 +17,6 @@ import ( "github.com/moby/moby/api/types/mount" "github.com/moby/moby/api/types/network" "github.com/moby/moby/api/types/swarm" - "github.com/pkg/errors" ) const serviceInspectPrettyTemplate formatter.Format = ` @@ -231,7 +231,7 @@ func inspectFormatWrite(fmtCtx formatter.Context, refs []string, getRef, getNetw } service, ok := serviceI.(swarm.Service) if !ok { - return errors.Errorf("got wrong object to inspect") + return errors.New("got wrong object to inspect") } if err := format(&serviceInspectContext{ Service: service, diff --git a/cli/command/service/generic_resource_opts.go b/cli/command/service/generic_resource_opts.go index 9d00d9444a5a..064111a3dba2 100644 --- a/cli/command/service/generic_resource_opts.go +++ b/cli/command/service/generic_resource_opts.go @@ -4,8 +4,6 @@ import ( "fmt" "strings" - "github.com/pkg/errors" - "github.com/moby/moby/api/types/swarm" swarmapi "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/api/genericresource" @@ -37,7 +35,7 @@ func ParseGenericResources(value []string) ([]swarm.GenericResource, error) { resources, err := genericresource.Parse(value) if err != nil { - return nil, errors.Wrapf(err, "invalid generic resource specification") + return nil, fmt.Errorf("invalid generic resource specification: %w", err) } swarmResources := genericResourcesFromGRPC(resources) diff --git a/cli/command/service/inspect.go b/cli/command/service/inspect.go index 6afa2ccdba54..46b70eb079f7 100644 --- a/cli/command/service/inspect.go +++ b/cli/command/service/inspect.go @@ -5,6 +5,8 @@ package service import ( "context" + "errors" + "fmt" "strings" "github.com/containerd/errdefs" @@ -13,7 +15,6 @@ import ( "github.com/docker/cli/cli/command/formatter" flagsHelper "github.com/docker/cli/cli/flags" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -35,7 +36,7 @@ func newInspectCommand(dockerCLI command.Cli) *cobra.Command { opts.refs = args if opts.pretty && len(opts.format) > 0 { - return errors.Errorf("--format is incompatible with human friendly format") + return errors.New("--format is incompatible with human friendly format") } return runInspect(cmd.Context(), dockerCLI, opts) }, @@ -69,7 +70,7 @@ func runInspect(ctx context.Context, dockerCLI command.Cli, opts inspectOptions) if err == nil || !errdefs.IsNotFound(err) { return service, nil, err } - return nil, nil, errors.Errorf("Error: no such service: %s", ref) + return nil, nil, fmt.Errorf("no such service: %s", ref) } getNetwork := func(ref string) (any, []byte, error) { @@ -77,7 +78,7 @@ func runInspect(ctx context.Context, dockerCLI command.Cli, opts inspectOptions) if err == nil || !errdefs.IsNotFound(err) { return nw, nil, err } - return nil, nil, errors.Errorf("Error: no such network: %s", ref) + return nil, nil, fmt.Errorf("no such network: %s", ref) } f := opts.format @@ -91,7 +92,7 @@ func runInspect(ctx context.Context, dockerCLI command.Cli, opts inspectOptions) // check if the user is trying to apply a template to the pretty format, which // is not supported if strings.HasPrefix(f, "pretty") && f != "pretty" { - return errors.Errorf("Cannot supply extra formatting options to the pretty template") + return errors.New("cannot supply extra formatting options to the pretty template") } serviceCtx := formatter.Context{ diff --git a/cli/command/service/logs.go b/cli/command/service/logs.go index 8130a2e45115..3a103d9891b2 100644 --- a/cli/command/service/logs.go +++ b/cli/command/service/logs.go @@ -3,6 +3,7 @@ package service import ( "bytes" "context" + "errors" "fmt" "io" "sort" @@ -18,7 +19,6 @@ import ( "github.com/moby/moby/api/pkg/stdcopy" "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -260,7 +260,7 @@ func (lw *logWriter) Write(buf []byte) (int, error) { // break up the log line into parts. parts := bytes.SplitN(buf, []byte(" "), numParts) if len(parts) != numParts { - return 0, errors.Errorf("invalid context in log message: %v", string(buf)) + return 0, fmt.Errorf("invalid context in log message: %v", string(buf)) } // parse the details out details, err := logdetails.Parse(string(parts[detailsIndex])) @@ -325,19 +325,19 @@ func (lw *logWriter) Write(buf []byte) (int, error) { func parseContext(details map[string]string) (logContext, error) { nodeID, ok := details["com.docker.swarm.node.id"] if !ok { - return logContext{}, errors.Errorf("missing node id in details: %v", details) + return logContext{}, fmt.Errorf("missing node id in details: %v", details) } delete(details, "com.docker.swarm.node.id") serviceID, ok := details["com.docker.swarm.service.id"] if !ok { - return logContext{}, errors.Errorf("missing service id in details: %v", details) + return logContext{}, fmt.Errorf("missing service id in details: %v", details) } delete(details, "com.docker.swarm.service.id") taskID, ok := details["com.docker.swarm.task.id"] if !ok { - return logContext{}, errors.Errorf("missing task id in details: %s", details) + return logContext{}, fmt.Errorf("missing task id in details: %s", details) } delete(details, "com.docker.swarm.task.id") diff --git a/cli/command/service/opts.go b/cli/command/service/opts.go index f8560b01826e..2dc89fffcb92 100644 --- a/cli/command/service/opts.go +++ b/cli/command/service/opts.go @@ -5,6 +5,7 @@ package service import ( "context" + "errors" "fmt" "sort" "strconv" @@ -20,7 +21,6 @@ import ( "github.com/moby/moby/client" "github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/api/defaults" - "github.com/pkg/errors" "github.com/spf13/pflag" ) @@ -100,7 +100,7 @@ func (o *placementPrefOpts) Set(value string) error { return errors.New(`placement preference must be of the format "="`) } if strategy != "spread" { - return errors.Errorf("unsupported placement preference %s (only spread is supported)", strategy) + return fmt.Errorf("unsupported placement preference %s (only spread is supported)", strategy) } o.prefs = append(o.prefs, swarm.PlacementPreference{ @@ -472,7 +472,7 @@ func (o *healthCheckOptions) toHealthConfig() (*container.HealthConfig, error) { o.retries != 0 if o.noHealthcheck { if haveHealthSettings { - return nil, errors.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck) + return nil, fmt.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck) } healthConfig = &container.HealthConfig{Test: []string{"NONE"}} } else if haveHealthSettings { @@ -610,7 +610,7 @@ func (options *serviceOptions) ToServiceMode() (swarm.ServiceMode, error) { switch options.mode { case "global": if options.replicas.Value() != nil { - return serviceMode, errors.Errorf("replicas can only be used with replicated or replicated-job mode") + return serviceMode, errors.New("replicas can only be used with replicated or replicated-job mode") } if options.maxReplicas > 0 { @@ -646,11 +646,11 @@ func (options *serviceOptions) ToServiceMode() (swarm.ServiceMode, error) { return serviceMode, errors.New("max-concurrent can only be used with replicated-job mode") } if options.replicas.Value() != nil { - return serviceMode, errors.Errorf("replicas can only be used with replicated or replicated-job mode") + return serviceMode, errors.New("replicas can only be used with replicated or replicated-job mode") } serviceMode.GlobalJob = &swarm.GlobalJob{} default: - return serviceMode, errors.Errorf("Unknown mode: %s, only replicated and global supported", options.mode) + return serviceMode, fmt.Errorf("unknown mode: %s, only replicated and global supported", options.mode) } return serviceMode, nil } @@ -718,7 +718,7 @@ func (options *serviceOptions) ToService(ctx context.Context, apiClient client.N // flags are not set, then the values will be nil. If they are non-nil, // then return an error. if (serviceMode.ReplicatedJob != nil || serviceMode.GlobalJob != nil) && (updateConfig != nil || rollbackConfig != nil) { - return service, errors.Errorf("update and rollback configuration is not supported for jobs") + return service, errors.New("update and rollback configuration is not supported for jobs") } networks := convertNetworks(options.networks) diff --git a/cli/command/service/parse.go b/cli/command/service/parse.go index 38c8e82674e7..9bc8bdb7d98b 100644 --- a/cli/command/service/parse.go +++ b/cli/command/service/parse.go @@ -2,11 +2,11 @@ package service import ( "context" + "fmt" "github.com/moby/moby/api/types/filters" "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/client" - "github.com/pkg/errors" ) // ParseSecrets retrieves the secrets with the requested names and fills @@ -20,7 +20,7 @@ func ParseSecrets(ctx context.Context, apiClient client.SecretAPIClient, request for _, secret := range requestedSecrets { if _, exists := secretRefs[secret.File.Name]; exists { - return nil, errors.Errorf("duplicate secret target for %s not allowed", secret.SecretName) + return nil, fmt.Errorf("duplicate secret target for %s not allowed", secret.SecretName) } secretRef := new(swarm.SecretReference) *secretRef = *secret @@ -49,7 +49,7 @@ func ParseSecrets(ctx context.Context, apiClient client.SecretAPIClient, request for _, ref := range secretRefs { id, ok := foundSecrets[ref.SecretName] if !ok { - return nil, errors.Errorf("secret not found: %s", ref.SecretName) + return nil, fmt.Errorf("secret not found: %s", ref.SecretName) } // set the id for the ref to properly assign in swarm @@ -98,7 +98,7 @@ func ParseConfigs(ctx context.Context, apiClient client.ConfigAPIClient, request } if _, exists := configRefs[config.File.Name]; exists { - return nil, errors.Errorf("duplicate config target for %s not allowed", config.ConfigName) + return nil, fmt.Errorf("duplicate config target for %s not allowed", config.ConfigName) } configRefs[config.File.Name] = configRef @@ -129,7 +129,7 @@ func ParseConfigs(ctx context.Context, apiClient client.ConfigAPIClient, request for _, ref := range configRefs { id, ok := foundConfigs[ref.ConfigName] if !ok { - return nil, errors.Errorf("config not found: %s", ref.ConfigName) + return nil, fmt.Errorf("config not found: %s", ref.ConfigName) } // set the id for the ref to properly assign in swarm @@ -144,7 +144,7 @@ func ParseConfigs(ctx context.Context, apiClient client.ConfigAPIClient, request for _, ref := range runtimeRefs { id, ok := foundConfigs[ref.ConfigName] if !ok { - return nil, errors.Errorf("config not found: %s", ref.ConfigName) + return nil, fmt.Errorf("config not found: %s", ref.ConfigName) } ref.ConfigID = id diff --git a/cli/command/service/ps.go b/cli/command/service/ps.go index 4d24ce1ca84c..09661c903c22 100644 --- a/cli/command/service/ps.go +++ b/cli/command/service/ps.go @@ -2,6 +2,7 @@ package service import ( "context" + "errors" "strings" "github.com/docker/cli/cli" @@ -12,7 +13,6 @@ import ( "github.com/docker/cli/opts" "github.com/moby/moby/api/types/filters" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) diff --git a/cli/command/service/trust.go b/cli/command/service/trust.go index 20377bc24f98..cec9f712a06d 100644 --- a/cli/command/service/trust.go +++ b/cli/command/service/trust.go @@ -2,6 +2,8 @@ package service import ( "encoding/hex" + "errors" + "fmt" "github.com/distribution/reference" "github.com/docker/cli/cli/command" @@ -9,7 +11,6 @@ import ( "github.com/docker/cli/internal/registry" "github.com/moby/moby/api/types/swarm" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/theupdateframework/notary/tuf/data" ) @@ -23,7 +24,7 @@ func resolveServiceImageDigestContentTrust(dockerCli command.Cli, service *swarm ref, err := reference.ParseAnyReference(service.TaskTemplate.ContainerSpec.Image) if err != nil { - return errors.Wrapf(err, "invalid reference %s", service.TaskTemplate.ContainerSpec.Image) + return fmt.Errorf("invalid reference %s: %w", service.TaskTemplate.ContainerSpec.Image, err) } // If reference does not have digest (is not canonical nor image id) @@ -40,7 +41,7 @@ func resolveServiceImageDigestContentTrust(dockerCli command.Cli, service *swarm resolvedImage, err := trustedResolveDigest(dockerCli, taggedRef) if err != nil { - return errors.Wrap(err, "failed to resolve image digest using content trust") + return fmt.Errorf("failed to resolve image digest using content trust: %w", err) } resolvedFamiliar := reference.FamiliarString(resolvedImage) logrus.Debugf("resolved image tag to %s using content trust", resolvedFamiliar) @@ -59,7 +60,7 @@ func trustedResolveDigest(cli command.Cli, ref reference.NamedTagged) (reference } notaryRepo, err := trust.GetNotaryRepository(cli.In(), cli.Out(), command.UserAgent(), repoInfo, &authConfig, "pull") if err != nil { - return nil, errors.Wrap(err, "error establishing connection to trust repository") + return nil, fmt.Errorf("error establishing connection to trust repository: %w", err) } t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole) @@ -69,7 +70,7 @@ func trustedResolveDigest(cli command.Cli, ref reference.NamedTagged) (reference // Only get the tag if it's in the top level targets role or the releases delegation role // ignore it if it's in any other delegation roles if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { - return nil, trust.NotaryError(repoInfo.Name.Name(), errors.Errorf("No trust data for %s", reference.FamiliarString(ref))) + return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("no trust data for %s", reference.FamiliarString(ref))) } logrus.Debugf("retrieving target for %s role", t.Role) diff --git a/cli/command/service/update.go b/cli/command/service/update.go index 9603d1d9982f..e51c037c71b2 100644 --- a/cli/command/service/update.go +++ b/cli/command/service/update.go @@ -2,6 +2,7 @@ package service import ( "context" + "errors" "fmt" "sort" "strings" @@ -18,7 +19,6 @@ import ( "github.com/moby/moby/api/types/versions" "github.com/moby/moby/client" "github.com/moby/swarmkit/v2/api/defaults" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -193,7 +193,7 @@ func runUpdate(ctx context.Context, dockerCLI command.Cli, flags *pflag.FlagSet, clientSideRollback = true spec = service.PreviousSpec if spec == nil { - return errors.Errorf("service does not have a previous specification to roll back to") + return errors.New("service does not have a previous specification to roll back to") } } else { serverSideRollback = true @@ -950,7 +950,7 @@ func updateMounts(flags *pflag.FlagSet, mounts *[]mount.Mount) error { values := flags.Lookup(flagMountAdd).Value.(*opts.MountOpt).Value() for _, mnt := range values { if _, ok := mountsByTarget[mnt.Target]; ok { - return errors.Errorf("duplicate mount target") + return errors.New("duplicate mount target") } mountsByTarget[mnt.Target] = mnt } @@ -1144,7 +1144,7 @@ func updateReplicas(flags *pflag.FlagSet, serviceMode *swarm.ServiceMode) error } if serviceMode == nil || serviceMode.Replicated == nil { - return errors.Errorf("replicas can only be used with replicated mode") + return errors.New("replicas can only be used with replicated mode") } serviceMode.Replicated.Replicas = flags.Lookup(flagReplicas).Value.(*Uint64Opt).Value() return nil @@ -1284,7 +1284,7 @@ func updateHealthcheck(flags *pflag.FlagSet, containerSpec *swarm.ContainerSpec) } return nil } - return errors.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck) + return fmt.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck) } if len(containerSpec.Healthcheck.Test) > 0 && containerSpec.Healthcheck.Test[0] == "NONE" { containerSpec.Healthcheck.Test = nil @@ -1355,7 +1355,7 @@ func updateNetworks(ctx context.Context, apiClient client.NetworkAPIClient, flag return err } if _, exists := existingNetworks[nwID]; exists { - return errors.Errorf("service is already attached to network %s", nw.Target) + return fmt.Errorf("service is already attached to network %s", nw.Target) } nw.Target = nwID newNetworks = append(newNetworks, nw) diff --git a/cli/command/stack/config_test.go b/cli/command/stack/config_test.go index f745ec23c25f..b4243567e709 100644 --- a/cli/command/stack/config_test.go +++ b/cli/command/stack/config_test.go @@ -15,7 +15,7 @@ func TestConfigWithEmptyComposeFile(t *testing.T) { cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) - assert.ErrorContains(t, cmd.Execute(), `Specify a Compose file`) + assert.ErrorContains(t, cmd.Execute(), `specify a Compose file`) } func TestConfigMergeInterpolation(t *testing.T) { diff --git a/cli/command/stack/deploy.go b/cli/command/stack/deploy.go index 72d6b13dc93d..c7f699b15d48 100644 --- a/cli/command/stack/deploy.go +++ b/cli/command/stack/deploy.go @@ -2,6 +2,7 @@ package stack import ( "context" + "errors" "fmt" "github.com/docker/cli/cli" @@ -10,7 +11,6 @@ import ( composetypes "github.com/docker/cli/cli/compose/types" "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/api/types/versions" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -80,7 +80,7 @@ func runDeploy(ctx context.Context, dockerCLI command.Cli, flags *pflag.FlagSet, case resolveImageAlways, resolveImageChanged, resolveImageNever: // valid options. default: - return errors.Errorf("Invalid option %s for flag --resolve-image", opts.resolveImage) + return fmt.Errorf("invalid option %s for flag --resolve-image", opts.resolveImage) } // client side image resolution should not be done when the supported @@ -108,7 +108,7 @@ func checkDaemonIsSwarmManager(ctx context.Context, dockerCli command.Cli) error return err } if !info.Swarm.ControlAvailable { - return errors.New("this node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again") + return errors.New(`this node is not a swarm manager. Use "docker swarm init" or "docker swarm join" to connect this node to swarm and try again`) } return nil } diff --git a/cli/command/stack/list_utils.go b/cli/command/stack/list_utils.go index b085642eadce..2daafab6a7fb 100644 --- a/cli/command/stack/list_utils.go +++ b/cli/command/stack/list_utils.go @@ -2,10 +2,10 @@ package stack import ( "context" + "errors" "github.com/docker/cli/cli/compose/convert" "github.com/moby/moby/client" - "github.com/pkg/errors" ) // getStacks lists the swarm stacks with the number of services they contain. diff --git a/cli/command/stack/loader.go b/cli/command/stack/loader.go index 8ff33f1606a0..fb86685acda9 100644 --- a/cli/command/stack/loader.go +++ b/cli/command/stack/loader.go @@ -4,6 +4,7 @@ package stack import ( + "errors" "fmt" "io" "os" @@ -17,7 +18,6 @@ import ( "github.com/docker/cli/cli/compose/loader" "github.com/docker/cli/cli/compose/schema" composetypes "github.com/docker/cli/cli/compose/types" - "github.com/pkg/errors" ) // loadComposeFile parse the composefile specified in the cli and returns its configOptions and version. @@ -30,9 +30,10 @@ func loadComposeFile(streams command.Streams, opts deployOptions) (*composetypes dicts := getDictsFrom(configDetails.ConfigFiles) config, err := loader.Load(configDetails) if err != nil { - if fpe, ok := err.(*loader.ForbiddenPropertiesError); ok { + var fpe *loader.ForbiddenPropertiesError + if errors.As(err, &fpe) { // this error is intentionally formatted multi-line - return nil, errors.Errorf("Compose file contains unsupported options:\n\n%s\n", propertyWarnings(fpe.Properties)) + return nil, fmt.Errorf("compose file contains unsupported options:\n\n%s\n", propertyWarnings(fpe.Properties)) //nolint:staticcheck // ignore ST1005 } return nil, err @@ -53,10 +54,10 @@ func loadComposeFile(streams command.Streams, opts deployOptions) (*composetypes // Validate if each service has a valid image-reference. for _, svc := range config.Services { if svc.Image == "" { - return nil, errors.Errorf("invalid image reference for service %s: no image specified", svc.Name) + return nil, fmt.Errorf("invalid image reference for service %s: no image specified", svc.Name) } if _, err := reference.ParseAnyReference(svc.Image); err != nil { - return nil, errors.Wrapf(err, "invalid image reference for service %s", svc.Name) + return nil, fmt.Errorf("invalid image reference for service %s: %w", svc.Name, err) } } @@ -87,7 +88,7 @@ func getConfigDetails(composefiles []string, stdin io.Reader) (composetypes.Conf var details composetypes.ConfigDetails if len(composefiles) == 0 { - return details, errors.New("Specify a Compose file (with --compose-file)") + return details, errors.New("specify a Compose file (with --compose-file)") } if composefiles[0] == "-" && len(composefiles) == 1 { @@ -133,7 +134,7 @@ func buildEnvironment(env []string) (map[string]string, error) { k, v, ok := strings.Cut(s, "=") if !ok || k == "" { - return result, errors.Errorf("unexpected environment variable '%s'", s) + return result, fmt.Errorf("unexpected environment variable '%s'", s) } // value may be set, but empty if "s" is like "K=", not "K". result[k] = v diff --git a/cli/command/swarm/ca.go b/cli/command/swarm/ca.go index 524b488ef3e5..2b20b12a400a 100644 --- a/cli/command/swarm/ca.go +++ b/cli/command/swarm/ca.go @@ -2,6 +2,7 @@ package swarm import ( "context" + "errors" "fmt" "io" "strings" @@ -12,7 +13,6 @@ import ( "github.com/docker/cli/internal/jsonstream" "github.com/moby/moby/api/types/swarm" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -138,7 +138,7 @@ func attach(ctx context.Context, dockerCLI command.Cli, opts caOptions) error { func displayTrustRoot(out io.Writer, info swarm.Swarm) error { if info.ClusterInfo.TLSInfo.TrustRoot == "" { - return errors.New("No CA information available") + return errors.New("no CA information available") } _, _ = fmt.Fprintln(out, strings.TrimSpace(info.ClusterInfo.TLSInfo.TrustRoot)) return nil diff --git a/cli/command/swarm/ca_test.go b/cli/command/swarm/ca_test.go index 127f60e11fa5..c6a84c5041bc 100644 --- a/cli/command/swarm/ca_test.go +++ b/cli/command/swarm/ca_test.go @@ -57,7 +57,7 @@ func swarmSpecWithFullCAConfig() *swarm.Spec { func TestDisplayTrustRootNoRoot(t *testing.T) { buffer := new(bytes.Buffer) err := displayTrustRoot(buffer, swarm.Swarm{}) - assert.Error(t, err, "No CA information available") + assert.Error(t, err, "no CA information available") } type invalidCATestCases struct { diff --git a/cli/command/swarm/init.go b/cli/command/swarm/init.go index 9ac8ed1d401f..b19b1beb27c9 100644 --- a/cli/command/swarm/init.go +++ b/cli/command/swarm/init.go @@ -9,7 +9,6 @@ import ( "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/moby/moby/api/types/swarm" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -89,14 +88,14 @@ func runInit(ctx context.Context, dockerCLI command.Cli, flags *pflag.FlagSet, o case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain: req.Availability = availability default: - return errors.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability) + return fmt.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability) } } nodeID, err := apiClient.SwarmInit(ctx, req) if err != nil { if strings.Contains(err.Error(), "could not choose an IP address to advertise") || strings.Contains(err.Error(), "could not find the system's IP address") { - return errors.New(err.Error() + " - specify one with --advertise-addr") + return fmt.Errorf("%w - specify one with --advertise-addr", err) } return err } @@ -112,7 +111,7 @@ func runInit(ctx context.Context, dockerCLI command.Cli, flags *pflag.FlagSet, o if req.AutoLockManagers { unlockKeyResp, err := apiClient.SwarmGetUnlockKey(ctx) if err != nil { - return errors.Wrap(err, "could not fetch unlock key") + return fmt.Errorf("could not fetch unlock key: %w", err) } printUnlockCommand(dockerCLI.Out(), unlockKeyResp.UnlockKey) } diff --git a/cli/command/swarm/join.go b/cli/command/swarm/join.go index bc0a4722102e..1f4c2896e451 100644 --- a/cli/command/swarm/join.go +++ b/cli/command/swarm/join.go @@ -8,7 +8,6 @@ import ( "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/moby/moby/api/types/swarm" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -69,7 +68,7 @@ func runJoin(ctx context.Context, dockerCLI command.Cli, flags *pflag.FlagSet, o case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain: req.Availability = availability default: - return errors.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability) + return fmt.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability) } } diff --git a/cli/command/swarm/join_token.go b/cli/command/swarm/join_token.go index f2ebee4b71f1..d0efdca6b229 100644 --- a/cli/command/swarm/join_token.go +++ b/cli/command/swarm/join_token.go @@ -2,12 +2,12 @@ package swarm import ( "context" + "errors" "fmt" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) diff --git a/cli/command/swarm/opts.go b/cli/command/swarm/opts.go index 3e3081ab36e7..57429ffb0904 100644 --- a/cli/command/swarm/opts.go +++ b/cli/command/swarm/opts.go @@ -3,6 +3,7 @@ package swarm import ( "encoding/csv" "encoding/pem" + "errors" "fmt" "os" "strings" @@ -10,7 +11,6 @@ import ( "github.com/docker/cli/opts" "github.com/moby/moby/api/types/swarm" - "github.com/pkg/errors" "github.com/spf13/pflag" ) @@ -177,7 +177,7 @@ func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) { for _, field := range fields { key, value, ok := strings.Cut(field, "=") if !ok { - return nil, errors.Errorf("invalid field '%s' must be a key=value pair", field) + return nil, fmt.Errorf("invalid field '%s' must be a key=value pair", field) } // TODO(thaJeztah): these options should not be case-insensitive. @@ -187,7 +187,7 @@ func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) { if strings.ToLower(value) == string(swarm.ExternalCAProtocolCFSSL) { externalCA.Protocol = swarm.ExternalCAProtocolCFSSL } else { - return nil, errors.Errorf("unrecognized external CA protocol %s", value) + return nil, fmt.Errorf("unrecognized external CA protocol %s", value) } case "url": hasURL = true @@ -195,7 +195,7 @@ func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) { case "cacert": cacontents, err := os.ReadFile(value) if err != nil { - return nil, errors.Wrap(err, "unable to read CA cert for external CA") + return nil, fmt.Errorf("unable to read CA cert for external CA: %w", err) } if pemBlock, _ := pem.Decode(cacontents); pemBlock == nil { return nil, errors.New("CA cert for external CA must be in PEM format") diff --git a/cli/command/swarm/unlock.go b/cli/command/swarm/unlock.go index ad416edfc029..2007f7873f2f 100644 --- a/cli/command/swarm/unlock.go +++ b/cli/command/swarm/unlock.go @@ -3,6 +3,7 @@ package swarm import ( "bufio" "context" + "errors" "fmt" "io" "strings" @@ -11,7 +12,6 @@ import ( "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/streams" "github.com/moby/moby/api/types/swarm" - "github.com/pkg/errors" "github.com/spf13/cobra" "golang.org/x/term" ) @@ -47,11 +47,11 @@ func runUnlock(ctx context.Context, dockerCLI command.Cli) error { switch info.Swarm.LocalNodeState { case swarm.LocalNodeStateInactive: - return errors.New("Error: This node is not part of a swarm") + return errors.New("error: this node is not part of a swarm") case swarm.LocalNodeStateLocked: break case swarm.LocalNodeStatePending, swarm.LocalNodeStateActive, swarm.LocalNodeStateError: - return errors.New("Error: swarm is not locked") + return errors.New("error: swarm is not locked") } key, err := readKey(dockerCLI.In(), "Enter unlock key: ") diff --git a/cli/command/swarm/unlock_key.go b/cli/command/swarm/unlock_key.go index d13d3c1ef30c..7b0fc5ad552c 100644 --- a/cli/command/swarm/unlock_key.go +++ b/cli/command/swarm/unlock_key.go @@ -2,13 +2,13 @@ package swarm import ( "context" + "errors" "fmt" "io" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -68,7 +68,7 @@ func runUnlockKey(ctx context.Context, dockerCLI command.Cli, opts unlockKeyOpti unlockKeyResp, err := apiClient.SwarmGetUnlockKey(ctx) if err != nil { - return errors.Wrap(err, "could not fetch unlock key") + return fmt.Errorf("could not fetch unlock key: %w", err) } if unlockKeyResp.UnlockKey == "" { diff --git a/cli/command/swarm/unlock_test.go b/cli/command/swarm/unlock_test.go index 5a06a6ee1cb9..f79290877e98 100644 --- a/cli/command/swarm/unlock_test.go +++ b/cli/command/swarm/unlock_test.go @@ -35,7 +35,7 @@ func TestSwarmUnlockErrors(t *testing.T) { }, }, nil }, - expectedError: "This node is not part of a swarm", + expectedError: "this node is not part of a swarm", }, { name: "is-not-locked", @@ -46,7 +46,7 @@ func TestSwarmUnlockErrors(t *testing.T) { }, }, nil }, - expectedError: "Error: swarm is not locked", + expectedError: "error: swarm is not locked", }, { name: "unlockrequest-failed", diff --git a/cli/command/swarm/update.go b/cli/command/swarm/update.go index cc5414f1a75b..3f4878f0d9aa 100644 --- a/cli/command/swarm/update.go +++ b/cli/command/swarm/update.go @@ -7,7 +7,6 @@ import ( "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -65,7 +64,7 @@ func runUpdate(ctx context.Context, dockerCLI command.Cli, flags *pflag.FlagSet, if curAutoLock && !prevAutoLock { unlockKeyResp, err := apiClient.SwarmGetUnlockKey(ctx) if err != nil { - return errors.Wrap(err, "could not fetch unlock key") + return fmt.Errorf("could not fetch unlock key: %w", err) } printUnlockCommand(dockerCLI.Out(), unlockKeyResp.UnlockKey) } diff --git a/cli/command/system/dial_stdio.go b/cli/command/system/dial_stdio.go index 13596acd62bf..62206af0edd8 100644 --- a/cli/command/system/dial_stdio.go +++ b/cli/command/system/dial_stdio.go @@ -2,12 +2,13 @@ package system import ( "context" + "errors" + "fmt" "io" "os" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" - "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -35,7 +36,7 @@ func runDialStdio(ctx context.Context, dockerCli command.Cli) error { dialer := dockerCli.Client().Dialer() conn, err := dialer(ctx) if err != nil { - return errors.Wrap(err, "failed to open the raw stream connection") + return fmt.Errorf("failed to open the raw stream connection: %w", err) } defer conn.Close() @@ -81,7 +82,7 @@ func copier(to halfWriteCloser, from halfReadCloser, debugDescription string) er } }() if _, err := io.Copy(to, from); err != nil { - return errors.Wrapf(err, "error while Copy (%s)", debugDescription) + return fmt.Errorf("error while Copy (%s): %w", debugDescription, err) } return nil } diff --git a/cli/command/system/inspect.go b/cli/command/system/inspect.go index f248314bc851..67177478875c 100644 --- a/cli/command/system/inspect.go +++ b/cli/command/system/inspect.go @@ -17,7 +17,6 @@ import ( flagsHelper "github.com/docker/cli/cli/flags" "github.com/moby/moby/api/types/image" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -99,7 +98,7 @@ func runInspect(ctx context.Context, dockerCli command.Cli, opts inspectOptions) typePlugin, typeSecret, typeService, typeTask, typeVolume: elementSearcher = inspectAll(ctx, dockerCli, opts.size, opts.objectType) default: - return errors.Errorf(`unknown type: %q: must be one of "%s"`, opts.objectType, strings.Join(allTypes, `", "`)) + return fmt.Errorf(`unknown type: %q: must be one of "%s"`, opts.objectType, strings.Join(allTypes, `", "`)) } return inspect.Inspect(dockerCli.Out(), opts.ids, opts.format, elementSearcher) } @@ -273,7 +272,7 @@ func inspectAll(ctx context.Context, dockerCLI command.Cli, getSize bool, typeCo } return v, raw, err } - return nil, nil, errors.Errorf("Error: No such object: %s", ref) + return nil, nil, fmt.Errorf("error: no such object: %s", ref) } } diff --git a/cli/command/system/version.go b/cli/command/system/version.go index 309bda941ef5..5f5937c59a31 100644 --- a/cli/command/system/version.go +++ b/cli/command/system/version.go @@ -2,6 +2,7 @@ package system import ( "context" + "fmt" "io" "runtime" "sort" @@ -18,7 +19,6 @@ import ( "github.com/docker/cli/templates" "github.com/moby/moby/api/types" "github.com/moby/moby/client" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/tonistiigi/go-rosetta" ) @@ -212,7 +212,7 @@ func newVersionTemplate(templateFormat string) (*template.Template, error) { } tmpl, err := templates.New("version").Funcs(template.FuncMap{"getDetailsOrder": getDetailsOrder}).Parse(templateFormat) if err != nil { - return nil, errors.Wrap(err, "template parsing error") + return nil, fmt.Errorf("template parsing error: %w", err) } return tmpl, nil } diff --git a/e2e/system/inspect_test.go b/e2e/system/inspect_test.go index 77fee311512a..7ab9b4b995e0 100644 --- a/e2e/system/inspect_test.go +++ b/e2e/system/inspect_test.go @@ -12,7 +12,7 @@ func TestInspectInvalidReference(t *testing.T) { result := icmd.RunCmd(icmd.Command("docker", "inspect", "FooBar")) result.Assert(t, icmd.Expected{ Out: "[]", - Err: "Error: No such object: FooBar", + Err: "error: no such object: FooBar", ExitCode: 1, }) } diff --git a/vendor.mod b/vendor.mod index f6c27ef8425d..eb596fb82024 100644 --- a/vendor.mod +++ b/vendor.mod @@ -42,7 +42,6 @@ require ( github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.1.1 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c - github.com/pkg/errors v0.9.1 github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.10.1 github.com/spf13/pflag v1.0.10 diff --git a/vendor.sum b/vendor.sum index 571f18e5de55..eaa84b73e332 100644 --- a/vendor.sum +++ b/vendor.sum @@ -218,7 +218,6 @@ github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFSt github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1b347..000000000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 9159de03e03d..000000000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.11.x - - 1.12.x - - 1.13.x - - tip - -script: - - make check diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e755ce..000000000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/Makefile b/vendor/github.com/pkg/errors/Makefile deleted file mode 100644 index ce9d7cded649..000000000000 --- a/vendor/github.com/pkg/errors/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -PKGS := github.com/pkg/errors -SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) -GO := go - -check: test vet gofmt misspell unconvert staticcheck ineffassign unparam - -test: - $(GO) test $(PKGS) - -vet: | test - $(GO) vet $(PKGS) - -staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck - staticcheck -checks all $(PKGS) - -misspell: - $(GO) get github.com/client9/misspell/cmd/misspell - misspell \ - -locale GB \ - -error \ - *.md *.go - -unconvert: - $(GO) get github.com/mdempsky/unconvert - unconvert -v $(PKGS) - -ineffassign: - $(GO) get github.com/gordonklaus/ineffassign - find $(SRCDIRS) -name '*.go' | xargs ineffassign - -pedantic: check errcheck - -unparam: - $(GO) get mvdan.cc/unparam - unparam ./... - -errcheck: - $(GO) get github.com/kisielk/errcheck - errcheck $(PKGS) - -gofmt: - @echo Checking code is gofmted - @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 54dfdcb12ea1..000000000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Roadmap - -With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: - -- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) -- 1.0. Final release. - -## Contributing - -Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. - -Before sending a PR, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0240..000000000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 161aea258296..000000000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,288 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which when applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// together with the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required, the errors.WithStack and -// errors.WithMessage functions destructure errors.Wrap into its component -// operations: annotating an error with a stack trace and with a message, -// respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error that does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// Although the causer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported: -// -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface: -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// The returned errors.StackTrace type is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d\n", f, f) -// } -// } -// -// Although the stackTracer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withStack) Unwrap() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -// WithMessagef annotates err with the format specifier. -// If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withMessage) Unwrap() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go deleted file mode 100644 index be0d10d0c793..000000000000 --- a/vendor/github.com/pkg/errors/go113.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.13 - -package errors - -import ( - stderrors "errors" -) - -// Is reports whether any error in err's chain matches target. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error is considered to match a target if it is equal to that target or if -// it implements a method Is(error) bool such that Is(target) returns true. -func Is(err, target error) bool { return stderrors.Is(err, target) } - -// As finds the first error in err's chain that matches target, and if so, sets -// target to that error value and returns true. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that -// As(target) returns true. In the latter case, the As method is responsible for -// setting target. -// -// As will panic if target is not a non-nil pointer to either a type that implements -// error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } - -// Unwrap returns the result of calling the Unwrap method on err, if err's -// type contains an Unwrap method returning error. -// Otherwise, Unwrap returns nil. -func Unwrap(err error) error { - return stderrors.Unwrap(err) -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 779a8348fb9c..000000000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,177 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strconv" - "strings" -) - -// Frame represents a program counter inside a stack frame. -// For historical reasons if Frame is interpreted as a uintptr -// its value represents the program counter + 1. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// name returns the name of this function, if known. -func (f Frame) name() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - return fn.Name() -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - io.WriteString(s, f.name()) - io.WriteString(s, "\n\t") - io.WriteString(s, f.file()) - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - io.WriteString(s, strconv.Itoa(f.line())) - case 'n': - io.WriteString(s, funcname(f.name())) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// MarshalText formats a stacktrace Frame as a text string. The output is the -// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. -func (f Frame) MarshalText() ([]byte, error) { - name := f.name() - if name == "unknown" { - return []byte(name), nil - } - return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - io.WriteString(s, "\n") - f.Format(s, verb) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - st.formatSlice(s, verb) - } - case 's': - st.formatSlice(s, verb) - } -} - -// formatSlice will format this StackTrace into the given buffer as a slice of -// Frame, only valid when called with '%s' or '%v'. -func (st StackTrace) formatSlice(s fmt.State, verb rune) { - io.WriteString(s, "[") - for i, f := range st { - if i > 0 { - io.WriteString(s, " ") - } - f.Format(s, verb) - } - io.WriteString(s, "]") -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/vendor/modules.txt b/vendor/modules.txt index e9d47e5afc65..3d8283e6e6a7 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -254,9 +254,6 @@ github.com/opencontainers/image-spec/specs-go/v1 # github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c ## explicit; go 1.14 github.com/pkg/browser -# github.com/pkg/errors v0.9.1 -## explicit -github.com/pkg/errors # github.com/prometheus/client_golang v1.22.0 ## explicit; go 1.22 github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil