Replace fmt.Errorf() with errors.Errorf() in the cli

Signed-off-by: Daniel Nephin <dnephin@docker.com>
This commit is contained in:
Daniel Nephin 2017-03-09 13:23:45 -05:00
parent c1b2fad9aa
commit e9d6193dfd
99 changed files with 370 additions and 337 deletions

View File

@ -5,6 +5,7 @@ import (
"strings" "strings"
"github.com/docker/docker/pkg/term" "github.com/docker/docker/pkg/term"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -51,7 +52,7 @@ var helpCommand = &cobra.Command{
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
cmd, args, e := c.Root().Find(args) cmd, args, e := c.Root().Find(args)
if cmd == nil || e != nil || len(args) > 0 { if cmd == nil || e != nil || len(args) > 0 {
return fmt.Errorf("unknown help topic: %v", strings.Join(args, " ")) return errors.Errorf("unknown help topic: %v", strings.Join(args, " "))
} }
helpFunc := cmd.HelpFunc() helpFunc := cmd.HelpFunc()

View File

@ -2,8 +2,9 @@ package bundlefile
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"github.com/pkg/errors"
) )
// Bundlefile stores the contents of a bundlefile // Bundlefile stores the contents of a bundlefile
@ -39,12 +40,12 @@ func LoadFile(reader io.Reader) (*Bundlefile, error) {
if err := decoder.Decode(bundlefile); err != nil { if err := decoder.Decode(bundlefile); err != nil {
switch jsonErr := err.(type) { switch jsonErr := err.(type) {
case *json.SyntaxError: case *json.SyntaxError:
return nil, fmt.Errorf( return nil, errors.Errorf(
"JSON syntax error at byte %v: %s", "JSON syntax error at byte %v: %s",
jsonErr.Offset, jsonErr.Offset,
jsonErr.Error()) jsonErr.Error())
case *json.UnmarshalTypeError: case *json.UnmarshalTypeError:
return nil, fmt.Errorf( return nil, errors.Errorf(
"Unexpected type at byte %v. Expected %s but received %s.", "Unexpected type at byte %v. Expected %s but received %s.",
jsonErr.Offset, jsonErr.Offset,
jsonErr.Type, jsonErr.Type,

View File

@ -1,8 +1,8 @@
package command package command
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"io" "io"
"net/http" "net/http"
"os" "os"

View File

@ -1,7 +1,7 @@
package container package container
import ( import (
"errors" "github.com/pkg/errors"
"io" "io"
"net/http/httputil" "net/http/httputil"

View File

@ -1,8 +1,6 @@
package container package container
import ( import (
"errors"
"fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -13,6 +11,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/system"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -227,7 +226,7 @@ func copyToContainer(ctx context.Context, dockerCli *command.DockerCli, srcPath,
content = os.Stdin content = os.Stdin
resolvedDstPath = dstInfo.Path resolvedDstPath = dstInfo.Path
if !dstInfo.IsDir { if !dstInfo.IsDir {
return fmt.Errorf("destination \"%s:%s\" must be a directory", dstContainer, dstPath) return errors.Errorf("destination \"%s:%s\" must be a directory", dstContainer, dstPath)
} }
} else { } else {
// Prepare source copy info. // Prepare source copy info.

View File

@ -14,6 +14,7 @@ import (
apiclient "github.com/docker/docker/client" apiclient "github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -118,7 +119,7 @@ func (cid *cidFile) Close() error {
return nil return nil
} }
if err := os.Remove(cid.path); err != nil { if err := os.Remove(cid.path); err != nil {
return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err) return errors.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
} }
return nil return nil
@ -126,7 +127,7 @@ func (cid *cidFile) Close() error {
func (cid *cidFile) Write(id string) error { func (cid *cidFile) Write(id string) error {
if _, err := cid.file.Write([]byte(id)); err != nil { if _, err := cid.file.Write([]byte(id)); err != nil {
return fmt.Errorf("Failed to write the container ID to the file: %s", err) return errors.Errorf("Failed to write the container ID to the file: %s", err)
} }
cid.written = true cid.written = true
return nil return nil
@ -134,12 +135,12 @@ func (cid *cidFile) Write(id string) error {
func newCIDFile(path string) (*cidFile, error) { func newCIDFile(path string) (*cidFile, error) {
if _, err := os.Stat(path); err == nil { if _, err := os.Stat(path); err == nil {
return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path) return nil, errors.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
} }
f, err := os.Create(path) f, err := os.Create(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to create the container ID file: %s", err) return nil, errors.Errorf("Failed to create the container ID file: %s", err)
} }
return &cidFile{path: path, file: f}, nil return &cidFile{path: path, file: f}, nil

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"

View File

@ -1,7 +1,7 @@
package container package container
import ( import (
"errors" "github.com/pkg/errors"
"io" "io"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"

View File

@ -18,6 +18,7 @@ import (
"github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/signal"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/pkg/errors"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -304,7 +305,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
// Validate the input mac address // Validate the input mac address
if copts.macAddress != "" { if copts.macAddress != "" {
if _, err := opts.ValidateMACAddress(copts.macAddress); err != nil { if _, err := opts.ValidateMACAddress(copts.macAddress); err != nil {
return nil, fmt.Errorf("%s is not a valid mac address", copts.macAddress) return nil, errors.Errorf("%s is not a valid mac address", copts.macAddress)
} }
} }
if copts.stdin { if copts.stdin {
@ -320,7 +321,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
swappiness := copts.swappiness swappiness := copts.swappiness
if swappiness != -1 && (swappiness < 0 || swappiness > 100) { if swappiness != -1 && (swappiness < 0 || swappiness > 100) {
return nil, fmt.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness) return nil, errors.Errorf("invalid value: %d. Valid memory swappiness range is 0-100", swappiness)
} }
var binds []string var binds []string
@ -371,7 +372,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
// Merge in exposed ports to the map of published ports // Merge in exposed ports to the map of published ports
for _, e := range copts.expose.GetAll() { for _, e := range copts.expose.GetAll() {
if strings.Contains(e, ":") { if strings.Contains(e, ":") {
return nil, fmt.Errorf("invalid port format for --expose: %s", e) return nil, errors.Errorf("invalid port format for --expose: %s", e)
} }
//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>] //support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
proto, port := nat.SplitProtoPort(e) proto, port := nat.SplitProtoPort(e)
@ -379,7 +380,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
//if expose a port, the start and end port are the same //if expose a port, the start and end port are the same
start, end, err := nat.ParsePortRange(port) start, end, err := nat.ParsePortRange(port)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid range format for --expose: %s, error: %s", e, err) return nil, errors.Errorf("invalid range format for --expose: %s, error: %s", e, err)
} }
for i := start; i <= end; i++ { for i := start; i <= end; i++ {
p, err := nat.NewPort(proto, strconv.FormatUint(i, 10)) p, err := nat.NewPort(proto, strconv.FormatUint(i, 10))
@ -416,22 +417,22 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
ipcMode := container.IpcMode(copts.ipcMode) ipcMode := container.IpcMode(copts.ipcMode)
if !ipcMode.Valid() { if !ipcMode.Valid() {
return nil, fmt.Errorf("--ipc: invalid IPC mode") return nil, errors.Errorf("--ipc: invalid IPC mode")
} }
pidMode := container.PidMode(copts.pidMode) pidMode := container.PidMode(copts.pidMode)
if !pidMode.Valid() { if !pidMode.Valid() {
return nil, fmt.Errorf("--pid: invalid PID mode") return nil, errors.Errorf("--pid: invalid PID mode")
} }
utsMode := container.UTSMode(copts.utsMode) utsMode := container.UTSMode(copts.utsMode)
if !utsMode.Valid() { if !utsMode.Valid() {
return nil, fmt.Errorf("--uts: invalid UTS mode") return nil, errors.Errorf("--uts: invalid UTS mode")
} }
usernsMode := container.UsernsMode(copts.usernsMode) usernsMode := container.UsernsMode(copts.usernsMode)
if !usernsMode.Valid() { if !usernsMode.Valid() {
return nil, fmt.Errorf("--userns: invalid USER mode") return nil, errors.Errorf("--userns: invalid USER mode")
} }
restartPolicy, err := runconfigopts.ParseRestartPolicy(copts.restartPolicy) restartPolicy, err := runconfigopts.ParseRestartPolicy(copts.restartPolicy)
@ -462,7 +463,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
copts.healthRetries != 0 copts.healthRetries != 0
if copts.noHealthcheck { if copts.noHealthcheck {
if haveHealthSettings { if haveHealthSettings {
return nil, fmt.Errorf("--no-healthcheck conflicts with --health-* options") return nil, errors.Errorf("--no-healthcheck conflicts with --health-* options")
} }
test := strslice.StrSlice{"NONE"} test := strslice.StrSlice{"NONE"}
healthConfig = &container.HealthConfig{Test: test} healthConfig = &container.HealthConfig{Test: test}
@ -473,13 +474,13 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
probe = strslice.StrSlice(args) probe = strslice.StrSlice(args)
} }
if copts.healthInterval < 0 { if copts.healthInterval < 0 {
return nil, fmt.Errorf("--health-interval cannot be negative") return nil, errors.Errorf("--health-interval cannot be negative")
} }
if copts.healthTimeout < 0 { if copts.healthTimeout < 0 {
return nil, fmt.Errorf("--health-timeout cannot be negative") return nil, errors.Errorf("--health-timeout cannot be negative")
} }
if copts.healthRetries < 0 { if copts.healthRetries < 0 {
return nil, fmt.Errorf("--health-retries cannot be negative") return nil, errors.Errorf("--health-retries cannot be negative")
} }
healthConfig = &container.HealthConfig{ healthConfig = &container.HealthConfig{
@ -594,7 +595,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
} }
if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() { if copts.autoRemove && !hostConfig.RestartPolicy.IsNone() {
return nil, fmt.Errorf("Conflicting options: --restart and --rm") return nil, errors.Errorf("Conflicting options: --restart and --rm")
} }
// only set this value if the user provided the flag, else it should default to nil // only set this value if the user provided the flag, else it should default to nil
@ -656,7 +657,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions) (*containerConfig, err
func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) { func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) {
loggingOptsMap := runconfigopts.ConvertKVStringsToMap(loggingOpts) loggingOptsMap := runconfigopts.ConvertKVStringsToMap(loggingOpts)
if loggingDriver == "none" && len(loggingOpts) > 0 { if loggingDriver == "none" && len(loggingOpts) > 0 {
return map[string]string{}, fmt.Errorf("invalid logging opts for driver %s", loggingDriver) return map[string]string{}, errors.Errorf("invalid logging opts for driver %s", loggingDriver)
} }
return loggingOptsMap, nil return loggingOptsMap, nil
} }
@ -669,17 +670,17 @@ func parseSecurityOpts(securityOpts []string) ([]string, error) {
if strings.Contains(opt, ":") { if strings.Contains(opt, ":") {
con = strings.SplitN(opt, ":", 2) con = strings.SplitN(opt, ":", 2)
} else { } else {
return securityOpts, fmt.Errorf("Invalid --security-opt: %q", opt) return securityOpts, errors.Errorf("Invalid --security-opt: %q", opt)
} }
} }
if con[0] == "seccomp" && con[1] != "unconfined" { if con[0] == "seccomp" && con[1] != "unconfined" {
f, err := ioutil.ReadFile(con[1]) f, err := ioutil.ReadFile(con[1])
if err != nil { if err != nil {
return securityOpts, fmt.Errorf("opening seccomp profile (%s) failed: %v", con[1], err) return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
} }
b := bytes.NewBuffer(nil) b := bytes.NewBuffer(nil)
if err := json.Compact(b, f); err != nil { if err := json.Compact(b, f); err != nil {
return securityOpts, fmt.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err) return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err)
} }
securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes()) securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes())
} }
@ -696,7 +697,7 @@ func parseStorageOpts(storageOpts []string) (map[string]string, error) {
opt := strings.SplitN(option, "=", 2) opt := strings.SplitN(option, "=", 2)
m[opt[0]] = opt[1] m[opt[0]] = opt[1]
} else { } else {
return nil, fmt.Errorf("invalid storage option") return nil, errors.Errorf("invalid storage option")
} }
} }
return m, nil return m, nil
@ -722,7 +723,7 @@ func parseDevice(device string) (container.DeviceMapping, error) {
case 1: case 1:
src = arr[0] src = arr[0]
default: default:
return container.DeviceMapping{}, fmt.Errorf("invalid device specification: %s", device) return container.DeviceMapping{}, errors.Errorf("invalid device specification: %s", device)
} }
if dst == "" { if dst == "" {
@ -745,7 +746,7 @@ func validateDeviceCgroupRule(val string) (string, error) {
return val, nil return val, nil
} }
return val, fmt.Errorf("invalid device cgroup format '%s'", val) return val, errors.Errorf("invalid device cgroup format '%s'", val)
} }
// validDeviceMode checks if the mode for device is valid or not. // validDeviceMode checks if the mode for device is valid or not.
@ -781,12 +782,12 @@ func validatePath(val string, validator func(string) bool) (string, error) {
var mode string var mode string
if strings.Count(val, ":") > 2 { if strings.Count(val, ":") > 2 {
return val, fmt.Errorf("bad format for path: %s", val) return val, errors.Errorf("bad format for path: %s", val)
} }
split := strings.SplitN(val, ":", 3) split := strings.SplitN(val, ":", 3)
if split[0] == "" { if split[0] == "" {
return val, fmt.Errorf("bad format for path: %s", val) return val, errors.Errorf("bad format for path: %s", val)
} }
switch len(split) { switch len(split) {
case 1: case 1:
@ -805,13 +806,13 @@ func validatePath(val string, validator func(string) bool) (string, error) {
containerPath = split[1] containerPath = split[1]
mode = split[2] mode = split[2]
if isValid := validator(split[2]); !isValid { if isValid := validator(split[2]); !isValid {
return val, fmt.Errorf("bad mode specified: %s", mode) return val, errors.Errorf("bad mode specified: %s", mode)
} }
val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode) val = fmt.Sprintf("%s:%s:%s", split[0], containerPath, mode)
} }
if !path.IsAbs(containerPath) { if !path.IsAbs(containerPath) {
return val, fmt.Errorf("%s is not an absolute path", containerPath) return val, errors.Errorf("%s is not an absolute path", containerPath)
} }
return val, nil return val, nil
} }
@ -885,5 +886,5 @@ func validateAttach(val string) (string, error) {
return s, nil return s, nil
} }
} }
return val, fmt.Errorf("valid streams are STDIN, STDOUT and STDERR") return val, errors.Errorf("valid streams are STDIN, STDOUT and STDERR")
} }

View File

@ -16,6 +16,7 @@ import (
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/docker/docker/runconfig" "github.com/docker/docker/runconfig"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/pkg/errors"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -224,7 +225,7 @@ func compareRandomizedStrings(a, b, c, d string) error {
if a == d && b == c { if a == d && b == c {
return nil return nil
} }
return fmt.Errorf("strings don't match") return errors.Errorf("strings don't match")
} }
// Simple parse with MacAddress validation // Simple parse with MacAddress validation
@ -751,14 +752,14 @@ func callDecodeContainerConfig(volumes []string, binds []string) (*container.Con
w.Config.Volumes[v] = struct{}{} w.Config.Volumes[v] = struct{}{}
} }
if b, err = json.Marshal(w); err != nil { if b, err = json.Marshal(w); err != nil {
return nil, nil, fmt.Errorf("Error on marshal %s", err.Error()) return nil, nil, errors.Errorf("Error on marshal %s", err.Error())
} }
c, h, _, err = runconfig.DecodeContainerConfig(bytes.NewReader(b)) c, h, _, err = runconfig.DecodeContainerConfig(bytes.NewReader(b))
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("Error parsing %s: %v", string(b), err) return nil, nil, errors.Errorf("Error parsing %s: %v", string(b), err)
} }
if c == nil || h == nil { if c == nil || h == nil {
return nil, nil, fmt.Errorf("Empty config or hostconfig") return nil, nil, errors.Errorf("Empty config or hostconfig")
} }
return c, h, err return c, h, err

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"

View File

@ -7,6 +7,7 @@ import (
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -64,7 +65,7 @@ func runPort(dockerCli *command.DockerCli, opts *portOptions) error {
} }
return nil return nil
} }
return fmt.Errorf("Error: No public port '%s' published for %s", natPort, opts.container) return errors.Errorf("Error: No public port '%s' published for %s", natPort, opts.container)
} }
for from, frontends := range c.NetworkSettings.Ports { for from, frontends := range c.NetworkSettings.Ports {

View File

@ -1,12 +1,12 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -45,7 +45,7 @@ func runRename(dockerCli *command.DockerCli, opts *renameOptions) error {
if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil { if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
fmt.Fprintln(dockerCli.Err(), err) fmt.Fprintln(dockerCli.Err(), err)
return fmt.Errorf("Error: failed to rename container named %s", oldName) return errors.Errorf("Error: failed to rename container named %s", oldName)
} }
return nil return nil
} }

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"time" "time"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"io" "io"
"net/http/httputil" "net/http/httputil"
"os" "os"

View File

@ -1,7 +1,6 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net/http/httputil" "net/http/httputil"
@ -12,6 +11,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/promise"
"github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/signal"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -173,7 +173,7 @@ func startContainersWithoutAttachments(ctx context.Context, dockerCli *command.D
} }
if len(failedContainers) > 0 { if len(failedContainers) > 0 {
return fmt.Errorf("Error: failed to start containers: %s", strings.Join(failedContainers, ", ")) return errors.Errorf("Error: failed to start containers: %s", strings.Join(failedContainers, ", "))
} }
return nil return nil
} }

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"io" "io"
"strings" "strings"
"sync" "sync"

View File

@ -2,7 +2,7 @@ package container
import ( import (
"encoding/json" "encoding/json"
"errors" "github.com/pkg/errors"
"io" "io"
"strings" "strings"
"sync" "sync"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"time" "time"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
containertypes "github.com/docker/docker/api/types/container" containertypes "github.com/docker/docker/api/types/container"

View File

@ -1,8 +1,8 @@
package container package container
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"

View File

@ -2,13 +2,13 @@ package formatter
import ( import (
"bytes" "bytes"
"fmt"
"io" "io"
"strings" "strings"
"text/tabwriter" "text/tabwriter"
"text/template" "text/template"
"github.com/docker/docker/pkg/templates" "github.com/docker/docker/pkg/templates"
"github.com/pkg/errors"
) )
// Format keys used to specify certain kinds of output formats // Format keys used to specify certain kinds of output formats
@ -64,7 +64,7 @@ func (c *Context) preFormat() {
func (c *Context) parseFormat() (*template.Template, error) { func (c *Context) parseFormat() (*template.Template, error) {
tmpl, err := templates.Parse(c.finalFormat) tmpl, err := templates.Parse(c.finalFormat)
if err != nil { if err != nil {
return tmpl, fmt.Errorf("Template parsing error: %v\n", err) return tmpl, errors.Errorf("Template parsing error: %v\n", err)
} }
return tmpl, err return tmpl, err
} }
@ -85,7 +85,7 @@ func (c *Context) postFormat(tmpl *template.Template, subContext subContext) {
func (c *Context) contextFormat(tmpl *template.Template, subContext subContext) error { func (c *Context) contextFormat(tmpl *template.Template, subContext subContext) error {
if err := tmpl.Execute(c.buffer, subContext); err != nil { if err := tmpl.Execute(c.buffer, subContext); err != nil {
return fmt.Errorf("Template parsing error: %v\n", err) return errors.Errorf("Template parsing error: %v\n", err)
} }
if c.Format.IsTable() && c.header != nil { if c.Format.IsTable() && c.header != nil {
c.header = subContext.FullHeader() c.header = subContext.FullHeader()

View File

@ -2,9 +2,10 @@ package formatter
import ( import (
"encoding/json" "encoding/json"
"fmt"
"reflect" "reflect"
"unicode" "unicode"
"github.com/pkg/errors"
) )
func marshalJSON(x interface{}) ([]byte, error) { func marshalJSON(x interface{}) ([]byte, error) {
@ -19,14 +20,14 @@ func marshalJSON(x interface{}) ([]byte, error) {
func marshalMap(x interface{}) (map[string]interface{}, error) { func marshalMap(x interface{}) (map[string]interface{}, error) {
val := reflect.ValueOf(x) val := reflect.ValueOf(x)
if val.Kind() != reflect.Ptr { if val.Kind() != reflect.Ptr {
return nil, fmt.Errorf("expected a pointer to a struct, got %v", val.Kind()) return nil, errors.Errorf("expected a pointer to a struct, got %v", val.Kind())
} }
if val.IsNil() { if val.IsNil() {
return nil, fmt.Errorf("expected a pointer to a struct, got nil pointer") return nil, errors.Errorf("expected a pointer to a struct, got nil pointer")
} }
valElem := val.Elem() valElem := val.Elem()
if valElem.Kind() != reflect.Struct { if valElem.Kind() != reflect.Struct {
return nil, fmt.Errorf("expected a pointer to a struct, got a pointer to %v", valElem.Kind()) return nil, errors.Errorf("expected a pointer to a struct, got a pointer to %v", valElem.Kind())
} }
typ := val.Type() typ := val.Type()
m := make(map[string]interface{}) m := make(map[string]interface{})
@ -48,7 +49,7 @@ var unmarshallableNames = map[string]struct{}{"FullHeader": {}}
// It returns ("", nil, nil) for valid but non-marshallable parameter. (e.g. "unexportedFunc()") // It returns ("", nil, nil) for valid but non-marshallable parameter. (e.g. "unexportedFunc()")
func marshalForMethod(typ reflect.Method, val reflect.Value) (string, interface{}, error) { func marshalForMethod(typ reflect.Method, val reflect.Value) (string, interface{}, error) {
if val.Kind() != reflect.Func { if val.Kind() != reflect.Func {
return "", nil, fmt.Errorf("expected func, got %v", val.Kind()) return "", nil, errors.Errorf("expected func, got %v", val.Kind())
} }
name, numIn, numOut := typ.Name, val.Type().NumIn(), val.Type().NumOut() name, numIn, numOut := typ.Name, val.Type().NumIn(), val.Type().NumOut()
_, blackListed := unmarshallableNames[name] _, blackListed := unmarshallableNames[name]

View File

@ -1,7 +1,6 @@
package formatter package formatter
import ( import (
"fmt"
"strings" "strings"
"time" "time"
@ -11,6 +10,7 @@ import (
"github.com/docker/docker/cli/command/inspect" "github.com/docker/docker/cli/command/inspect"
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
units "github.com/docker/go-units" units "github.com/docker/go-units"
"github.com/pkg/errors"
) )
const serviceInspectPrettyTemplate Format = ` const serviceInspectPrettyTemplate Format = `
@ -147,7 +147,7 @@ func ServiceInspectWrite(ctx Context, refs []string, getRef inspect.GetRefFunc)
} }
service, ok := serviceI.(swarm.Service) service, ok := serviceI.(swarm.Service)
if !ok { if !ok {
return fmt.Errorf("got wrong object to inspect") return errors.Errorf("got wrong object to inspect")
} }
if err := format(&serviceInspectContext{Service: service}); err != nil { if err := format(&serviceInspectContext{Service: service}); err != nil {
return err return err

View File

@ -1,12 +1,11 @@
package idresolver package idresolver
import ( import (
"fmt"
"golang.org/x/net/context" "golang.org/x/net/context"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/pkg/errors"
) )
// IDResolver provides ID to Name resolution. // IDResolver provides ID to Name resolution.
@ -46,7 +45,7 @@ func (r *IDResolver) get(ctx context.Context, t interface{}, id string) (string,
} }
return service.Spec.Annotations.Name, nil return service.Spec.Annotations.Name, nil
default: default:
return "", fmt.Errorf("unsupported type") return "", errors.Errorf("unsupported type")
} }
} }

View File

@ -28,6 +28,7 @@ import (
"github.com/docker/docker/pkg/urlutil" "github.com/docker/docker/pkg/urlutil"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
units "github.com/docker/go-units" units "github.com/docker/go-units"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -166,14 +167,14 @@ func runBuild(dockerCli *command.DockerCli, options buildOptions) error {
case urlutil.IsURL(specifiedContext): case urlutil.IsURL(specifiedContext):
buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, options.dockerfileName) buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, options.dockerfileName)
default: default:
return fmt.Errorf("unable to prepare context: path %q not found", specifiedContext) return errors.Errorf("unable to prepare context: path %q not found", specifiedContext)
} }
if err != nil { if err != nil {
if options.quiet && urlutil.IsURL(specifiedContext) { if options.quiet && urlutil.IsURL(specifiedContext) {
fmt.Fprintln(dockerCli.Err(), progBuff) fmt.Fprintln(dockerCli.Err(), progBuff)
} }
return fmt.Errorf("unable to prepare context: %s", err) return errors.Errorf("unable to prepare context: %s", err)
} }
if tempDir != "" { if tempDir != "" {
@ -185,7 +186,7 @@ func runBuild(dockerCli *command.DockerCli, options buildOptions) error {
// And canonicalize dockerfile name to a platform-independent one // And canonicalize dockerfile name to a platform-independent one
relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile) relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
if err != nil { if err != nil {
return fmt.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err) return errors.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
} }
f, err := os.Open(filepath.Join(contextDir, ".dockerignore")) f, err := os.Open(filepath.Join(contextDir, ".dockerignore"))
@ -203,7 +204,7 @@ func runBuild(dockerCli *command.DockerCli, options buildOptions) error {
} }
if err := build.ValidateContextDirectory(contextDir, excludes); err != nil { if err := build.ValidateContextDirectory(contextDir, excludes); err != nil {
return fmt.Errorf("Error checking context: '%s'.", err) return errors.Errorf("Error checking context: '%s'.", err)
} }
// If .dockerignore mentions .dockerignore or the Dockerfile // If .dockerignore mentions .dockerignore or the Dockerfile

View File

@ -18,6 +18,7 @@ import (
"github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/progress" "github.com/docker/docker/pkg/progress"
"github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/streamformatter"
"github.com/pkg/errors"
) )
const ( const (
@ -36,7 +37,7 @@ func ValidateContextDirectory(srcPath string, excludes []string) error {
return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error { return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
if err != nil { if err != nil {
if os.IsPermission(err) { if os.IsPermission(err) {
return fmt.Errorf("can't stat '%s'", filePath) return errors.Errorf("can't stat '%s'", filePath)
} }
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil return nil
@ -65,7 +66,7 @@ func ValidateContextDirectory(srcPath string, excludes []string) error {
if !f.IsDir() { if !f.IsDir() {
currentFile, err := os.Open(filePath) currentFile, err := os.Open(filePath)
if err != nil && os.IsPermission(err) { if err != nil && os.IsPermission(err) {
return fmt.Errorf("no permission to read from '%s'", filePath) return errors.Errorf("no permission to read from '%s'", filePath)
} }
currentFile.Close() currentFile.Close()
} }
@ -81,7 +82,7 @@ func GetContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCl
magic, err := buf.Peek(archive.HeaderSize) magic, err := buf.Peek(archive.HeaderSize)
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
return nil, "", fmt.Errorf("failed to peek context header from STDIN: %v", err) return nil, "", errors.Errorf("failed to peek context header from STDIN: %v", err)
} }
if archive.IsArchive(magic) { if archive.IsArchive(magic) {
@ -91,7 +92,7 @@ func GetContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCl
// Input should be read as a Dockerfile. // Input should be read as a Dockerfile.
tmpDir, err := ioutil.TempDir("", "docker-build-context-") tmpDir, err := ioutil.TempDir("", "docker-build-context-")
if err != nil { if err != nil {
return nil, "", fmt.Errorf("unable to create temporary context directory: %v", err) return nil, "", errors.Errorf("unable to create temporary context directory: %v", err)
} }
f, err := os.Create(filepath.Join(tmpDir, DefaultDockerfileName)) f, err := os.Create(filepath.Join(tmpDir, DefaultDockerfileName))
@ -131,10 +132,10 @@ func GetContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCl
// success. // success.
func GetContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) { func GetContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
if _, err := exec.LookPath("git"); err != nil { if _, err := exec.LookPath("git"); err != nil {
return "", "", fmt.Errorf("unable to find 'git': %v", err) return "", "", errors.Errorf("unable to find 'git': %v", err)
} }
if absContextDir, err = gitutils.Clone(gitURL); err != nil { if absContextDir, err = gitutils.Clone(gitURL); err != nil {
return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err) return "", "", errors.Errorf("unable to 'git clone' to temporary context directory: %v", err)
} }
return getDockerfileRelPath(absContextDir, dockerfileName) return getDockerfileRelPath(absContextDir, dockerfileName)
@ -147,7 +148,7 @@ func GetContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDock
func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) { func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
response, err := httputils.Download(remoteURL) response, err := httputils.Download(remoteURL)
if err != nil { if err != nil {
return nil, "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err) return nil, "", errors.Errorf("unable to download remote context %s: %v", remoteURL, err)
} }
progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true) progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
@ -167,7 +168,7 @@ func GetContextFromLocalDir(localDir, dockerfileName string) (absContextDir, rel
// current directory and not the context directory. // current directory and not the context directory.
if dockerfileName != "" { if dockerfileName != "" {
if dockerfileName, err = filepath.Abs(dockerfileName); err != nil { if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err) return "", "", errors.Errorf("unable to get absolute path to Dockerfile: %v", err)
} }
} }
@ -179,7 +180,7 @@ func GetContextFromLocalDir(localDir, dockerfileName string) (absContextDir, rel
// the dockerfile in that context directory, and a non-nil error on success. // the dockerfile in that context directory, and a non-nil error on success.
func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) { func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
if absContextDir, err = filepath.Abs(givenContextDir); err != nil { if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
return "", "", fmt.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err) return "", "", errors.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err)
} }
// The context dir might be a symbolic link, so follow it to the actual // The context dir might be a symbolic link, so follow it to the actual
@ -192,17 +193,17 @@ func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDi
if !isUNC(absContextDir) { if !isUNC(absContextDir) {
absContextDir, err = filepath.EvalSymlinks(absContextDir) absContextDir, err = filepath.EvalSymlinks(absContextDir)
if err != nil { if err != nil {
return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err) return "", "", errors.Errorf("unable to evaluate symlinks in context path: %v", err)
} }
} }
stat, err := os.Lstat(absContextDir) stat, err := os.Lstat(absContextDir)
if err != nil { if err != nil {
return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err) return "", "", errors.Errorf("unable to stat context directory %q: %v", absContextDir, err)
} }
if !stat.IsDir() { if !stat.IsDir() {
return "", "", fmt.Errorf("context must be a directory: %s", absContextDir) return "", "", errors.Errorf("context must be a directory: %s", absContextDir)
} }
absDockerfile := givenDockerfile absDockerfile := givenDockerfile
@ -236,23 +237,23 @@ func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDi
if !isUNC(absDockerfile) { if !isUNC(absDockerfile) {
absDockerfile, err = filepath.EvalSymlinks(absDockerfile) absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
if err != nil { if err != nil {
return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err) return "", "", errors.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
} }
} }
if _, err := os.Lstat(absDockerfile); err != nil { if _, err := os.Lstat(absDockerfile); err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile) return "", "", errors.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
} }
return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err) return "", "", errors.Errorf("unable to stat Dockerfile: %v", err)
} }
if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil { if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err) return "", "", errors.Errorf("unable to get relative Dockerfile path: %v", err)
} }
if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir) return "", "", errors.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
} }
return absContextDir, relDockerfile, nil return absContextDir, relDockerfile, nil

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"fmt"
"io" "io"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -10,6 +9,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/system"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -56,7 +56,7 @@ func runLoad(dockerCli *command.DockerCli, opts loadOptions) error {
// To avoid getting stuck, verify that a tar file is given either in // 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. // the input flag or through stdin and if not display an error message and exit.
if opts.input == "" && dockerCli.In().IsTerminal() { if opts.input == "" && dockerCli.In().IsTerminal() {
return fmt.Errorf("requested load from stdin, but stdin is empty") return errors.Errorf("requested load from stdin, but stdin is empty")
} }
if !dockerCli.Out().IsTerminal() { if !dockerCli.Out().IsTerminal() {

View File

@ -1,8 +1,8 @@
package image package image
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"strings" "strings"
"golang.org/x/net/context" "golang.org/x/net/context"

View File

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -71,7 +72,7 @@ func runRemove(dockerCli *command.DockerCli, opts removeOptions, images []string
} }
if len(errs) > 0 { if len(errs) > 0 {
return fmt.Errorf("%s", strings.Join(errs, "\n")) return errors.Errorf("%s", strings.Join(errs, "\n"))
} }
return nil return nil
} }

View File

@ -1,7 +1,7 @@
package image package image
import ( import (
"errors" "github.com/pkg/errors"
"io" "io"
"golang.org/x/net/context" "golang.org/x/net/context"

View File

@ -3,7 +3,6 @@ package image
import ( import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"path" "path"
@ -19,6 +18,7 @@ import (
"github.com/docker/notary/client" "github.com/docker/notary/client"
"github.com/docker/notary/tuf/data" "github.com/docker/notary/tuf/data"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -92,7 +92,7 @@ func PushTrustedReference(cli *command.DockerCli, repoInfo *registry.RepositoryI
} }
if cnt > 1 { if cnt > 1 {
return fmt.Errorf("internal error: only one call to handleTarget expected") return errors.Errorf("internal error: only one call to handleTarget expected")
} }
if target == nil { if target == nil {
@ -195,7 +195,7 @@ func addTargetToAllSignableRoles(repo *client.NotaryRepository, target *client.T
} }
if len(signableRoles) == 0 { if len(signableRoles) == 0 {
return fmt.Errorf("no valid signing keys for delegation roles") return errors.Errorf("no valid signing keys for delegation roles")
} }
return repo.AddTarget(target, signableRoles...) return repo.AddTarget(target, signableRoles...)
@ -245,7 +245,7 @@ func trustedPull(ctx context.Context, cli *command.DockerCli, repoInfo *registry
refs = append(refs, t) refs = append(refs, t)
} }
if len(refs) == 0 { if len(refs) == 0 {
return trust.NotaryError(ref.Name(), fmt.Errorf("No trusted tags for %s", ref.Name())) return trust.NotaryError(ref.Name(), errors.Errorf("No trusted tags for %s", ref.Name()))
} }
} else { } else {
t, err := notaryRepo.GetTargetByName(tagged.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole) t, err := notaryRepo.GetTargetByName(tagged.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
@ -255,7 +255,7 @@ func trustedPull(ctx context.Context, cli *command.DockerCli, repoInfo *registry
// Only get the tag if it's in the top level targets role or the releases delegation role // 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 // ignore it if it's in any other delegation roles
if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
return trust.NotaryError(ref.Name(), fmt.Errorf("No trust data for %s", tagged.Tag())) return trust.NotaryError(ref.Name(), errors.Errorf("No trust data for %s", tagged.Tag()))
} }
logrus.Debugf("retrieving target for %s role\n", t.Role) logrus.Debugf("retrieving target for %s role\n", t.Role)
@ -347,7 +347,7 @@ func TrustedReference(ctx context.Context, cli *command.DockerCli, ref reference
// Only list tags in the top level targets role or the releases delegation role - ignore // Only list tags in the top level targets role or the releases delegation role - ignore
// all other delegation roles // all other delegation roles
if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("No trust data for %s", ref.Tag())) return nil, trust.NotaryError(repoInfo.Name.Name(), errors.Errorf("No trust data for %s", ref.Tag()))
} }
r, err := convertTarget(t.Target) r, err := convertTarget(t.Target)
if err != nil { if err != nil {

View File

@ -1,7 +1,7 @@
package command package command
import ( import (
"errors" "github.com/pkg/errors"
"io" "io"
"os" "os"
"runtime" "runtime"

View File

@ -3,7 +3,6 @@ package inspect
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"strings" "strings"
"text/template" "text/template"
@ -11,6 +10,7 @@ import (
"github.com/Sirupsen/logrus" "github.com/Sirupsen/logrus"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/pkg/templates" "github.com/docker/docker/pkg/templates"
"github.com/pkg/errors"
) )
// Inspector defines an interface to implement to process elements // Inspector defines an interface to implement to process elements
@ -44,7 +44,7 @@ func NewTemplateInspectorFromString(out io.Writer, tmplStr string) (Inspector, e
tmpl, err := templates.Parse(tmplStr) tmpl, err := templates.Parse(tmplStr)
if err != nil { if err != nil {
return nil, fmt.Errorf("Template parsing error: %s", err) return nil, errors.Errorf("Template parsing error: %s", err)
} }
return NewTemplateInspector(out, tmpl), nil return NewTemplateInspector(out, tmpl), nil
} }
@ -94,7 +94,7 @@ func (i *TemplateInspector) Inspect(typedElement interface{}, rawElement []byte)
buffer := new(bytes.Buffer) buffer := new(bytes.Buffer)
if err := i.tmpl.Execute(buffer, typedElement); err != nil { if err := i.tmpl.Execute(buffer, typedElement); err != nil {
if rawElement == nil { if rawElement == nil {
return fmt.Errorf("Template parsing error: %v", err) return errors.Errorf("Template parsing error: %v", err)
} }
return i.tryRawInspectFallback(rawElement) return i.tryRawInspectFallback(rawElement)
} }
@ -112,12 +112,12 @@ func (i *TemplateInspector) tryRawInspectFallback(rawElement []byte) error {
dec := json.NewDecoder(rdr) dec := json.NewDecoder(rdr)
if rawErr := dec.Decode(&raw); rawErr != nil { if rawErr := dec.Decode(&raw); rawErr != nil {
return fmt.Errorf("unable to read inspect data: %v", rawErr) return errors.Errorf("unable to read inspect data: %v", rawErr)
} }
tmplMissingKey := i.tmpl.Option("missingkey=error") tmplMissingKey := i.tmpl.Option("missingkey=error")
if rawErr := tmplMissingKey.Execute(buffer, raw); rawErr != nil { if rawErr := tmplMissingKey.Execute(buffer, raw); rawErr != nil {
return fmt.Errorf("Template parsing error: %v", rawErr) return errors.Errorf("Template parsing error: %v", rawErr)
} }
i.buffer.Write(buffer.Bytes()) i.buffer.Write(buffer.Bytes())

View File

@ -13,6 +13,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -110,7 +111,7 @@ func runCreate(dockerCli *command.DockerCli, opts createOptions) error {
// structured ipam data. // structured ipam data.
func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) { func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) {
if len(subnets) < len(ranges) || len(subnets) < len(gateways) { if len(subnets) < len(ranges) || len(subnets) < len(gateways) {
return nil, fmt.Errorf("every ip-range or gateway must have a corresponding subnet") return nil, errors.Errorf("every ip-range or gateway must have a corresponding subnet")
} }
iData := map[string]*network.IPAMConfig{} iData := map[string]*network.IPAMConfig{}
@ -126,7 +127,7 @@ func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]str
return nil, err return nil, err
} }
if ok1 || ok2 { if ok1 || ok2 {
return nil, fmt.Errorf("multiple overlapping subnet configuration is not supported") return nil, errors.Errorf("multiple overlapping subnet configuration is not supported")
} }
} }
iData[s] = &network.IPAMConfig{Subnet: s, AuxAddress: map[string]string{}} iData[s] = &network.IPAMConfig{Subnet: s, AuxAddress: map[string]string{}}
@ -144,14 +145,14 @@ func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]str
continue continue
} }
if iData[s].IPRange != "" { if iData[s].IPRange != "" {
return nil, fmt.Errorf("cannot configure multiple ranges (%s, %s) on the same subnet (%s)", r, iData[s].IPRange, s) return nil, errors.Errorf("cannot configure multiple ranges (%s, %s) on the same subnet (%s)", r, iData[s].IPRange, s)
} }
d := iData[s] d := iData[s]
d.IPRange = r d.IPRange = r
match = true match = true
} }
if !match { if !match {
return nil, fmt.Errorf("no matching subnet for range %s", r) return nil, errors.Errorf("no matching subnet for range %s", r)
} }
} }
@ -167,14 +168,14 @@ func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]str
continue continue
} }
if iData[s].Gateway != "" { if iData[s].Gateway != "" {
return nil, fmt.Errorf("cannot configure multiple gateways (%s, %s) for the same subnet (%s)", g, iData[s].Gateway, s) return nil, errors.Errorf("cannot configure multiple gateways (%s, %s) for the same subnet (%s)", g, iData[s].Gateway, s)
} }
d := iData[s] d := iData[s]
d.Gateway = g d.Gateway = g
match = true match = true
} }
if !match { if !match {
return nil, fmt.Errorf("no matching subnet for gateway %s", g) return nil, errors.Errorf("no matching subnet for gateway %s", g)
} }
} }
@ -193,7 +194,7 @@ func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]str
match = true match = true
} }
if !match { if !match {
return nil, fmt.Errorf("no matching subnet for aux-address %s", aa) return nil, errors.Errorf("no matching subnet for aux-address %s", aa)
} }
} }
@ -211,13 +212,13 @@ func subnetMatches(subnet, data string) (bool, error) {
_, s, err := net.ParseCIDR(subnet) _, s, err := net.ParseCIDR(subnet)
if err != nil { if err != nil {
return false, fmt.Errorf("Invalid subnet %s : %v", s, err) return false, errors.Errorf("Invalid subnet %s : %v", s, err)
} }
if strings.Contains(data, "/") { if strings.Contains(data, "/") {
ip, _, err = net.ParseCIDR(data) ip, _, err = net.ParseCIDR(data)
if err != nil { if err != nil {
return false, fmt.Errorf("Invalid cidr %s : %v", data, err) return false, errors.Errorf("Invalid cidr %s : %v", data, err)
} }
} else { } else {
ip = net.ParseIP(data) ip = net.ParseIP(data)

View File

@ -2,12 +2,12 @@ package node
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -26,14 +26,14 @@ func TestNodeDemoteErrors(t *testing.T) {
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
expectedError: "error inspecting the node", expectedError: "error inspecting the node",
}, },
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
return fmt.Errorf("error updating the node") return errors.Errorf("error updating the node")
}, },
expectedError: "error updating the node", expectedError: "error updating the node",
}, },
@ -60,7 +60,7 @@ func TestNodeDemoteNoChange(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if node.Role != swarm.NodeRoleWorker { if node.Role != swarm.NodeRoleWorker {
return fmt.Errorf("expected role worker, got %s", node.Role) return errors.Errorf("expected role worker, got %s", node.Role)
} }
return nil return nil
}, },
@ -78,7 +78,7 @@ func TestNodeDemoteMultipleNode(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if node.Role != swarm.NodeRoleWorker { if node.Role != swarm.NodeRoleWorker {
return fmt.Errorf("expected role worker, got %s", node.Role) return errors.Errorf("expected role worker, got %s", node.Role)
} }
return nil return nil
}, },

View File

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -29,24 +30,24 @@ func TestNodeInspectErrors(t *testing.T) {
{ {
args: []string{"self"}, args: []string{"self"},
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error asking for node info", expectedError: "error asking for node info",
}, },
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error inspecting the node", expectedError: "error inspecting the node",
}, },
{ {
args: []string{"self"}, args: []string{"self"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, nil return types.Info{}, nil
@ -59,7 +60,7 @@ func TestNodeInspectErrors(t *testing.T) {
"pretty": "true", "pretty": "true",
}, },
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error asking for node info", expectedError: "error asking for node info",
}, },

View File

@ -2,13 +2,13 @@ package node
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -22,7 +22,7 @@ func TestNodeListErrorOnAPIFailure(t *testing.T) {
}{ }{
{ {
nodeListFunc: func() ([]swarm.Node, error) { nodeListFunc: func() ([]swarm.Node, error) {
return []swarm.Node{}, fmt.Errorf("error listing nodes") return []swarm.Node{}, errors.Errorf("error listing nodes")
}, },
expectedError: "error listing nodes", expectedError: "error listing nodes",
}, },
@ -35,7 +35,7 @@ func TestNodeListErrorOnAPIFailure(t *testing.T) {
}, nil }, nil
}, },
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error asking for node info", expectedError: "error asking for node info",
}, },

View File

@ -2,12 +2,12 @@ package node
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -26,14 +26,14 @@ func TestNodePromoteErrors(t *testing.T) {
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
expectedError: "error inspecting the node", expectedError: "error inspecting the node",
}, },
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
return fmt.Errorf("error updating the node") return errors.Errorf("error updating the node")
}, },
expectedError: "error updating the node", expectedError: "error updating the node",
}, },
@ -60,7 +60,7 @@ func TestNodePromoteNoChange(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if node.Role != swarm.NodeRoleManager { if node.Role != swarm.NodeRoleManager {
return fmt.Errorf("expected role manager, got %s", node.Role) return errors.Errorf("expected role manager, got %s", node.Role)
} }
return nil return nil
}, },
@ -78,7 +78,7 @@ func TestNodePromoteMultipleNode(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if node.Role != swarm.NodeRoleManager { if node.Role != swarm.NodeRoleManager {
return fmt.Errorf("expected role manager, got %s", node.Role) return errors.Errorf("expected role manager, got %s", node.Role)
} }
return nil return nil
}, },

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"fmt"
"strings" "strings"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
@ -12,6 +11,7 @@ import (
"github.com/docker/docker/cli/command/idresolver" "github.com/docker/docker/cli/command/idresolver"
"github.com/docker/docker/cli/command/task" "github.com/docker/docker/cli/command/task"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -100,7 +100,7 @@ func runPs(dockerCli command.Cli, opts psOptions) error {
} }
if len(errs) > 0 { if len(errs) > 0 {
return fmt.Errorf("%s", strings.Join(errs, "\n")) return errors.Errorf("%s", strings.Join(errs, "\n"))
} }
return nil return nil

View File

@ -10,6 +10,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -28,21 +29,21 @@ func TestNodePsErrors(t *testing.T) {
}{ }{
{ {
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error asking for node info", expectedError: "error asking for node info",
}, },
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
expectedError: "error inspecting the node", expectedError: "error inspecting the node",
}, },
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
taskListFunc: func(options types.TaskListOptions) ([]swarm.Task, error) { taskListFunc: func(options types.TaskListOptions) ([]swarm.Task, error) {
return []swarm.Task{}, fmt.Errorf("error returning the task list") return []swarm.Task{}, errors.Errorf("error returning the task list")
}, },
expectedError: "error returning the task list", expectedError: "error returning the task list",
}, },

View File

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -49,7 +50,7 @@ func runRemove(dockerCli command.Cli, args []string, opts removeOptions) error {
} }
if len(errs) > 0 { if len(errs) > 0 {
return fmt.Errorf("%s", strings.Join(errs, "\n")) return errors.Errorf("%s", strings.Join(errs, "\n"))
} }
return nil return nil

View File

@ -2,12 +2,12 @@ package node
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/pkg/errors"
) )
func TestNodeRemoveErrors(t *testing.T) { func TestNodeRemoveErrors(t *testing.T) {
@ -22,7 +22,7 @@ func TestNodeRemoveErrors(t *testing.T) {
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeRemoveFunc: func() error { nodeRemoveFunc: func() error {
return fmt.Errorf("error removing the node") return errors.Errorf("error removing the node")
}, },
expectedError: "error removing the node", expectedError: "error removing the node",
}, },

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"errors"
"fmt" "fmt"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
@ -9,6 +8,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -104,7 +104,7 @@ func mergeNodeUpdate(flags *pflag.FlagSet) func(*swarm.Node) error {
for _, k := range keys { for _, k := range keys {
// if a key doesn't exist, fail the command explicitly // if a key doesn't exist, fail the command explicitly
if _, exists := spec.Annotations.Labels[k]; !exists { if _, exists := spec.Annotations.Labels[k]; !exists {
return fmt.Errorf("key %s doesn't exist in node's labels", k) return errors.Errorf("key %s doesn't exist in node's labels", k)
} }
delete(spec.Annotations.Labels, k) delete(spec.Annotations.Labels, k)
} }

View File

@ -2,12 +2,12 @@ package node
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -31,14 +31,14 @@ func TestNodeUpdateErrors(t *testing.T) {
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
expectedError: "error inspecting the node", expectedError: "error inspecting the node",
}, },
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
return fmt.Errorf("error updating the node") return errors.Errorf("error updating the node")
}, },
expectedError: "error updating the node", expectedError: "error updating the node",
}, },
@ -88,7 +88,7 @@ func TestNodeUpdate(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if node.Role != swarm.NodeRoleManager { if node.Role != swarm.NodeRoleManager {
return fmt.Errorf("expected role manager, got %s", node.Role) return errors.Errorf("expected role manager, got %s", node.Role)
} }
return nil return nil
}, },
@ -103,7 +103,7 @@ func TestNodeUpdate(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if node.Availability != swarm.NodeAvailabilityDrain { if node.Availability != swarm.NodeAvailabilityDrain {
return fmt.Errorf("expected drain availability, got %s", node.Availability) return errors.Errorf("expected drain availability, got %s", node.Availability)
} }
return nil return nil
}, },
@ -118,7 +118,7 @@ func TestNodeUpdate(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if _, present := node.Annotations.Labels["lbl"]; !present { if _, present := node.Annotations.Labels["lbl"]; !present {
return fmt.Errorf("expected 'lbl' label, got %v", node.Annotations.Labels) return errors.Errorf("expected 'lbl' label, got %v", node.Annotations.Labels)
} }
return nil return nil
}, },
@ -133,7 +133,7 @@ func TestNodeUpdate(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if value, present := node.Annotations.Labels["key"]; !present || value != "value" { if value, present := node.Annotations.Labels["key"]; !present || value != "value" {
return fmt.Errorf("expected 'key' label to be 'value', got %v", node.Annotations.Labels) return errors.Errorf("expected 'key' label to be 'value', got %v", node.Annotations.Labels)
} }
return nil return nil
}, },
@ -150,7 +150,7 @@ func TestNodeUpdate(t *testing.T) {
}, },
nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error { nodeUpdateFunc: func(nodeID string, version swarm.Version, node swarm.NodeSpec) error {
if len(node.Annotations.Labels) > 0 { if len(node.Annotations.Labels) > 0 {
return fmt.Errorf("expected no labels, got %v", node.Annotations.Labels) return errors.Errorf("expected no labels, got %v", node.Annotations.Labels)
} }
return nil return nil
}, },

View File

@ -13,6 +13,7 @@ import (
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/archive"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -50,7 +51,7 @@ func validateContextDir(contextDir string) (string, error) {
} }
if !stat.IsDir() { if !stat.IsDir() {
return "", fmt.Errorf("context must be a directory") return "", errors.Errorf("context must be a directory")
} }
return absContextDir, nil return absContextDir, nil

View File

@ -6,6 +6,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -36,7 +37,7 @@ func newEnableCommand(dockerCli *command.DockerCli) *cobra.Command {
func runEnable(dockerCli *command.DockerCli, opts *enableOpts) error { func runEnable(dockerCli *command.DockerCli, opts *enableOpts) error {
name := opts.name name := opts.name
if opts.timeout < 0 { if opts.timeout < 0 {
return fmt.Errorf("negative timeout %d is invalid", opts.timeout) return errors.Errorf("negative timeout %d is invalid", opts.timeout)
} }
if err := dockerCli.Client().PluginEnable(context.Background(), name, types.PluginEnableOptions{Timeout: opts.timeout}); err != nil { if err := dockerCli.Client().PluginEnable(context.Background(), name, types.PluginEnableOptions{Timeout: opts.timeout}); err != nil {

View File

@ -1,7 +1,6 @@
package plugin package plugin
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
@ -12,6 +11,7 @@ import (
"github.com/docker/docker/cli/command/image" "github.com/docker/docker/cli/command/image"
"github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -92,7 +92,7 @@ func buildPullConfig(ctx context.Context, dockerCli *command.DockerCli, opts plu
ref = reference.TagNameOnly(ref) ref = reference.TagNameOnly(ref)
nt, ok := ref.(reference.NamedTagged) nt, ok := ref.(reference.NamedTagged)
if !ok { if !ok {
return types.PluginInstallOptions{}, fmt.Errorf("invalid name: %s", ref.String()) return types.PluginInstallOptions{}, errors.Errorf("invalid name: %s", ref.String())
} }
ctx := context.Background() ctx := context.Background()
@ -132,7 +132,7 @@ func runInstall(dockerCli *command.DockerCli, opts pluginOptions) error {
return err return err
} }
if _, ok := aref.(reference.Canonical); ok { if _, ok := aref.(reference.Canonical); ok {
return fmt.Errorf("invalid name: %s", opts.localName) return errors.Errorf("invalid name: %s", opts.localName)
} }
localName = reference.FamiliarString(reference.TagNameOnly(aref)) localName = reference.FamiliarString(reference.TagNameOnly(aref))
} }

View File

@ -1,8 +1,6 @@
package plugin package plugin
import ( import (
"fmt"
"golang.org/x/net/context" "golang.org/x/net/context"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
@ -11,6 +9,7 @@ import (
"github.com/docker/docker/cli/command/image" "github.com/docker/docker/cli/command/image"
"github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -37,7 +36,7 @@ func runPush(dockerCli *command.DockerCli, name string) error {
return err return err
} }
if _, ok := named.(reference.Canonical); ok { if _, ok := named.(reference.Canonical); ok {
return fmt.Errorf("invalid name: %s", name) return errors.Errorf("invalid name: %s", name)
} }
named = reference.TagNameOnly(named) named = reference.TagNameOnly(named)

View File

@ -39,11 +39,11 @@ func runUpgrade(dockerCli *command.DockerCli, opts pluginOptions) error {
ctx := context.Background() ctx := context.Background()
p, _, err := dockerCli.Client().PluginInspectWithRaw(ctx, opts.localName) p, _, err := dockerCli.Client().PluginInspectWithRaw(ctx, opts.localName)
if err != nil { if err != nil {
return fmt.Errorf("error reading plugin data: %v", err) return errors.Errorf("error reading plugin data: %v", err)
} }
if p.Enabled { if p.Enabled {
return fmt.Errorf("the plugin must be disabled before upgrading") return errors.Errorf("the plugin must be disabled before upgrading")
} }
opts.localName = p.Name opts.localName = p.Name

View File

@ -17,6 +17,7 @@ import (
registrytypes "github.com/docker/docker/api/types/registry" registrytypes "github.com/docker/docker/api/types/registry"
"github.com/docker/docker/pkg/term" "github.com/docker/docker/pkg/term"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/pkg/errors"
) )
// ElectAuthServer returns the default registry to use (by asking the daemon) // ElectAuthServer returns the default registry to use (by asking the daemon)
@ -95,7 +96,7 @@ func ConfigureAuth(cli *DockerCli, flUser, flPassword, serverAddress string, isD
// will hit this if you attempt docker login from mintty where stdin // will hit this if you attempt docker login from mintty where stdin
// is a pipe, not a character based console. // is a pipe, not a character based console.
if flPassword == "" && !cli.In().IsTerminal() { if flPassword == "" && !cli.In().IsTerminal() {
return authconfig, fmt.Errorf("Error: Cannot perform an interactive login from a non TTY device") return authconfig, errors.Errorf("Error: Cannot perform an interactive login from a non TTY device")
} }
authconfig.Username = strings.TrimSpace(authconfig.Username) authconfig.Username = strings.TrimSpace(authconfig.Username)
@ -113,7 +114,7 @@ func ConfigureAuth(cli *DockerCli, flUser, flPassword, serverAddress string, isD
} }
} }
if flUser == "" { if flUser == "" {
return authconfig, fmt.Errorf("Error: Non-null Username Required") return authconfig, errors.Errorf("Error: Non-null Username Required")
} }
if flPassword == "" { if flPassword == "" {
oldState, err := term.SaveState(cli.In().FD()) oldState, err := term.SaveState(cli.In().FD())
@ -128,7 +129,7 @@ func ConfigureAuth(cli *DockerCli, flUser, flPassword, serverAddress string, isD
term.RestoreTerminal(cli.In().FD(), oldState) term.RestoreTerminal(cli.In().FD(), oldState)
if flPassword == "" { if flPassword == "" {
return authconfig, fmt.Errorf("Error: Password Required") return authconfig, errors.Errorf("Error: Password Required")
} }
} }

View File

@ -8,6 +8,7 @@ import (
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -76,7 +77,7 @@ func runLogin(dockerCli *command.DockerCli, opts loginOptions) error {
authConfig.IdentityToken = response.IdentityToken authConfig.IdentityToken = response.IdentityToken
} }
if err := dockerCli.CredentialsStore(serverAddress).Store(authConfig); err != nil { if err := dockerCli.CredentialsStore(serverAddress).Store(authConfig); err != nil {
return fmt.Errorf("Error saving credentials: %v", err) return errors.Errorf("Error saving credentials: %v", err)
} }
if response.Status != "" { if response.Status != "" {

View File

@ -11,6 +11,7 @@ import (
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
"github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/system"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -58,7 +59,7 @@ func runSecretCreate(dockerCli *command.DockerCli, options createOptions) error
secretData, err := ioutil.ReadAll(in) secretData, err := ioutil.ReadAll(in)
if err != nil { if err != nil {
return fmt.Errorf("Error reading content from %q: %v", options.file, err) return errors.Errorf("Error reading content from %q: %v", options.file, err)
} }
spec := swarm.SecretSpec{ spec := swarm.SecretSpec{

View File

@ -6,6 +6,7 @@ import (
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -45,7 +46,7 @@ func runSecretRemove(dockerCli *command.DockerCli, opts removeOptions) error {
} }
if len(errs) > 0 { if len(errs) > 0 {
return fmt.Errorf("%s", strings.Join(errs, "\n")) return errors.Errorf("%s", strings.Join(errs, "\n"))
} }
return nil return nil

View File

@ -1,7 +1,6 @@
package service package service
import ( import (
"fmt"
"strings" "strings"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -10,6 +9,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/cli/command/formatter" "github.com/docker/docker/cli/command/formatter"
apiclient "github.com/docker/docker/client" apiclient "github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -30,7 +30,7 @@ func newInspectCommand(dockerCli *command.DockerCli) *cobra.Command {
opts.refs = args opts.refs = args
if opts.pretty && len(opts.format) > 0 { if opts.pretty && len(opts.format) > 0 {
return fmt.Errorf("--format is incompatible with human friendly format") return errors.Errorf("--format is incompatible with human friendly format")
} }
return runInspect(dockerCli, opts) return runInspect(dockerCli, opts)
}, },
@ -55,7 +55,7 @@ func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
if err == nil || !apiclient.IsErrServiceNotFound(err) { if err == nil || !apiclient.IsErrServiceNotFound(err) {
return service, nil, err return service, nil, err
} }
return nil, nil, fmt.Errorf("Error: no such service: %s", ref) return nil, nil, errors.Errorf("Error: no such service: %s", ref)
} }
f := opts.format f := opts.format
@ -69,7 +69,7 @@ func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
// check if the user is trying to apply a template to the pretty format, which // check if the user is trying to apply a template to the pretty format, which
// is not supported // is not supported
if strings.HasPrefix(f, "pretty") && f != "pretty" { if strings.HasPrefix(f, "pretty") && f != "pretty" {
return fmt.Errorf("Cannot supply extra formatting options to the pretty template") return errors.Errorf("Cannot supply extra formatting options to the pretty template")
} }
serviceCtx := formatter.Context{ serviceCtx := formatter.Context{

View File

@ -17,6 +17,7 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/stdcopy"
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -170,7 +171,7 @@ func (lw *logWriter) Write(buf []byte) (int, error) {
parts := bytes.SplitN(buf, []byte(" "), numParts) parts := bytes.SplitN(buf, []byte(" "), numParts)
if len(parts) != numParts { if len(parts) != numParts {
return 0, fmt.Errorf("invalid context in log message: %v", string(buf)) return 0, errors.Errorf("invalid context in log message: %v", string(buf))
} }
logCtx, err := lw.parseContext(string(parts[contextIndex])) logCtx, err := lw.parseContext(string(parts[contextIndex]))
@ -210,24 +211,24 @@ func (lw *logWriter) parseContext(input string) (logContext, error) {
for _, component := range components { for _, component := range components {
parts := strings.SplitN(component, "=", 2) parts := strings.SplitN(component, "=", 2)
if len(parts) != 2 { if len(parts) != 2 {
return logContext{}, fmt.Errorf("invalid context: %s", input) return logContext{}, errors.Errorf("invalid context: %s", input)
} }
context[parts[0]] = parts[1] context[parts[0]] = parts[1]
} }
nodeID, ok := context["com.docker.swarm.node.id"] nodeID, ok := context["com.docker.swarm.node.id"]
if !ok { if !ok {
return logContext{}, fmt.Errorf("missing node id in context: %s", input) return logContext{}, errors.Errorf("missing node id in context: %s", input)
} }
serviceID, ok := context["com.docker.swarm.service.id"] serviceID, ok := context["com.docker.swarm.service.id"]
if !ok { if !ok {
return logContext{}, fmt.Errorf("missing service id in context: %s", input) return logContext{}, errors.Errorf("missing service id in context: %s", input)
} }
taskID, ok := context["com.docker.swarm.task.id"] taskID, ok := context["com.docker.swarm.task.id"]
if !ok { if !ok {
return logContext{}, fmt.Errorf("missing task id in context: %s", input) return logContext{}, errors.Errorf("missing task id in context: %s", input)
} }
return logContext{ return logContext{

View File

@ -1,7 +1,6 @@
package service package service
import ( import (
"errors"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -11,6 +10,7 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/pkg/errors"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -32,7 +32,7 @@ func (d *PositiveDurationOpt) Set(s string) error {
return err return err
} }
if *d.DurationOpt.value < 0 { if *d.DurationOpt.value < 0 {
return fmt.Errorf("duration cannot be negative") return errors.Errorf("duration cannot be negative")
} }
return nil return nil
} }
@ -140,7 +140,7 @@ func (opts *placementPrefOpts) Set(value string) error {
return errors.New(`placement preference must be of the format "<strategy>=<arg>"`) return errors.New(`placement preference must be of the format "<strategy>=<arg>"`)
} }
if fields[0] != "spread" { if fields[0] != "spread" {
return fmt.Errorf("unsupported placement preference %s (only spread is supported)", fields[0]) return errors.Errorf("unsupported placement preference %s (only spread is supported)", fields[0])
} }
opts.prefs = append(opts.prefs, swarm.PlacementPreference{ opts.prefs = append(opts.prefs, swarm.PlacementPreference{
@ -268,7 +268,7 @@ func (opts *healthCheckOptions) toHealthConfig() (*container.HealthConfig, error
opts.retries != 0 opts.retries != 0
if opts.noHealthcheck { if opts.noHealthcheck {
if haveHealthSettings { if haveHealthSettings {
return nil, fmt.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck) return nil, errors.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck)
} }
healthConfig = &container.HealthConfig{Test: []string{"NONE"}} healthConfig = &container.HealthConfig{Test: []string{"NONE"}}
} else if haveHealthSettings { } else if haveHealthSettings {
@ -372,7 +372,7 @@ func (opts *serviceOptions) ToServiceMode() (swarm.ServiceMode, error) {
switch opts.mode { switch opts.mode {
case "global": case "global":
if opts.replicas.Value() != nil { if opts.replicas.Value() != nil {
return serviceMode, fmt.Errorf("replicas can only be used with replicated mode") return serviceMode, errors.Errorf("replicas can only be used with replicated mode")
} }
serviceMode.Global = &swarm.GlobalService{} serviceMode.Global = &swarm.GlobalService{}
@ -381,7 +381,7 @@ func (opts *serviceOptions) ToServiceMode() (swarm.ServiceMode, error) {
Replicas: opts.replicas.Value(), Replicas: opts.replicas.Value(),
} }
default: default:
return serviceMode, fmt.Errorf("Unknown mode: %s, only replicated and global supported", opts.mode) return serviceMode, errors.Errorf("Unknown mode: %s, only replicated and global supported", opts.mode)
} }
return serviceMode, nil return serviceMode, nil
} }

View File

@ -1,12 +1,11 @@
package service package service
import ( import (
"fmt"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
swarmtypes "github.com/docker/docker/api/types/swarm" swarmtypes "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/pkg/errors"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -18,7 +17,7 @@ func ParseSecrets(client client.SecretAPIClient, requestedSecrets []*swarmtypes.
for _, secret := range requestedSecrets { for _, secret := range requestedSecrets {
if _, exists := secretRefs[secret.File.Name]; exists { if _, exists := secretRefs[secret.File.Name]; exists {
return nil, fmt.Errorf("duplicate secret target for %s not allowed", secret.SecretName) return nil, errors.Errorf("duplicate secret target for %s not allowed", secret.SecretName)
} }
secretRef := new(swarmtypes.SecretReference) secretRef := new(swarmtypes.SecretReference)
*secretRef = *secret *secretRef = *secret
@ -47,7 +46,7 @@ func ParseSecrets(client client.SecretAPIClient, requestedSecrets []*swarmtypes.
for _, ref := range secretRefs { for _, ref := range secretRefs {
id, ok := foundSecrets[ref.SecretName] id, ok := foundSecrets[ref.SecretName]
if !ok { if !ok {
return nil, fmt.Errorf("secret not found: %s", ref.SecretName) return nil, errors.Errorf("secret not found: %s", ref.SecretName)
} }
// set the id for the ref to properly assign in swarm // set the id for the ref to properly assign in swarm

View File

@ -1,7 +1,6 @@
package service package service
import ( import (
"fmt"
"strings" "strings"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -15,6 +14,7 @@ import (
"github.com/docker/docker/cli/command/node" "github.com/docker/docker/cli/command/node"
"github.com/docker/docker/cli/command/task" "github.com/docker/docker/cli/command/task"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -89,7 +89,7 @@ func runPS(dockerCli *command.DockerCli, opts psOptions) error {
} }
// If nothing has been found, return immediately. // If nothing has been found, return immediately.
if serviceCount == 0 { if serviceCount == 0 {
return fmt.Errorf("no such services: %s", service) return errors.Errorf("no such services: %s", service)
} }
} }

View File

@ -6,6 +6,7 @@ import (
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -41,7 +42,7 @@ func runRemove(dockerCli *command.DockerCli, sids []string) error {
fmt.Fprintf(dockerCli.Out(), "%s\n", sid) fmt.Fprintf(dockerCli.Out(), "%s\n", sid)
} }
if len(errs) > 0 { if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, "\n")) return errors.Errorf(strings.Join(errs, "\n"))
} }
return nil return nil
} }

View File

@ -10,6 +10,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -30,7 +31,7 @@ func scaleArgs(cmd *cobra.Command, args []string) error {
} }
for _, arg := range args { for _, arg := range args {
if parts := strings.SplitN(arg, "=", 2); len(parts) != 2 { if parts := strings.SplitN(arg, "=", 2); len(parts) != 2 {
return fmt.Errorf( return errors.Errorf(
"Invalid scale specifier '%s'.\nSee '%s --help'.\n\nUsage: %s\n\n%s", "Invalid scale specifier '%s'.\nSee '%s --help'.\n\nUsage: %s\n\n%s",
arg, arg,
cmd.CommandPath(), cmd.CommandPath(),
@ -43,7 +44,7 @@ func scaleArgs(cmd *cobra.Command, args []string) error {
} }
func runScale(dockerCli *command.DockerCli, args []string) error { func runScale(dockerCli *command.DockerCli, args []string) error {
var errors []string var errs []string
for _, arg := range args { for _, arg := range args {
parts := strings.SplitN(arg, "=", 2) parts := strings.SplitN(arg, "=", 2)
serviceID, scaleStr := parts[0], parts[1] serviceID, scaleStr := parts[0], parts[1]
@ -51,19 +52,19 @@ func runScale(dockerCli *command.DockerCli, args []string) error {
// validate input arg scale number // validate input arg scale number
scale, err := strconv.ParseUint(scaleStr, 10, 64) scale, err := strconv.ParseUint(scaleStr, 10, 64)
if err != nil { if err != nil {
errors = append(errors, fmt.Sprintf("%s: invalid replicas value %s: %v", serviceID, scaleStr, err)) errs = append(errs, fmt.Sprintf("%s: invalid replicas value %s: %v", serviceID, scaleStr, err))
continue continue
} }
if err := runServiceScale(dockerCli, serviceID, scale); err != nil { if err := runServiceScale(dockerCli, serviceID, scale); err != nil {
errors = append(errors, fmt.Sprintf("%s: %v", serviceID, err)) errs = append(errs, fmt.Sprintf("%s: %v", serviceID, err))
} }
} }
if len(errors) == 0 { if len(errs) == 0 {
return nil return nil
} }
return fmt.Errorf(strings.Join(errors, "\n")) return errors.Errorf(strings.Join(errs, "\n"))
} }
func runServiceScale(dockerCli *command.DockerCli, serviceID string, scale uint64) error { func runServiceScale(dockerCli *command.DockerCli, serviceID string, scale uint64) error {
@ -77,7 +78,7 @@ func runServiceScale(dockerCli *command.DockerCli, serviceID string, scale uint6
serviceMode := &service.Spec.Mode serviceMode := &service.Spec.Mode
if serviceMode.Replicated == nil { if serviceMode.Replicated == nil {
return fmt.Errorf("scale can only be used with replicated mode") return errors.Errorf("scale can only be used with replicated mode")
} }
serviceMode.Replicated.Replicas = &scale serviceMode.Replicated.Replicas = &scale

View File

@ -2,7 +2,6 @@ package service
import ( import (
"encoding/hex" "encoding/hex"
"fmt"
"github.com/Sirupsen/logrus" "github.com/Sirupsen/logrus"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
@ -72,7 +71,7 @@ func trustedResolveDigest(ctx context.Context, cli *command.DockerCli, ref refer
// Only get the tag if it's in the top level targets role or the releases delegation role // 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 // ignore it if it's in any other delegation roles
if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole { if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
return nil, trust.NotaryError(repoInfo.Name.Name(), fmt.Errorf("No trust data for %s", reference.FamiliarString(ref))) return nil, trust.NotaryError(repoInfo.Name.Name(), errors.Errorf("No trust data for %s", reference.FamiliarString(ref)))
} }
logrus.Debugf("retrieving target for %s role\n", t.Role) logrus.Debugf("retrieving target for %s role\n", t.Role)

View File

@ -1,7 +1,6 @@
package service package service
import ( import (
"errors"
"fmt" "fmt"
"sort" "sort"
"strings" "strings"
@ -19,6 +18,7 @@ import (
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
shlex "github.com/flynn-archive/go-shlex" shlex "github.com/flynn-archive/go-shlex"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"golang.org/x/net/context" "golang.org/x/net/context"
@ -136,7 +136,7 @@ func runUpdate(dockerCli *command.DockerCli, flags *pflag.FlagSet, serviceID str
clientSideRollback = true clientSideRollback = true
spec = service.PreviousSpec spec = service.PreviousSpec
if spec == nil { if spec == nil {
return fmt.Errorf("service does not have a previous specification to roll back to") return errors.Errorf("service does not have a previous specification to roll back to")
} }
} else { } else {
serverSideRollback = true serverSideRollback = true
@ -621,7 +621,7 @@ func updateMounts(flags *pflag.FlagSet, mounts *[]mounttypes.Mount) error {
values := flags.Lookup(flagMountAdd).Value.(*opts.MountOpt).Value() values := flags.Lookup(flagMountAdd).Value.(*opts.MountOpt).Value()
for _, mount := range values { for _, mount := range values {
if _, ok := mountsByTarget[mount.Target]; ok { if _, ok := mountsByTarget[mount.Target]; ok {
return fmt.Errorf("duplicate mount target") return errors.Errorf("duplicate mount target")
} }
mountsByTarget[mount.Target] = mount mountsByTarget[mount.Target] = mount
} }
@ -819,7 +819,7 @@ func updateReplicas(flags *pflag.FlagSet, serviceMode *swarm.ServiceMode) error
} }
if serviceMode == nil || serviceMode.Replicated == nil { if serviceMode == nil || serviceMode.Replicated == nil {
return fmt.Errorf("replicas can only be used with replicated mode") return errors.Errorf("replicas can only be used with replicated mode")
} }
serviceMode.Replicated.Replicas = flags.Lookup(flagReplicas).Value.(*Uint64Opt).Value() serviceMode.Replicated.Replicas = flags.Lookup(flagReplicas).Value.(*Uint64Opt).Value()
return nil return nil
@ -908,7 +908,7 @@ func updateHealthcheck(flags *pflag.FlagSet, containerSpec *swarm.ContainerSpec)
} }
return nil return nil
} }
return fmt.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck) return errors.Errorf("--%s conflicts with --health-* options", flagNoHealthcheck)
} }
if len(containerSpec.Healthcheck.Test) > 0 && containerSpec.Healthcheck.Test[0] == "NONE" { if len(containerSpec.Healthcheck.Test) > 0 && containerSpec.Healthcheck.Test[0] == "NONE" {
containerSpec.Healthcheck.Test = nil containerSpec.Healthcheck.Test = nil

View File

@ -52,9 +52,9 @@ func runDeploy(dockerCli *command.DockerCli, opts deployOptions) error {
switch { switch {
case opts.bundlefile == "" && opts.composefile == "": case opts.bundlefile == "" && opts.composefile == "":
return fmt.Errorf("Please specify either a bundle file (with --bundle-file) or a Compose file (with --compose-file).") return errors.Errorf("Please specify either a bundle file (with --bundle-file) or a Compose file (with --compose-file).")
case opts.bundlefile != "" && opts.composefile != "": case opts.bundlefile != "" && opts.composefile != "":
return fmt.Errorf("You cannot specify both a bundle file and a Compose file.") return errors.Errorf("You cannot specify both a bundle file and a Compose file.")
case opts.bundlefile != "": case opts.bundlefile != "":
return deployBundle(ctx, dockerCli, opts) return deployBundle(ctx, dockerCli, opts)
default: default:

View File

@ -28,7 +28,7 @@ func deployCompose(ctx context.Context, dockerCli *command.DockerCli, opts deplo
config, err := loader.Load(configDetails) config, err := loader.Load(configDetails)
if err != nil { if err != nil {
if fpe, ok := err.(*loader.ForbiddenPropertiesError); ok { if fpe, ok := err.(*loader.ForbiddenPropertiesError); ok {
return fmt.Errorf("Compose file contains unsupported options:\n\n%s\n", return errors.Errorf("Compose file contains unsupported options:\n\n%s\n",
propertyWarnings(fpe.Properties)) propertyWarnings(fpe.Properties))
} }
@ -168,12 +168,12 @@ func validateExternalNetworks(
network, err := client.NetworkInspect(ctx, networkName, false) network, err := client.NetworkInspect(ctx, networkName, false)
if err != nil { if err != nil {
if dockerclient.IsErrNetworkNotFound(err) { if dockerclient.IsErrNetworkNotFound(err) {
return fmt.Errorf("network %q is declared as external, but could not be found. You need to create the network before the stack is deployed (with overlay driver)", networkName) return errors.Errorf("network %q is declared as external, but could not be found. You need to create the network before the stack is deployed (with overlay driver)", networkName)
} }
return err return err
} }
if network.Scope != "swarm" { if network.Scope != "swarm" {
return fmt.Errorf("network %q is declared as external, but it is not in the right scope: %q instead of %q", networkName, network.Scope, "swarm") return errors.Errorf("network %q is declared as external, but it is not in the right scope: %q instead of %q", networkName, network.Scope, "swarm")
} }
} }

View File

@ -12,6 +12,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/cli/compose/convert" "github.com/docker/docker/cli/compose/convert"
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -100,7 +101,7 @@ func getStacks(
labels := service.Spec.Labels labels := service.Spec.Labels
name, ok := labels[convert.LabelNamespace] name, ok := labels[convert.LabelNamespace]
if !ok { if !ok {
return nil, fmt.Errorf("cannot get label %s for service %s", return nil, errors.Errorf("cannot get label %s for service %s",
convert.LabelNamespace, service.ID) convert.LabelNamespace, service.ID)
} }
ztack, ok := m[name] ztack, ok := m[name]

View File

@ -6,6 +6,7 @@ import (
"os" "os"
"github.com/docker/docker/cli/command/bundlefile" "github.com/docker/docker/cli/command/bundlefile"
"github.com/pkg/errors"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -30,7 +31,7 @@ func loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefil
path = defaultPath path = defaultPath
} }
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf( return nil, errors.Errorf(
"Bundle %s not found. Specify the path with --file", "Bundle %s not found. Specify the path with --file",
path) path)
} }
@ -44,7 +45,7 @@ func loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefil
bundle, err := bundlefile.LoadFile(reader) bundle, err := bundlefile.LoadFile(reader)
if err != nil { if err != nil {
return nil, fmt.Errorf("Error reading %s: %v\n", path, err) return nil, errors.Errorf("Error reading %s: %v\n", path, err)
} }
return bundle, err return bundle, err
} }

View File

@ -7,6 +7,7 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -61,7 +62,7 @@ func runRemove(dockerCli *command.DockerCli, opts removeOptions) error {
hasError = removeNetworks(ctx, dockerCli, networks) || hasError hasError = removeNetworks(ctx, dockerCli, networks) || hasError
if hasError { if hasError {
return fmt.Errorf("Failed to remove some resources") return errors.Errorf("Failed to remove some resources")
} }
return nil return nil
} }

View File

@ -64,7 +64,7 @@ func runInit(dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) erro
case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain: case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain:
req.Availability = availability req.Availability = availability
default: default:
return fmt.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability) return errors.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability)
} }
} }

View File

@ -11,6 +11,7 @@ import (
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/docker/docker/pkg/testutil/golden" "github.com/docker/docker/pkg/testutil/golden"
"github.com/pkg/errors"
) )
func TestSwarmInitErrorOnAPIFailure(t *testing.T) { func TestSwarmInitErrorOnAPIFailure(t *testing.T) {
@ -26,28 +27,28 @@ func TestSwarmInitErrorOnAPIFailure(t *testing.T) {
{ {
name: "init-failed", name: "init-failed",
swarmInitFunc: func() (string, error) { swarmInitFunc: func() (string, error) {
return "", fmt.Errorf("error initializing the swarm") return "", errors.Errorf("error initializing the swarm")
}, },
expectedError: "error initializing the swarm", expectedError: "error initializing the swarm",
}, },
{ {
name: "init-failed-with-ip-choice", name: "init-failed-with-ip-choice",
swarmInitFunc: func() (string, error) { swarmInitFunc: func() (string, error) {
return "", fmt.Errorf("could not choose an IP address to advertise") return "", errors.Errorf("could not choose an IP address to advertise")
}, },
expectedError: "could not choose an IP address to advertise - specify one with --advertise-addr", expectedError: "could not choose an IP address to advertise - specify one with --advertise-addr",
}, },
{ {
name: "swarm-inspect-after-init-failed", name: "swarm-inspect-after-init-failed",
swarmInspectFunc: func() (swarm.Swarm, error) { swarmInspectFunc: func() (swarm.Swarm, error) {
return swarm.Swarm{}, fmt.Errorf("error inspecting the swarm") return swarm.Swarm{}, errors.Errorf("error inspecting the swarm")
}, },
expectedError: "error inspecting the swarm", expectedError: "error inspecting the swarm",
}, },
{ {
name: "node-inspect-after-init-failed", name: "node-inspect-after-init-failed",
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting the node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting the node")
}, },
expectedError: "error inspecting the node", expectedError: "error inspecting the node",
}, },
@ -57,7 +58,7 @@ func TestSwarmInitErrorOnAPIFailure(t *testing.T) {
flagAutolock: "true", flagAutolock: "true",
}, },
swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) {
return types.SwarmUnlockKeyResponse{}, fmt.Errorf("error getting swarm unlock key") return types.SwarmUnlockKeyResponse{}, errors.Errorf("error getting swarm unlock key")
}, },
expectedError: "could not fetch unlock key: error getting swarm unlock key", expectedError: "could not fetch unlock key: error getting swarm unlock key",
}, },

View File

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -61,7 +62,7 @@ func runJoin(dockerCli command.Cli, flags *pflag.FlagSet, opts joinOptions) erro
case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain: case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain:
req.Availability = availability req.Availability = availability
default: default:
return fmt.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability) return errors.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability)
} }
} }

View File

@ -2,7 +2,6 @@ package swarm
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
@ -11,6 +10,7 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/pkg/errors"
) )
func TestSwarmJoinErrors(t *testing.T) { func TestSwarmJoinErrors(t *testing.T) {
@ -34,7 +34,7 @@ func TestSwarmJoinErrors(t *testing.T) {
name: "join-failed", name: "join-failed",
args: []string{"remote"}, args: []string{"remote"},
swarmJoinFunc: func() error { swarmJoinFunc: func() error {
return fmt.Errorf("error joining the swarm") return errors.Errorf("error joining the swarm")
}, },
expectedError: "error joining the swarm", expectedError: "error joining the swarm",
}, },
@ -42,7 +42,7 @@ func TestSwarmJoinErrors(t *testing.T) {
name: "join-failed-on-init", name: "join-failed-on-init",
args: []string{"remote"}, args: []string{"remote"},
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error asking for node info", expectedError: "error asking for node info",
}, },

View File

@ -1,8 +1,8 @@
package swarm package swarm
import ( import (
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"

View File

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -44,7 +45,7 @@ func TestSwarmJoinTokenErrors(t *testing.T) {
name: "swarm-inspect-failed", name: "swarm-inspect-failed",
args: []string{"worker"}, args: []string{"worker"},
swarmInspectFunc: func() (swarm.Swarm, error) { swarmInspectFunc: func() (swarm.Swarm, error) {
return swarm.Swarm{}, fmt.Errorf("error inspecting the swarm") return swarm.Swarm{}, errors.Errorf("error inspecting the swarm")
}, },
expectedError: "error inspecting the swarm", expectedError: "error inspecting the swarm",
}, },
@ -55,7 +56,7 @@ func TestSwarmJoinTokenErrors(t *testing.T) {
flagRotate: "true", flagRotate: "true",
}, },
swarmInspectFunc: func() (swarm.Swarm, error) { swarmInspectFunc: func() (swarm.Swarm, error) {
return swarm.Swarm{}, fmt.Errorf("error inspecting the swarm") return swarm.Swarm{}, errors.Errorf("error inspecting the swarm")
}, },
expectedError: "error inspecting the swarm", expectedError: "error inspecting the swarm",
}, },
@ -66,7 +67,7 @@ func TestSwarmJoinTokenErrors(t *testing.T) {
flagRotate: "true", flagRotate: "true",
}, },
swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error { swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error {
return fmt.Errorf("error updating the swarm") return errors.Errorf("error updating the swarm")
}, },
expectedError: "error updating the swarm", expectedError: "error updating the swarm",
}, },
@ -74,7 +75,7 @@ func TestSwarmJoinTokenErrors(t *testing.T) {
name: "node-inspect-failed", name: "node-inspect-failed",
args: []string{"worker"}, args: []string{"worker"},
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return swarm.Node{}, []byte{}, fmt.Errorf("error inspecting node") return swarm.Node{}, []byte{}, errors.Errorf("error inspecting node")
}, },
expectedError: "error inspecting node", expectedError: "error inspecting node",
}, },
@ -82,7 +83,7 @@ func TestSwarmJoinTokenErrors(t *testing.T) {
name: "info-failed", name: "info-failed",
args: []string{"worker"}, args: []string{"worker"},
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
return types.Info{}, fmt.Errorf("error asking for node info") return types.Info{}, errors.Errorf("error asking for node info")
}, },
expectedError: "error asking for node info", expectedError: "error asking for node info",
}, },

View File

@ -2,13 +2,13 @@ package swarm
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/pkg/errors"
) )
func TestSwarmLeaveErrors(t *testing.T) { func TestSwarmLeaveErrors(t *testing.T) {
@ -26,7 +26,7 @@ func TestSwarmLeaveErrors(t *testing.T) {
{ {
name: "leave-failed", name: "leave-failed",
swarmLeaveFunc: func() error { swarmLeaveFunc: func() error {
return fmt.Errorf("error leaving the swarm") return errors.Errorf("error leaving the swarm")
}, },
expectedError: "error leaving the swarm", expectedError: "error leaving the swarm",
}, },

View File

@ -2,13 +2,13 @@ package swarm
import ( import (
"encoding/csv" "encoding/csv"
"errors"
"fmt" "fmt"
"strings" "strings"
"time" "time"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
"github.com/pkg/errors"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -139,7 +139,7 @@ func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) {
parts := strings.SplitN(field, "=", 2) parts := strings.SplitN(field, "=", 2)
if len(parts) != 2 { if len(parts) != 2 {
return nil, fmt.Errorf("invalid field '%s' must be a key=value pair", field) return nil, errors.Errorf("invalid field '%s' must be a key=value pair", field)
} }
key, value := parts[0], parts[1] key, value := parts[0], parts[1]
@ -150,7 +150,7 @@ func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) {
if strings.ToLower(value) == string(swarm.ExternalCAProtocolCFSSL) { if strings.ToLower(value) == string(swarm.ExternalCAProtocolCFSSL) {
externalCA.Protocol = swarm.ExternalCAProtocolCFSSL externalCA.Protocol = swarm.ExternalCAProtocolCFSSL
} else { } else {
return nil, fmt.Errorf("unrecognized external CA protocol %s", value) return nil, errors.Errorf("unrecognized external CA protocol %s", value)
} }
case "url": case "url":
hasURL = true hasURL = true

View File

@ -2,8 +2,8 @@ package swarm
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"github.com/pkg/errors"
"io" "io"
"strings" "strings"

View File

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -36,7 +37,7 @@ func TestSwarmUnlockKeyErrors(t *testing.T) {
flagRotate: "true", flagRotate: "true",
}, },
swarmInspectFunc: func() (swarm.Swarm, error) { swarmInspectFunc: func() (swarm.Swarm, error) {
return swarm.Swarm{}, fmt.Errorf("error inspecting the swarm") return swarm.Swarm{}, errors.Errorf("error inspecting the swarm")
}, },
expectedError: "error inspecting the swarm", expectedError: "error inspecting the swarm",
}, },
@ -59,14 +60,14 @@ func TestSwarmUnlockKeyErrors(t *testing.T) {
return *Swarm(Autolock()), nil return *Swarm(Autolock()), nil
}, },
swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error { swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error {
return fmt.Errorf("error updating the swarm") return errors.Errorf("error updating the swarm")
}, },
expectedError: "error updating the swarm", expectedError: "error updating the swarm",
}, },
{ {
name: "swarm-get-unlock-key-failed", name: "swarm-get-unlock-key-failed",
swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) {
return types.SwarmUnlockKeyResponse{}, fmt.Errorf("error getting unlock key") return types.SwarmUnlockKeyResponse{}, errors.Errorf("error getting unlock key")
}, },
expectedError: "error getting unlock key", expectedError: "error getting unlock key",
}, },

View File

@ -2,7 +2,6 @@ package swarm
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
@ -11,6 +10,7 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/pkg/errors"
) )
func TestSwarmUnlockErrors(t *testing.T) { func TestSwarmUnlockErrors(t *testing.T) {
@ -59,7 +59,7 @@ func TestSwarmUnlockErrors(t *testing.T) {
}, nil }, nil
}, },
swarmUnlockFunc: func(req swarm.UnlockRequest) error { swarmUnlockFunc: func(req swarm.UnlockRequest) error {
return fmt.Errorf("error unlocking the swarm") return errors.Errorf("error unlocking the swarm")
}, },
expectedError: "error unlocking the swarm", expectedError: "error unlocking the swarm",
}, },
@ -90,7 +90,7 @@ func TestSwarmUnlock(t *testing.T) {
}, },
swarmUnlockFunc: func(req swarm.UnlockRequest) error { swarmUnlockFunc: func(req swarm.UnlockRequest) error {
if req.UnlockKey != input { if req.UnlockKey != input {
return fmt.Errorf("Invalid unlock key") return errors.Errorf("Invalid unlock key")
} }
return nil return nil
}, },

View File

@ -10,6 +10,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -37,7 +38,7 @@ func TestSwarmUpdateErrors(t *testing.T) {
flagTaskHistoryLimit: "10", flagTaskHistoryLimit: "10",
}, },
swarmInspectFunc: func() (swarm.Swarm, error) { swarmInspectFunc: func() (swarm.Swarm, error) {
return swarm.Swarm{}, fmt.Errorf("error inspecting the swarm") return swarm.Swarm{}, errors.Errorf("error inspecting the swarm")
}, },
expectedError: "error inspecting the swarm", expectedError: "error inspecting the swarm",
}, },
@ -47,7 +48,7 @@ func TestSwarmUpdateErrors(t *testing.T) {
flagTaskHistoryLimit: "10", flagTaskHistoryLimit: "10",
}, },
swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error { swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error {
return fmt.Errorf("error updating the swarm") return errors.Errorf("error updating the swarm")
}, },
expectedError: "error updating the swarm", expectedError: "error updating the swarm",
}, },
@ -60,7 +61,7 @@ func TestSwarmUpdateErrors(t *testing.T) {
return *Swarm(), nil return *Swarm(), nil
}, },
swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) { swarmGetUnlockKeyFunc: func() (types.SwarmUnlockKeyResponse, error) {
return types.SwarmUnlockKeyResponse{}, fmt.Errorf("error getting unlock key") return types.SwarmUnlockKeyResponse{}, errors.Errorf("error getting unlock key")
}, },
expectedError: "error getting unlock key", expectedError: "error getting unlock key",
}, },
@ -108,33 +109,33 @@ func TestSwarmUpdate(t *testing.T) {
}, },
swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error { swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error {
if *swarm.Orchestration.TaskHistoryRetentionLimit != 10 { if *swarm.Orchestration.TaskHistoryRetentionLimit != 10 {
return fmt.Errorf("historyLimit not correctly set") return errors.Errorf("historyLimit not correctly set")
} }
heartbeatDuration, err := time.ParseDuration("10s") heartbeatDuration, err := time.ParseDuration("10s")
if err != nil { if err != nil {
return err return err
} }
if swarm.Dispatcher.HeartbeatPeriod != heartbeatDuration { if swarm.Dispatcher.HeartbeatPeriod != heartbeatDuration {
return fmt.Errorf("heartbeatPeriodLimit not correctly set") return errors.Errorf("heartbeatPeriodLimit not correctly set")
} }
certExpiryDuration, err := time.ParseDuration("20s") certExpiryDuration, err := time.ParseDuration("20s")
if err != nil { if err != nil {
return err return err
} }
if swarm.CAConfig.NodeCertExpiry != certExpiryDuration { if swarm.CAConfig.NodeCertExpiry != certExpiryDuration {
return fmt.Errorf("certExpiry not correctly set") return errors.Errorf("certExpiry not correctly set")
} }
if len(swarm.CAConfig.ExternalCAs) != 1 { if len(swarm.CAConfig.ExternalCAs) != 1 {
return fmt.Errorf("externalCA not correctly set") return errors.Errorf("externalCA not correctly set")
} }
if *swarm.Raft.KeepOldSnapshots != 10 { if *swarm.Raft.KeepOldSnapshots != 10 {
return fmt.Errorf("keepOldSnapshots not correctly set") return errors.Errorf("keepOldSnapshots not correctly set")
} }
if swarm.Raft.SnapshotInterval != 100 { if swarm.Raft.SnapshotInterval != 100 {
return fmt.Errorf("snapshotInterval not correctly set") return errors.Errorf("snapshotInterval not correctly set")
} }
if !swarm.EncryptionConfig.AutoLockManagers { if !swarm.EncryptionConfig.AutoLockManagers {
return fmt.Errorf("autolock not correctly set") return errors.Errorf("autolock not correctly set")
} }
return nil return nil
}, },
@ -147,7 +148,7 @@ func TestSwarmUpdate(t *testing.T) {
}, },
swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error { swarmUpdateFunc: func(swarm swarm.Spec, flags swarm.UpdateFlags) error {
if *swarm.Orchestration.TaskHistoryRetentionLimit != 10 { if *swarm.Orchestration.TaskHistoryRetentionLimit != 10 {
return fmt.Errorf("historyLimit not correctly set") return errors.Errorf("historyLimit not correctly set")
} }
return nil return nil
}, },

View File

@ -10,6 +10,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/cli/command/inspect" "github.com/docker/docker/cli/command/inspect"
apiclient "github.com/docker/docker/client" apiclient "github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -48,7 +49,7 @@ func runInspect(dockerCli *command.DockerCli, opts inspectOptions) error {
case "", "container", "image", "node", "network", "service", "volume", "task", "plugin": case "", "container", "image", "node", "network", "service", "volume", "task", "plugin":
elementSearcher = inspectAll(context.Background(), dockerCli, opts.size, opts.inspectType) elementSearcher = inspectAll(context.Background(), dockerCli, opts.size, opts.inspectType)
default: default:
return fmt.Errorf("%q is not a valid value for --type", opts.inspectType) return errors.Errorf("%q is not a valid value for --type", opts.inspectType)
} }
return inspect.Inspect(dockerCli.Out(), opts.ids, opts.format, elementSearcher) return inspect.Inspect(dockerCli.Out(), opts.ids, opts.format, elementSearcher)
} }
@ -198,6 +199,6 @@ func inspectAll(ctx context.Context, dockerCli *command.DockerCli, getSize bool,
} }
return v, raw, err return v, raw, err
} }
return nil, nil, fmt.Errorf("Error: No such object: %s", ref) return nil, nil, errors.Errorf("Error: No such object: %s", ref)
} }
} }

View File

@ -8,6 +8,7 @@ import (
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
runconfigopts "github.com/docker/docker/runconfig/opts" runconfigopts "github.com/docker/docker/runconfig/opts"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -32,7 +33,7 @@ func newCreateCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 1 { if len(args) == 1 {
if opts.name != "" { if opts.name != "" {
return fmt.Errorf("Conflicting options: either specify --name or provide positional arg, not both\n") return errors.Errorf("Conflicting options: either specify --name or provide positional arg, not both\n")
} }
opts.name = args[0] opts.name = args[0]
} }

View File

@ -2,7 +2,6 @@ package volume
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
@ -11,6 +10,7 @@ import (
volumetypes "github.com/docker/docker/api/types/volume" volumetypes "github.com/docker/docker/api/types/volume"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/pkg/errors"
) )
func TestVolumeCreateErrors(t *testing.T) { func TestVolumeCreateErrors(t *testing.T) {
@ -33,7 +33,7 @@ func TestVolumeCreateErrors(t *testing.T) {
}, },
{ {
volumeCreateFunc: func(createBody volumetypes.VolumesCreateBody) (types.Volume, error) { volumeCreateFunc: func(createBody volumetypes.VolumesCreateBody) (types.Volume, error) {
return types.Volume{}, fmt.Errorf("error creating volume") return types.Volume{}, errors.Errorf("error creating volume")
}, },
expectedError: "error creating volume", expectedError: "error creating volume",
}, },
@ -60,7 +60,7 @@ func TestVolumeCreateWithName(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) { volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) {
if body.Name != name { if body.Name != name {
return types.Volume{}, fmt.Errorf("expected name %q, got %q", name, body.Name) return types.Volume{}, errors.Errorf("expected name %q, got %q", name, body.Name)
} }
return types.Volume{ return types.Volume{
Name: body.Name, Name: body.Name,
@ -98,16 +98,16 @@ func TestVolumeCreateWithFlags(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) { volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) {
if body.Name != "" { if body.Name != "" {
return types.Volume{}, fmt.Errorf("expected empty name, got %q", body.Name) return types.Volume{}, errors.Errorf("expected empty name, got %q", body.Name)
} }
if body.Driver != expectedDriver { if body.Driver != expectedDriver {
return types.Volume{}, fmt.Errorf("expected driver %q, got %q", expectedDriver, body.Driver) return types.Volume{}, errors.Errorf("expected driver %q, got %q", expectedDriver, body.Driver)
} }
if !compareMap(body.DriverOpts, expectedOpts) { if !compareMap(body.DriverOpts, expectedOpts) {
return types.Volume{}, fmt.Errorf("expected drivers opts %v, got %v", expectedOpts, body.DriverOpts) return types.Volume{}, errors.Errorf("expected drivers opts %v, got %v", expectedOpts, body.DriverOpts)
} }
if !compareMap(body.Labels, expectedLabels) { if !compareMap(body.Labels, expectedLabels) {
return types.Volume{}, fmt.Errorf("expected labels %v, got %v", expectedLabels, body.Labels) return types.Volume{}, errors.Errorf("expected labels %v, got %v", expectedLabels, body.Labels)
} }
return types.Volume{ return types.Volume{
Name: name, Name: name,

View File

@ -8,6 +8,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -27,7 +28,7 @@ func TestVolumeInspectErrors(t *testing.T) {
{ {
args: []string{"foo"}, args: []string{"foo"},
volumeInspectFunc: func(volumeID string) (types.Volume, error) { volumeInspectFunc: func(volumeID string) (types.Volume, error) {
return types.Volume{}, fmt.Errorf("error while inspecting the volume") return types.Volume{}, errors.Errorf("error while inspecting the volume")
}, },
expectedError: "error while inspecting the volume", expectedError: "error while inspecting the volume",
}, },
@ -46,7 +47,7 @@ func TestVolumeInspectErrors(t *testing.T) {
Name: "foo", Name: "foo",
}, nil }, nil
} }
return types.Volume{}, fmt.Errorf("error while inspecting the volume") return types.Volume{}, errors.Errorf("error while inspecting the volume")
}, },
expectedError: "error while inspecting the volume", expectedError: "error while inspecting the volume",
}, },
@ -78,7 +79,7 @@ func TestVolumeInspectWithoutFormat(t *testing.T) {
args: []string{"foo"}, args: []string{"foo"},
volumeInspectFunc: func(volumeID string) (types.Volume, error) { volumeInspectFunc: func(volumeID string) (types.Volume, error) {
if volumeID != "foo" { if volumeID != "foo" {
return types.Volume{}, fmt.Errorf("Invalid volumeID, expected %s, got %s", "foo", volumeID) return types.Volume{}, errors.Errorf("Invalid volumeID, expected %s, got %s", "foo", volumeID)
} }
return *Volume(), nil return *Volume(), nil
}, },

View File

@ -2,7 +2,6 @@ package volume
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -11,6 +10,7 @@ import (
volumetypes "github.com/docker/docker/api/types/volume" volumetypes "github.com/docker/docker/api/types/volume"
"github.com/docker/docker/cli/config/configfile" "github.com/docker/docker/cli/config/configfile"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/docker/cli/internal/test/builders" . "github.com/docker/docker/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
@ -30,7 +30,7 @@ func TestVolumeListErrors(t *testing.T) {
}, },
{ {
volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) { volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) {
return volumetypes.VolumesListOKBody{}, fmt.Errorf("error listing volumes") return volumetypes.VolumesListOKBody{}, errors.Errorf("error listing volumes")
}, },
expectedError: "error listing volumes", expectedError: "error listing volumes",
}, },

View File

@ -13,6 +13,7 @@ import (
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/docker/docker/pkg/testutil/golden" "github.com/docker/docker/pkg/testutil/golden"
"github.com/pkg/errors"
) )
func TestVolumePruneErrors(t *testing.T) { func TestVolumePruneErrors(t *testing.T) {
@ -31,7 +32,7 @@ func TestVolumePruneErrors(t *testing.T) {
"force": "true", "force": "true",
}, },
volumePruneFunc: func(args filters.Args) (types.VolumesPruneReport, error) { volumePruneFunc: func(args filters.Args) (types.VolumesPruneReport, error) {
return types.VolumesPruneReport{}, fmt.Errorf("error pruning volumes") return types.VolumesPruneReport{}, errors.Errorf("error pruning volumes")
}, },
expectedError: "error pruning volumes", expectedError: "error pruning volumes",
}, },

View File

@ -6,6 +6,7 @@ import (
"github.com/docker/docker/cli" "github.com/docker/docker/cli"
"github.com/docker/docker/cli/command" "github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -53,7 +54,7 @@ func runRemove(dockerCli command.Cli, opts *removeOptions) error {
} }
if len(errs) > 0 { if len(errs) > 0 {
return fmt.Errorf("%s", strings.Join(errs, "\n")) return errors.Errorf("%s", strings.Join(errs, "\n"))
} }
return nil return nil
} }

View File

@ -2,12 +2,12 @@ package volume
import ( import (
"bytes" "bytes"
"fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/docker/cli/internal/test" "github.com/docker/docker/cli/internal/test"
"github.com/docker/docker/pkg/testutil/assert" "github.com/docker/docker/pkg/testutil/assert"
"github.com/pkg/errors"
) )
func TestVolumeRemoveErrors(t *testing.T) { func TestVolumeRemoveErrors(t *testing.T) {
@ -22,7 +22,7 @@ func TestVolumeRemoveErrors(t *testing.T) {
{ {
args: []string{"nodeID"}, args: []string{"nodeID"},
volumeRemoveFunc: func(volumeID string, force bool) error { volumeRemoveFunc: func(volumeID string, force bool) error {
return fmt.Errorf("error removing the volume") return errors.Errorf("error removing the volume")
}, },
expectedError: "error removing the volume", expectedError: "error removing the volume",
}, },

View File

@ -261,7 +261,7 @@ func convertHealthcheck(healthcheck *composetypes.HealthCheckConfig) (*container
) )
if healthcheck.Disable { if healthcheck.Disable {
if len(healthcheck.Test) != 0 { if len(healthcheck.Test) != 0 {
return nil, fmt.Errorf("test and disable can't be set at the same time") return nil, errors.Errorf("test and disable can't be set at the same time")
} }
return &container.HealthConfig{ return &container.HealthConfig{
Test: []string{"NONE"}, Test: []string{"NONE"},
@ -312,7 +312,7 @@ func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*
MaxAttempts: &attempts, MaxAttempts: &attempts,
}, nil }, nil
default: default:
return nil, fmt.Errorf("unknown restart policy: %s", restart) return nil, errors.Errorf("unknown restart policy: %s", restart)
} }
} }
return &swarm.RestartPolicy{ return &swarm.RestartPolicy{
@ -418,13 +418,13 @@ func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error)
switch mode { switch mode {
case "global": case "global":
if replicas != nil { if replicas != nil {
return serviceMode, fmt.Errorf("replicas can only be used with replicated mode") return serviceMode, errors.Errorf("replicas can only be used with replicated mode")
} }
serviceMode.Global = &swarm.GlobalService{} serviceMode.Global = &swarm.GlobalService{}
case "replicated", "": case "replicated", "":
serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas} serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
default: default:
return serviceMode, fmt.Errorf("Unknown mode: %s", mode) return serviceMode, errors.Errorf("Unknown mode: %s", mode)
} }
return serviceMode, nil return serviceMode, nil
} }

View File

@ -36,7 +36,7 @@ func ParseYAML(source []byte) (map[string]interface{}, error) {
} }
cfgMap, ok := cfg.(map[interface{}]interface{}) cfgMap, ok := cfg.(map[interface{}]interface{})
if !ok { if !ok {
return nil, fmt.Errorf("Top-level object must be a mapping") return nil, errors.Errorf("Top-level object must be a mapping")
} }
converted, err := convertToStringKeysRecursive(cfgMap, "") converted, err := convertToStringKeysRecursive(cfgMap, "")
if err != nil { if err != nil {
@ -48,10 +48,10 @@ func ParseYAML(source []byte) (map[string]interface{}, error) {
// Load reads a ConfigDetails and returns a fully loaded configuration // Load reads a ConfigDetails and returns a fully loaded configuration
func Load(configDetails types.ConfigDetails) (*types.Config, error) { func Load(configDetails types.ConfigDetails) (*types.Config, error) {
if len(configDetails.ConfigFiles) < 1 { if len(configDetails.ConfigFiles) < 1 {
return nil, fmt.Errorf("No files specified") return nil, errors.Errorf("No files specified")
} }
if len(configDetails.ConfigFiles) > 1 { if len(configDetails.ConfigFiles) > 1 {
return nil, fmt.Errorf("Multiple files are not yet supported") return nil, errors.Errorf("Multiple files are not yet supported")
} }
configDict := getConfigDict(configDetails) configDict := getConfigDict(configDetails)
@ -310,7 +310,7 @@ func formatInvalidKeyError(keyPrefix string, key interface{}) error {
} else { } else {
location = fmt.Sprintf("in %s", keyPrefix) location = fmt.Sprintf("in %s", keyPrefix)
} }
return fmt.Errorf("Non-string key %s: %#v", location, key) return errors.Errorf("Non-string key %s: %#v", location, key)
} }
// LoadServices produces a ServiceConfig map from a compose file Dict // LoadServices produces a ServiceConfig map from a compose file Dict
@ -415,7 +415,7 @@ func transformUlimits(data interface{}) (interface{}, error) {
ulimit.Hard = value["hard"].(int) ulimit.Hard = value["hard"].(int)
return ulimit, nil return ulimit, nil
default: default:
return data, fmt.Errorf("invalid type %T for ulimits", value) return data, errors.Errorf("invalid type %T for ulimits", value)
} }
} }
@ -503,7 +503,7 @@ func transformMapStringString(data interface{}) (interface{}, error) {
case map[string]string: case map[string]string:
return value, nil return value, nil
default: default:
return data, fmt.Errorf("invalid type %T for map[string]string", value) return data, errors.Errorf("invalid type %T for map[string]string", value)
} }
} }
@ -514,7 +514,7 @@ func transformExternal(data interface{}) (interface{}, error) {
case map[string]interface{}: case map[string]interface{}:
return map[string]interface{}{"external": true, "name": value["name"]}, nil return map[string]interface{}{"external": true, "name": value["name"]}, nil
default: default:
return data, fmt.Errorf("invalid type %T for external", value) return data, errors.Errorf("invalid type %T for external", value)
} }
} }
@ -542,12 +542,12 @@ func transformServicePort(data interface{}) (interface{}, error) {
case map[string]interface{}: case map[string]interface{}:
ports = append(ports, value) ports = append(ports, value)
default: default:
return data, fmt.Errorf("invalid type %T for port", value) return data, errors.Errorf("invalid type %T for port", value)
} }
} }
return ports, nil return ports, nil
default: default:
return data, fmt.Errorf("invalid type %T for port", entries) return data, errors.Errorf("invalid type %T for port", entries)
} }
} }
@ -558,7 +558,7 @@ func transformServiceSecret(data interface{}) (interface{}, error) {
case map[string]interface{}: case map[string]interface{}:
return data, nil return data, nil
default: default:
return data, fmt.Errorf("invalid type %T for secret", value) return data, errors.Errorf("invalid type %T for secret", value)
} }
} }
@ -569,7 +569,7 @@ func transformServiceVolumeConfig(data interface{}) (interface{}, error) {
case map[string]interface{}: case map[string]interface{}:
return data, nil return data, nil
default: default:
return data, fmt.Errorf("invalid type %T for service volume", value) return data, errors.Errorf("invalid type %T for service volume", value)
} }
} }
@ -601,7 +601,7 @@ func transformStringList(data interface{}) (interface{}, error) {
case []interface{}: case []interface{}:
return value, nil return value, nil
default: default:
return data, fmt.Errorf("invalid type %T for string list", value) return data, errors.Errorf("invalid type %T for string list", value)
} }
} }
@ -625,7 +625,7 @@ func transformMappingOrList(mappingOrList interface{}, sep string, allowNil bool
} }
return result return result
} }
panic(fmt.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList)) panic(errors.Errorf("expected a map or a list, got %T: %#v", mappingOrList, mappingOrList))
} }
func transformShellCommand(value interface{}) (interface{}, error) { func transformShellCommand(value interface{}) (interface{}, error) {
@ -642,7 +642,7 @@ func transformHealthCheckTest(data interface{}) (interface{}, error) {
case []interface{}: case []interface{}:
return value, nil return value, nil
default: default:
return value, fmt.Errorf("invalid type %T for healthcheck.test", value) return value, errors.Errorf("invalid type %T for healthcheck.test", value)
} }
} }
@ -653,7 +653,7 @@ func transformSize(value interface{}) (int64, error) {
case string: case string:
return units.RAMInBytes(value) return units.RAMInBytes(value)
} }
panic(fmt.Errorf("invalid type for size %T", value)) panic(errors.Errorf("invalid type for size %T", value))
} }
func toServicePortConfigs(value string) ([]interface{}, error) { func toServicePortConfigs(value string) ([]interface{}, error) {

View File

@ -10,19 +10,20 @@ package schema
import ( import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
) )
func bindataRead(data []byte, name string) ([]byte, error) { func bindataRead(data []byte, name string) ([]byte, error) {
gz, err := gzip.NewReader(bytes.NewBuffer(data)) gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil { if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err) return nil, errors.Errorf("Read %q: %v", name, err)
} }
var buf bytes.Buffer var buf bytes.Buffer
@ -30,7 +31,7 @@ func bindataRead(data []byte, name string) ([]byte, error) {
clErr := gz.Close() clErr := gz.Close()
if err != nil { if err != nil {
return nil, fmt.Errorf("Read %q: %v", name, err) return nil, errors.Errorf("Read %q: %v", name, err)
} }
if clErr != nil { if clErr != nil {
return nil, err return nil, err
@ -138,11 +139,11 @@ func Asset(name string) ([]byte, error) {
if f, ok := _bindata[cannonicalName]; ok { if f, ok := _bindata[cannonicalName]; ok {
a, err := f() a, err := f()
if err != nil { if err != nil {
return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) return nil, errors.Errorf("Asset %s can't read by error: %v", name, err)
} }
return a.bytes, nil return a.bytes, nil
} }
return nil, fmt.Errorf("Asset %s not found", name) return nil, errors.Errorf("Asset %s not found", name)
} }
// MustAsset is like Asset but panics when Asset would return an error. // MustAsset is like Asset but panics when Asset would return an error.
@ -164,11 +165,11 @@ func AssetInfo(name string) (os.FileInfo, error) {
if f, ok := _bindata[cannonicalName]; ok { if f, ok := _bindata[cannonicalName]; ok {
a, err := f() a, err := f()
if err != nil { if err != nil {
return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) return nil, errors.Errorf("AssetInfo %s can't read by error: %v", name, err)
} }
return a.info, nil return a.info, nil
} }
return nil, fmt.Errorf("AssetInfo %s not found", name) return nil, errors.Errorf("AssetInfo %s not found", name)
} }
// AssetNames returns the names of the assets. // AssetNames returns the names of the assets.
@ -208,12 +209,12 @@ func AssetDir(name string) ([]string, error) {
for _, p := range pathList { for _, p := range pathList {
node = node.Children[p] node = node.Children[p]
if node == nil { if node == nil {
return nil, fmt.Errorf("Asset %s not found", name) return nil, errors.Errorf("Asset %s not found", name)
} }
} }
} }
if node.Func != nil { if node.Func != nil {
return nil, fmt.Errorf("Asset %s not found", name) return nil, errors.Errorf("Asset %s not found", name)
} }
rv := make([]string, 0, len(node.Children)) rv := make([]string, 0, len(node.Children))
for childName := range node.Children { for childName := range node.Children {
@ -226,6 +227,7 @@ type bintree struct {
Func func() (*asset, error) Func func() (*asset, error)
Children map[string]*bintree Children map[string]*bintree
} }
var _bintree = &bintree{nil, map[string]*bintree{ var _bintree = &bintree{nil, map[string]*bintree{
"data": &bintree{nil, map[string]*bintree{ "data": &bintree{nil, map[string]*bintree{
"config_schema_v3.0.json": &bintree{dataConfig_schema_v30Json, map[string]*bintree{}}, "config_schema_v3.0.json": &bintree{dataConfig_schema_v30Json, map[string]*bintree{}},
@ -280,4 +282,3 @@ func _filePath(dir, name string) string {
cannonicalName := strings.Replace(name, "\\", "/", -1) cannonicalName := strings.Replace(name, "\\", "/", -1)
return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...)
} }

View File

@ -1,7 +1,6 @@
package config package config
import ( import (
"fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -9,6 +8,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/cli/config/configfile" "github.com/docker/docker/cli/config/configfile"
"github.com/docker/docker/pkg/homedir" "github.com/docker/docker/pkg/homedir"
"github.com/pkg/errors"
) )
const ( const (
@ -84,18 +84,18 @@ func Load(configDir string) (*configfile.ConfigFile, error) {
if _, err := os.Stat(configFile.Filename); err == nil { if _, err := os.Stat(configFile.Filename); err == nil {
file, err := os.Open(configFile.Filename) file, err := os.Open(configFile.Filename)
if err != nil { if err != nil {
return &configFile, fmt.Errorf("%s - %v", configFile.Filename, err) return &configFile, errors.Errorf("%s - %v", configFile.Filename, err)
} }
defer file.Close() defer file.Close()
err = configFile.LoadFromReader(file) err = configFile.LoadFromReader(file)
if err != nil { if err != nil {
err = fmt.Errorf("%s - %v", configFile.Filename, err) err = errors.Errorf("%s - %v", configFile.Filename, err)
} }
return &configFile, err return &configFile, err
} else if !os.IsNotExist(err) { } else if !os.IsNotExist(err) {
// if file is there but we can't stat it for any reason other // if file is there but we can't stat it for any reason other
// than it doesn't exist then stop // than it doesn't exist then stop
return &configFile, fmt.Errorf("%s - %v", configFile.Filename, err) return &configFile, errors.Errorf("%s - %v", configFile.Filename, err)
} }
// Can't find latest config file so check for the old one // Can't find latest config file so check for the old one
@ -105,12 +105,12 @@ func Load(configDir string) (*configfile.ConfigFile, error) {
} }
file, err := os.Open(confFile) file, err := os.Open(confFile)
if err != nil { if err != nil {
return &configFile, fmt.Errorf("%s - %v", confFile, err) return &configFile, errors.Errorf("%s - %v", confFile, err)
} }
defer file.Close() defer file.Close()
err = configFile.LegacyLoadFromReader(file) err = configFile.LegacyLoadFromReader(file)
if err != nil { if err != nil {
return &configFile, fmt.Errorf("%s - %v", confFile, err) return &configFile, errors.Errorf("%s - %v", confFile, err)
} }
if configFile.HTTPHeaders == nil { if configFile.HTTPHeaders == nil {

View File

@ -3,7 +3,6 @@ package configfile
import ( import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
@ -11,6 +10,7 @@ import (
"strings" "strings"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/pkg/errors"
) )
const ( const (
@ -51,12 +51,12 @@ func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error {
if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil { if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil {
arr := strings.Split(string(b), "\n") arr := strings.Split(string(b), "\n")
if len(arr) < 2 { if len(arr) < 2 {
return fmt.Errorf("The Auth config file is empty") return errors.Errorf("The Auth config file is empty")
} }
authConfig := types.AuthConfig{} authConfig := types.AuthConfig{}
origAuth := strings.Split(arr[0], " = ") origAuth := strings.Split(arr[0], " = ")
if len(origAuth) != 2 { if len(origAuth) != 2 {
return fmt.Errorf("Invalid Auth config file") return errors.Errorf("Invalid Auth config file")
} }
authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1]) authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
if err != nil { if err != nil {
@ -135,7 +135,7 @@ func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error {
// Save encodes and writes out all the authorization information // Save encodes and writes out all the authorization information
func (configFile *ConfigFile) Save() error { func (configFile *ConfigFile) Save() error {
if configFile.Filename == "" { if configFile.Filename == "" {
return fmt.Errorf("Can't save config with empty filename") return errors.Errorf("Can't save config with empty filename")
} }
if err := os.MkdirAll(filepath.Dir(configFile.Filename), 0700); err != nil { if err := os.MkdirAll(filepath.Dir(configFile.Filename), 0700); err != nil {
@ -176,11 +176,11 @@ func decodeAuth(authStr string) (string, string, error) {
return "", "", err return "", "", err
} }
if n > decLen { if n > decLen {
return "", "", fmt.Errorf("Something went wrong decoding auth config") return "", "", errors.Errorf("Something went wrong decoding auth config")
} }
arr := strings.SplitN(string(decoded), ":", 2) arr := strings.SplitN(string(decoded), ":", 2)
if len(arr) != 2 { if len(arr) != 2 {
return "", "", fmt.Errorf("Invalid auth configuration file") return "", "", errors.Errorf("Invalid auth configuration file")
} }
password := strings.Trim(arr[1], "\x00") password := strings.Trim(arr[1], "\x00")
return arr[0], password, nil return arr[0], password, nil

View File

@ -11,6 +11,7 @@ import (
"github.com/docker/docker-credential-helpers/client" "github.com/docker/docker-credential-helpers/client"
"github.com/docker/docker-credential-helpers/credentials" "github.com/docker/docker-credential-helpers/credentials"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/pkg/errors"
) )
const ( const (
@ -20,7 +21,7 @@ const (
missingCredsAddress = "https://missing.docker.io/v1" missingCredsAddress = "https://missing.docker.io/v1"
) )
var errCommandExited = fmt.Errorf("exited 1") var errCommandExited = errors.Errorf("exited 1")
// mockCommand simulates interactions between the docker client and a remote // mockCommand simulates interactions between the docker client and a remote
// credentials helper. // credentials helper.

View File

@ -1,9 +1,9 @@
package cli package cli
import ( import (
"fmt"
"strings" "strings"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -14,10 +14,10 @@ func NoArgs(cmd *cobra.Command, args []string) error {
} }
if cmd.HasSubCommands() { if cmd.HasSubCommands() {
return fmt.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n")) return errors.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n"))
} }
return fmt.Errorf( return errors.Errorf(
"\"%s\" accepts no argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", "\"%s\" accepts no argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(), cmd.CommandPath(),
cmd.CommandPath(), cmd.CommandPath(),
@ -32,7 +32,7 @@ func RequiresMinArgs(min int) cobra.PositionalArgs {
if len(args) >= min { if len(args) >= min {
return nil return nil
} }
return fmt.Errorf( return errors.Errorf(
"\"%s\" requires at least %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", "\"%s\" requires at least %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(), cmd.CommandPath(),
min, min,
@ -49,7 +49,7 @@ func RequiresMaxArgs(max int) cobra.PositionalArgs {
if len(args) <= max { if len(args) <= max {
return nil return nil
} }
return fmt.Errorf( return errors.Errorf(
"\"%s\" requires at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", "\"%s\" requires at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(), cmd.CommandPath(),
max, max,
@ -66,7 +66,7 @@ func RequiresRangeArgs(min int, max int) cobra.PositionalArgs {
if len(args) >= min && len(args) <= max { if len(args) >= min && len(args) <= max {
return nil return nil
} }
return fmt.Errorf( return errors.Errorf(
"\"%s\" requires at least %d and at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", "\"%s\" requires at least %d and at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(), cmd.CommandPath(),
min, min,
@ -84,7 +84,7 @@ func ExactArgs(number int) cobra.PositionalArgs {
if len(args) == number { if len(args) == number {
return nil return nil
} }
return fmt.Errorf( return errors.Errorf(
"\"%s\" requires exactly %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", "\"%s\" requires exactly %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(), cmd.CommandPath(),
number, number,

View File

@ -2,7 +2,6 @@ package trust
import ( import (
"encoding/json" "encoding/json"
"fmt"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -29,6 +28,7 @@ import (
"github.com/docker/notary/trustpinning" "github.com/docker/notary/trustpinning"
"github.com/docker/notary/tuf/data" "github.com/docker/notary/tuf/data"
"github.com/docker/notary/tuf/signed" "github.com/docker/notary/tuf/signed"
"github.com/pkg/errors"
) )
var ( var (
@ -57,7 +57,7 @@ func Server(index *registrytypes.IndexInfo) (string, error) {
if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" { if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" {
urlObj, err := url.Parse(s) urlObj, err := url.Parse(s)
if err != nil || urlObj.Scheme != "https" { if err != nil || urlObj.Scheme != "https" {
return "", fmt.Errorf("valid https URL required for trust server, got %s", s) return "", errors.Errorf("valid https URL required for trust server, got %s", s)
} }
return s, nil return s, nil
@ -205,27 +205,27 @@ func NotaryError(repoName string, err error) error {
switch err.(type) { switch err.(type) {
case *json.SyntaxError: case *json.SyntaxError:
logrus.Debugf("Notary syntax error: %s", err) logrus.Debugf("Notary syntax error: %s", err)
return fmt.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName) return errors.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName)
case signed.ErrExpired: case signed.ErrExpired:
return fmt.Errorf("Error: remote repository %s out-of-date: %v", repoName, err) return errors.Errorf("Error: remote repository %s out-of-date: %v", repoName, err)
case trustmanager.ErrKeyNotFound: case trustmanager.ErrKeyNotFound:
return fmt.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err) return errors.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err)
case storage.NetworkError: case storage.NetworkError:
return fmt.Errorf("Error: error contacting notary server: %v", err) return errors.Errorf("Error: error contacting notary server: %v", err)
case storage.ErrMetaNotFound: case storage.ErrMetaNotFound:
return fmt.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err) return errors.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err)
case trustpinning.ErrRootRotationFail, trustpinning.ErrValidationFail, signed.ErrInvalidKeyType: case trustpinning.ErrRootRotationFail, trustpinning.ErrValidationFail, signed.ErrInvalidKeyType:
return fmt.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err) return errors.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err)
case signed.ErrNoKeys: case signed.ErrNoKeys:
return fmt.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err) return errors.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err)
case signed.ErrLowVersion: case signed.ErrLowVersion:
return fmt.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err) return errors.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err)
case signed.ErrRoleThreshold: case signed.ErrRoleThreshold:
return fmt.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err) return errors.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err)
case client.ErrRepositoryNotExist: case client.ErrRepositoryNotExist:
return fmt.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err) return errors.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err)
case signed.ErrInsufficientSignatures: case signed.ErrInsufficientSignatures:
return fmt.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err) return errors.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err)
} }
return err return err