Merge pull request #3794 from thaJeztah/use_gofumpt

format code with gofumpt
This commit is contained in:
Sebastiaan van Stijn 2022-09-30 13:50:51 +02:00 committed by GitHub
commit 65438e008c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
93 changed files with 199 additions and 177 deletions

View File

@ -10,9 +10,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var ( var pluginNameRe = regexp.MustCompile("^[a-z][a-z0-9]*$")
pluginNameRe = regexp.MustCompile("^[a-z][a-z0-9]*$")
)
// Plugin represents a potential plugin with all it's metadata. // Plugin represents a potential plugin with all it's metadata.
type Plugin struct { type Plugin struct {

View File

@ -6,6 +6,7 @@ package manager
func trimExeSuffix(s string) (string, error) { func trimExeSuffix(s string) (string, error) {
return s, nil return s, nil
} }
func addExeSuffix(s string) string { func addExeSuffix(s string) string {
return s return s
} }

View File

@ -33,7 +33,6 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
flags.StringVarP(&opts.checkpointDir, "checkpoint-dir", "", "", "Use a custom checkpoint storage directory") flags.StringVarP(&opts.checkpointDir, "checkpoint-dir", "", "", "Use a custom checkpoint storage directory")
return cmd return cmd
} }
func runList(dockerCli command.Cli, container string, opts listOptions) error { func runList(dockerCli command.Cli, container string, opts listOptions) error {

View File

@ -120,7 +120,7 @@ func (c *fakeClient) NegotiateAPIVersionPing(types.Ping) {
func TestInitializeFromClient(t *testing.T) { func TestInitializeFromClient(t *testing.T) {
defaultVersion := "v1.55" defaultVersion := "v1.55"
var testcases = []struct { testcases := []struct {
doc string doc string
pingFunc func() (types.Ping, error) pingFunc func() (types.Ping, error)
expectedServer ServerInfo expectedServer ServerInfo
@ -222,7 +222,7 @@ func TestInitializeFromClientHangs(t *testing.T) {
func TestExperimentalCLI(t *testing.T) { func TestExperimentalCLI(t *testing.T) {
defaultVersion := "v1.55" defaultVersion := "v1.55"
var testcases = []struct { testcases := []struct {
doc string doc string
configfile string configfile string
}{ }{

View File

@ -29,7 +29,8 @@ func TestConfigCreateErrors(t *testing.T) {
args: []string{"too_few"}, args: []string{"too_few"},
expectedError: "requires exactly 2 arguments", expectedError: "requires exactly 2 arguments",
}, },
{args: []string{"too", "many", "arguments"}, {
args: []string{"too", "many", "arguments"},
expectedError: "requires exactly 2 arguments", expectedError: "requires exactly 2 arguments",
}, },
{ {

View File

@ -26,29 +26,39 @@ func TestConfigContextFormatWrite(t *testing.T) {
`template parsing error: template: :1:2: executing "" at <nil>: nil is not a command`, `template parsing error: template: :1:2: executing "" at <nil>: nil is not a command`,
}, },
// Table format // Table format
{formatter.Context{Format: NewFormat("table", false)}, {
formatter.Context{Format: NewFormat("table", false)},
`ID NAME CREATED UPDATED `ID NAME CREATED UPDATED
1 passwords Less than a second ago Less than a second ago 1 passwords Less than a second ago Less than a second ago
2 id_rsa Less than a second ago Less than a second ago 2 id_rsa Less than a second ago Less than a second ago
`}, `,
{formatter.Context{Format: NewFormat("table {{.Name}}", true)}, },
{
formatter.Context{Format: NewFormat("table {{.Name}}", true)},
`NAME `NAME
passwords passwords
id_rsa id_rsa
`}, `,
{formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)}, },
{
formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
`1-passwords `1-passwords
2-id_rsa 2-id_rsa
`}, `,
},
} }
configs := []swarm.Config{ configs := []swarm.Config{
{ID: "1", {
ID: "1",
Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()}, Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()},
Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "passwords"}}}, Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "passwords"}},
{ID: "2", },
{
ID: "2",
Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()}, Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()},
Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "id_rsa"}}}, Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "id_rsa"}},
},
} }
for _, tc := range cases { for _, tc := range cases {
tc := tc tc := tc

View File

@ -68,5 +68,4 @@ func RunConfigInspect(dockerCli command.Cli, opts InspectOptions) error {
return cli.StatusError{StatusCode: 1, Status: err.Error()} return cli.StatusError{StatusCode: 1, Status: err.Error()}
} }
return nil return nil
} }

View File

@ -17,7 +17,7 @@ import (
) )
func TestRunCopyWithInvalidArguments(t *testing.T) { func TestRunCopyWithInvalidArguments(t *testing.T) {
var testcases = []struct { testcases := []struct {
doc string doc string
options copyOptions options copyOptions
expectedErr string expectedErr string
@ -143,7 +143,7 @@ func TestRunCopyToContainerSourceDoesNotExist(t *testing.T) {
} }
func TestSplitCpArg(t *testing.T) { func TestSplitCpArg(t *testing.T) {
var testcases = []struct { testcases := []struct {
doc string doc string
path string path string
os string os string

View File

@ -158,7 +158,7 @@ func TestParseExecNoSuchFile(t *testing.T) {
} }
func TestRunExec(t *testing.T) { func TestRunExec(t *testing.T) {
var testcases = []struct { testcases := []struct {
doc string doc string
options ExecOptions options ExecOptions
client fakeClient client fakeClient

View File

@ -24,7 +24,6 @@ func NewDiffFormat(source string) formatter.Format {
// DiffFormatWrite writes formatted diff using the Context // DiffFormatWrite writes formatted diff using the Context
func DiffFormatWrite(ctx formatter.Context, changes []container.ContainerChangeResponseItem) error { func DiffFormatWrite(ctx formatter.Context, changes []container.ContainerChangeResponseItem) error {
render := func(format func(subContext formatter.SubContext) error) error { render := func(format func(subContext formatter.SubContext) error) error {
for _, change := range changes { for _, change := range changes {
if err := format(&diffContext{c: change}); err != nil { if err := format(&diffContext{c: change}); err != nil {
@ -65,7 +64,6 @@ func (d *diffContext) Type() string {
kind = "D" kind = "D"
} }
return kind return kind
} }
func (d *diffContext) Path() string { func (d *diffContext) Path() string {

View File

@ -26,7 +26,7 @@ func TestRunLogs(t *testing.T) {
}, nil }, nil
} }
var testcases = []struct { testcases := []struct {
doc string doc string
options *logsOptions options *logsOptions
client fakeClient client fakeClient

View File

@ -27,9 +27,7 @@ import (
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
var ( var deviceCgroupRuleRegexp = regexp.MustCompile(`^[acb] ([0-9]+|\*):([0-9]+|\*) [rwm]{1,3}$`)
deviceCgroupRuleRegexp = regexp.MustCompile(`^[acb] ([0-9]+|\*):([0-9]+|\*) [rwm]{1,3}$`)
)
// containerOptions is a data object with all the options for creating a container // containerOptions is a data object with all the options for creating a container
type containerOptions struct { type containerOptions struct {
@ -978,7 +976,7 @@ func validateDeviceCgroupRule(val string) (string, error) {
// validDeviceMode checks if the mode for device is valid or not. // validDeviceMode checks if the mode for device is valid or not.
// Valid mode is a composition of r (read), w (write), and m (mknod). // Valid mode is a composition of r (read), w (write), and m (mknod).
func validDeviceMode(mode string) bool { func validDeviceMode(mode string) bool {
var legalDeviceMode = map[rune]bool{ legalDeviceMode := map[rune]bool{
'r': true, 'r': true,
'w': true, 'w': true,
'm': true, 'm': true,

View File

@ -184,7 +184,6 @@ func TestParseRunWithInvalidArgs(t *testing.T) {
//nolint:gocyclo //nolint:gocyclo
func TestParseWithVolumes(t *testing.T) { func TestParseWithVolumes(t *testing.T) {
// A single volume // A single volume
arr, tryit := setupPlatformVolume([]string{`/tmp`}, []string{`c:\tmp`}) arr, tryit := setupPlatformVolume([]string{`/tmp`}, []string{`c:\tmp`})
if config, hostConfig := mustParse(t, tryit); hostConfig.Binds != nil { if config, hostConfig := mustParse(t, tryit); hostConfig.Binds != nil {
@ -252,7 +251,6 @@ func TestParseWithVolumes(t *testing.T) {
t.Fatalf("Error parsing %s. Should have a single bind mount and no volumes", arr[0]) t.Fatalf("Error parsing %s. Should have a single bind mount and no volumes", arr[0])
} }
} }
} }
// setupPlatformVolume takes two arrays of volume specs - a Unix style // setupPlatformVolume takes two arrays of volume specs - a Unix style
@ -453,7 +451,6 @@ func TestParseDevice(t *testing.T) {
t.Fatalf("Expected %v, got %v", deviceMapping, hostconfig.Devices) t.Fatalf("Expected %v, got %v", deviceMapping, hostconfig.Devices)
} }
} }
} }
func TestParseNetworkConfig(t *testing.T) { func TestParseNetworkConfig(t *testing.T) {
@ -956,7 +953,6 @@ func TestConvertToStandardNotation(t *testing.T) {
for key, ports := range valid { for key, ports := range valid {
convertedPorts, err := convertToStandardNotation(ports) convertedPorts, err := convertToStandardNotation(ports)
if err != nil { if err != nil {
assert.NilError(t, err) assert.NilError(t, err)
} }

View File

@ -174,7 +174,6 @@ func runContainer(dockerCli command.Cli, opts *runOptions, copts *containerOptio
} }
close, err := attachContainer(ctx, dockerCli, &errCh, config, createResponse.ID) close, err := attachContainer(ctx, dockerCli, &errCh, config, createResponse.ID)
if err != nil { if err != nil {
return err return err
} }

View File

@ -44,5 +44,4 @@ func TestForwardSignals(t *testing.T) {
case <-timer.C: case <-timer.C:
t.Fatal("timeout waiting for signal to be processed") t.Fatal("timeout waiting for signal to be processed")
} }
} }

View File

@ -15,5 +15,4 @@ func TestShow(t *testing.T) {
cli.OutBuffer().Reset() cli.OutBuffer().Reset()
assert.NilError(t, runShow(cli)) assert.NilError(t, runShow(cli))
golden.Assert(t, cli.OutBuffer().String(), "show.golden") golden.Assert(t, cli.OutBuffer().String(), "show.golden")
} }

View File

@ -33,18 +33,20 @@ func TestContainerPsContext(t *testing.T) {
{types.Container{Image: "ubuntu"}, true, "ubuntu", ctx.Image}, {types.Container{Image: "ubuntu"}, true, "ubuntu", ctx.Image},
{types.Container{Image: "verylongimagename"}, true, "verylongimagename", ctx.Image}, {types.Container{Image: "verylongimagename"}, true, "verylongimagename", ctx.Image},
{types.Container{Image: "verylongimagename"}, false, "verylongimagename", ctx.Image}, {types.Container{Image: "verylongimagename"}, false, "verylongimagename", ctx.Image},
{types.Container{ {
Image: "a5a665ff33eced1e0803148700880edab4", types.Container{
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5", Image: "a5a665ff33eced1e0803148700880edab4",
}, ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
true, true,
"a5a665ff33ec", "a5a665ff33ec",
ctx.Image, ctx.Image,
}, },
{types.Container{ {
Image: "a5a665ff33eced1e0803148700880edab4", types.Container{
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5", Image: "a5a665ff33eced1e0803148700880edab4",
}, ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
false, false,
"a5a665ff33eced1e0803148700880edab4", "a5a665ff33eced1e0803148700880edab4",
ctx.Image, ctx.Image,
@ -446,7 +448,8 @@ func TestDisplayablePorts(t *testing.T) {
Type: "tcp", Type: "tcp",
}, },
}, },
"9988/tcp"}, "9988/tcp",
},
{ {
[]types.Port{ []types.Port{
{ {

View File

@ -289,7 +289,6 @@ func (c *diskUsageImagesContext) Active() string {
func (c *diskUsageImagesContext) Size() string { func (c *diskUsageImagesContext) Size() string {
return units.HumanSize(float64(c.totalSize)) return units.HumanSize(float64(c.totalSize))
} }
func (c *diskUsageImagesContext) Reclaimable() string { func (c *diskUsageImagesContext) Reclaimable() string {
@ -391,7 +390,6 @@ func (c *diskUsageVolumesContext) TotalCount() string {
} }
func (c *diskUsageVolumesContext) Active() string { func (c *diskUsageVolumesContext) Active() string {
used := 0 used := 0
for _, v := range c.volumes { for _, v := range c.volumes {
if v.UsageData.RefCount > 0 { if v.UsageData.RefCount > 0 {

View File

@ -19,7 +19,8 @@ func TestDiskUsageContextFormatWrite(t *testing.T) {
Context: Context{ Context: Context{
Format: NewDiskUsageFormat("table", false), Format: NewDiskUsageFormat("table", false),
}, },
Verbose: false}, Verbose: false,
},
`TYPE TOTAL ACTIVE SIZE RECLAIMABLE `TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 0 0 0B 0B Images 0 0 0B 0B
Containers 0 0 0B 0B Containers 0 0 0B 0B

View File

@ -8,7 +8,7 @@ import (
) )
func TestEllipsis(t *testing.T) { func TestEllipsis(t *testing.T) {
var testcases = []struct { testcases := []struct {
source string source string
width int width int
expected string expected string

View File

@ -177,7 +177,6 @@ func imageFormatTaggedAndDigest(ctx ImageContext, image types.ImageSummary) []*i
} }
} else { } else {
addImage(repo, "<none>", "") addImage(repo, "<none>", "")
} }
} }
return images return images

View File

@ -5,8 +5,7 @@ import (
"testing" "testing"
) )
type dummy struct { type dummy struct{}
}
func (d *dummy) Func1() string { func (d *dummy) Func1() string {
return "Func1" return "Func1"

View File

@ -576,7 +576,6 @@ func (b *Writer) Write(buf []byte) (n int, err error) {
b.startEscape(ch) b.startEscape(ch)
} }
} }
} else { } else {
// inside escape // inside escape
if ch == b.endChar { if ch == b.endChar {

View File

@ -48,7 +48,6 @@ func (r *IDResolver) get(ctx context.Context, t interface{}, id string) (string,
default: default:
return "", errors.Errorf("unsupported type") return "", errors.Errorf("unsupported type")
} }
} }
// Resolve will attempt to resolve an ID to a Name by querying the manager. // Resolve will attempt to resolve an ID to a Name by querying the manager.

View File

@ -119,7 +119,6 @@ func TestGetContextFromLocalDirWithCustomDockerfile(t *testing.T) {
func TestGetContextFromReaderString(t *testing.T) { func TestGetContextFromReaderString(t *testing.T) {
tarArchive, relDockerfile, err := GetContextFromReader(io.NopCloser(strings.NewReader(dockerfileContents)), "") tarArchive, relDockerfile, err := GetContextFromReader(io.NopCloser(strings.NewReader(dockerfileContents)), "")
if err != nil { if err != nil {
t.Fatalf("Error when executing GetContextFromReader: %s", err) t.Fatalf("Error when executing GetContextFromReader: %s", err)
} }
@ -253,7 +252,7 @@ func chdir(t *testing.T, dir string) {
} }
func TestIsArchive(t *testing.T) { func TestIsArchive(t *testing.T) {
var testcases = []struct { testcases := []struct {
doc string doc string
header []byte header []byte
expected bool expected bool
@ -285,7 +284,7 @@ func TestIsArchive(t *testing.T) {
} }
func TestDetectArchiveReader(t *testing.T) { func TestDetectArchiveReader(t *testing.T) {
var testcases = []struct { testcases := []struct {
file string file string
desc string desc string
expected bool expected bool

View File

@ -82,7 +82,7 @@ func TestRunBuildResetsUidAndGidInContext(t *testing.T) {
{Name: "Dockerfile"}, {Name: "Dockerfile"},
{Name: "foo"}, {Name: "foo"},
} }
var cmpTarHeaderNameAndOwner = cmp.Comparer(func(x, y tar.Header) bool { cmpTarHeaderNameAndOwner := cmp.Comparer(func(x, y tar.Header) bool {
return x.Name == y.Name && x.Uid == y.Uid && x.Gid == y.Gid return x.Name == y.Name && x.Uid == y.Uid && x.Gid == y.Gid
}) })
assert.DeepEqual(t, expected, headers, cmpTarHeaderNameAndOwner) assert.DeepEqual(t, expected, headers, cmpTarHeaderNameAndOwner)

View File

@ -44,7 +44,8 @@ func (cli *fakeClient) ImageSave(_ context.Context, images []string) (io.ReadClo
} }
func (cli *fakeClient) ImageRemove(_ context.Context, image string, func (cli *fakeClient) ImageRemove(_ context.Context, image string,
options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { options types.ImageRemoveOptions,
) ([]types.ImageDeleteResponseItem, error) {
if cli.imageRemoveFunc != nil { if cli.imageRemoveFunc != nil {
return cli.imageRemoveFunc(image, options) return cli.imageRemoveFunc(image, options)
} }
@ -101,7 +102,8 @@ func (cli *fakeClient) ImageInspectWithRaw(_ context.Context, image string) (typ
} }
func (cli *fakeClient) ImageImport(_ context.Context, source types.ImageImportSource, ref string, func (cli *fakeClient) ImageImport(_ context.Context, source types.ImageImportSource, ref string,
options types.ImageImportOptions) (io.ReadCloser, error) { options types.ImageImportOptions,
) (io.ReadCloser, error) {
if cli.imageImportFunc != nil { if cli.imageImportFunc != nil {
return cli.imageImportFunc(source, ref, options) return cli.imageImportFunc(source, ref, options)
} }

View File

@ -234,18 +234,20 @@ imageID6 17 years ago /bin/bash echo 183MB
context formatter.Context context formatter.Context
expected string expected string
}{ }{
{formatter.Context{ {
Format: NewHistoryFormat("table", false, true), formatter.Context{
Trunc: true, Format: NewHistoryFormat("table", false, true),
Output: out, Trunc: true,
}, Output: out,
},
expectedTrunc, expectedTrunc,
}, },
{formatter.Context{ {
Format: NewHistoryFormat("table", false, true), formatter.Context{
Trunc: false, Format: NewHistoryFormat("table", false, true),
Output: out, Trunc: false,
}, Output: out,
},
expectedNoTrunc, expectedNoTrunc,
}, },
} }

View File

@ -44,7 +44,6 @@ func NewLoadCommand(dockerCli command.Cli) *cobra.Command {
} }
func runLoad(dockerCli command.Cli, opts loadOptions) error { func runLoad(dockerCli command.Cli, opts loadOptions) error {
var input io.Reader = dockerCli.In() var input io.Reader = dockerCli.In()
if opts.input != "" { if opts.input != "" {
// We use sequential.Open to use sequential file access on Windows, avoiding // We use sequential.Open to use sequential file access on Windows, avoiding

View File

@ -59,7 +59,7 @@ func runRemove(dockerCli command.Cli, opts removeOptions, images []string) error
} }
var errs []string var errs []string
var fatalErr = false fatalErr := false
for _, img := range images { for _, img := range images {
dels, err := client.ImageRemove(ctx, img, options) dels, err := client.ImageRemove(ctx, img, options)
if err != nil { if err != nil {

View File

@ -312,7 +312,6 @@ func TrustedReference(ctx context.Context, cli command.Cli, ref reference.NamedT
r, err := convertTarget(t.Target) r, err := convertTarget(t.Target)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return reference.WithDigest(reference.TrimNamed(ref), r.digest) return reference.WithDigest(reference.TrimNamed(ref), r.digest)
} }

View File

@ -63,7 +63,6 @@ func newPushListCommand(dockerCli command.Cli) *cobra.Command {
} }
func runPush(dockerCli command.Cli, opts pushOpts) error { func runPush(dockerCli command.Cli, opts pushOpts) error {
targetRef, err := normalizeReference(opts.target) targetRef, err := normalizeReference(opts.target)
if err != nil { if err != nil {
return err return err

View File

@ -229,9 +229,7 @@ func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]str
} }
func subnetMatches(subnet, data string) (bool, error) { func subnetMatches(subnet, data string) (bool, error) {
var ( var ip net.IP
ip net.IP
)
_, s, err := net.ParseCIDR(subnet) _, s, err := net.ParseCIDR(subnet)
if err != nil { if err != nil {

View File

@ -142,6 +142,7 @@ func TestNetworkCreateErrors(t *testing.T) {
} }
} }
func TestNetworkCreateWithFlags(t *testing.T) { func TestNetworkCreateWithFlags(t *testing.T) {
expectedDriver := "foo" expectedDriver := "foo"
expectedOpts := []network.IPAMConfig{ expectedOpts := []network.IPAMConfig{

View File

@ -75,7 +75,6 @@ func TestNetworkContextWrite(t *testing.T) {
context formatter.Context context formatter.Context
expected string expected string
}{ }{
// Errors // Errors
{ {
formatter.Context{Format: "{{InvalidFunction}}"}, formatter.Context{Format: "{{InvalidFunction}}"},

View File

@ -75,7 +75,8 @@ func TestNetworkList(t *testing.T) {
return []types.NetworkResource{ return []types.NetworkResource{
*NetworkResource(NetworkResourceName("network-2-foo")), *NetworkResource(NetworkResourceName("network-2-foo")),
*NetworkResource(NetworkResourceName("network-1-foo")), *NetworkResource(NetworkResourceName("network-1-foo")),
*NetworkResource(NetworkResourceName("network-10-foo"))}, nil *NetworkResource(NetworkResourceName("network-10-foo")),
}, nil
}, },
}, },
} }

View File

@ -59,7 +59,6 @@ func TestNodeContextWrite(t *testing.T) {
expected string expected string
clusterInfo swarm.ClusterInfo clusterInfo swarm.ClusterInfo
}{ }{
// Errors // Errors
{ {
context: formatter.Context{Format: "{{InvalidFunction}}"}, context: formatter.Context{Format: "{{InvalidFunction}}"},

View File

@ -13,9 +13,7 @@ import (
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
var ( var errNoRoleChange = errors.New("role was already set to the requested value")
errNoRoleChange = errors.New("role was already set to the requested value")
)
func newUpdateCommand(dockerCli command.Cli) *cobra.Command { func newUpdateCommand(dockerCli command.Cli) *cobra.Command {
options := newNodeOptions() options := newNodeOptions()

View File

@ -55,7 +55,6 @@ func TestPluginContextWrite(t *testing.T) {
context formatter.Context context formatter.Context
expected string expected string
}{ }{
// Errors // Errors
{ {
formatter.Context{Format: "{{InvalidFunction}}"}, formatter.Context{Format: "{{InvalidFunction}}"},

View File

@ -93,7 +93,6 @@ func TestInstallContentTrustErrors(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
pluginInstallFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) { pluginInstallFunc: func(name string, options types.PluginInstallOptions) (io.ReadCloser, error) {
return nil, fmt.Errorf("should not try to install plugin") return nil, fmt.Errorf("should not try to install plugin")
}, },
}, test.EnableContentTrust) }, test.EnableContentTrust)
cli.SetNotaryClient(tc.notaryFunc) cli.SetNotaryClient(tc.notaryFunc)

View File

@ -12,7 +12,6 @@ import (
) )
func TestRemoveErrors(t *testing.T) { func TestRemoveErrors(t *testing.T) {
testCases := []struct { testCases := []struct {
args []string args []string
pluginRemoveFunc func(name string, options types.PluginRemoveOptions) error pluginRemoveFunc func(name string, options types.PluginRemoveOptions) error

View File

@ -74,7 +74,7 @@ func GetDefaultAuthConfig(cli Cli, checkCredStore bool, serverAddress string, is
if !isDefaultRegistry { if !isDefaultRegistry {
serverAddress = registry.ConvertToHostname(serverAddress) serverAddress = registry.ConvertToHostname(serverAddress)
} }
var authconfig = configtypes.AuthConfig{} authconfig := configtypes.AuthConfig{}
var err error var err error
if checkCredStore { if checkCredStore {
authconfig, err = cli.ConfigFile().GetAuthConfig(serverAddress) authconfig, err = cli.ConfigFile().GetAuthConfig(serverAddress)

View File

@ -108,7 +108,6 @@ func TestSearchContextWrite(t *testing.T) {
context formatter.Context context formatter.Context
expected string expected string
}{ }{
// Errors // Errors
{ {
formatter.Context{Format: "{{InvalidFunction}}"}, formatter.Context{Format: "{{InvalidFunction}}"},

View File

@ -16,15 +16,19 @@ import (
"gotest.tools/v3/fs" "gotest.tools/v3/fs"
) )
const userErr = "userunknownError" const (
const testAuthErrMsg = "UNKNOWN_ERR" userErr = "userunknownError"
testAuthErrMsg = "UNKNOWN_ERR"
)
var testAuthErrors = map[string]error{ var testAuthErrors = map[string]error{
userErr: fmt.Errorf(testAuthErrMsg), userErr: fmt.Errorf(testAuthErrMsg),
} }
var expiredPassword = "I_M_EXPIRED" var (
var useToken = "I_M_TOKEN" expiredPassword = "I_M_EXPIRED"
useToken = "I_M_TOKEN"
)
type fakeClient struct { type fakeClient struct {
client.Client client.Client

View File

@ -24,10 +24,12 @@ func TestSecretCreateErrors(t *testing.T) {
secretCreateFunc func(swarm.SecretSpec) (types.SecretCreateResponse, error) secretCreateFunc func(swarm.SecretSpec) (types.SecretCreateResponse, error)
expectedError string expectedError string
}{ }{
{args: []string{"too", "many", "arguments"}, {
args: []string{"too", "many", "arguments"},
expectedError: "requires at least 1 and at most 2 arguments", expectedError: "requires at least 1 and at most 2 arguments",
}, },
{args: []string{"create", "--driver", "driver", "-"}, {
args: []string{"create", "--driver", "driver", "-"},
expectedError: "secret data must be empty", expectedError: "secret data must be empty",
}, },
{ {

View File

@ -26,29 +26,39 @@ func TestSecretContextFormatWrite(t *testing.T) {
`template parsing error: template: :1:2: executing "" at <nil>: nil is not a command`, `template parsing error: template: :1:2: executing "" at <nil>: nil is not a command`,
}, },
// Table format // Table format
{formatter.Context{Format: NewFormat("table", false)}, {
formatter.Context{Format: NewFormat("table", false)},
`ID NAME DRIVER CREATED UPDATED `ID NAME DRIVER CREATED UPDATED
1 passwords Less than a second ago Less than a second ago 1 passwords Less than a second ago Less than a second ago
2 id_rsa Less than a second ago Less than a second ago 2 id_rsa Less than a second ago Less than a second ago
`}, `,
{formatter.Context{Format: NewFormat("table {{.Name}}", true)}, },
{
formatter.Context{Format: NewFormat("table {{.Name}}", true)},
`NAME `NAME
passwords passwords
id_rsa id_rsa
`}, `,
{formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)}, },
{
formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
`1-passwords `1-passwords
2-id_rsa 2-id_rsa
`}, `,
},
} }
secrets := []swarm.Secret{ secrets := []swarm.Secret{
{ID: "1", {
ID: "1",
Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()}, Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()},
Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "passwords"}}}, Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "passwords"}},
{ID: "2", },
{
ID: "2",
Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()}, Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()},
Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "id_rsa"}}}, Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "id_rsa"}},
},
} }
for _, tc := range cases { for _, tc := range cases {
tc := tc tc := tc

View File

@ -273,6 +273,7 @@ func (ctx *serviceInspectContext) HasLogDriver() bool {
func (ctx *serviceInspectContext) HasLogDriverName() bool { func (ctx *serviceInspectContext) HasLogDriverName() bool {
return ctx.Service.Spec.TaskTemplate.LogDriver.Name != "" return ctx.Service.Spec.TaskTemplate.LogDriver.Name != ""
} }
func (ctx *serviceInspectContext) LogDriverName() string { func (ctx *serviceInspectContext) LogDriverName() string {
return ctx.Service.Spec.TaskTemplate.LogDriver.Name return ctx.Service.Spec.TaskTemplate.LogDriver.Name
} }

View File

@ -301,6 +301,7 @@ func TestServiceContextWriteJSON(t *testing.T) {
assert.Check(t, is.DeepEqual(expectedJSONs[i], m), msg) assert.Check(t, is.DeepEqual(expectedJSONs[i], m), msg)
} }
} }
func TestServiceContextWriteJSONField(t *testing.T) { func TestServiceContextWriteJSONField(t *testing.T) {
services := []swarm.Service{ services := []swarm.Service{
{ {

View File

@ -180,7 +180,6 @@ func TestResourceOptionsToResourceRequirements(t *testing.T) {
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Len(r.Reservations.GenericResources, len(opt.resGenericResources))) assert.Check(t, is.Len(r.Reservations.GenericResources, len(opt.resGenericResources)))
} }
} }
func TestToServiceNetwork(t *testing.T) { func TestToServiceNetwork(t *testing.T) {

View File

@ -91,7 +91,8 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// Task with DesiredState beyond Running is ignored // Task with DesiredState beyond Running is ignored
tasks = append(tasks, tasks = append(tasks,
swarm.Task{ID: "1", swarm.Task{
ID: "1",
NodeID: "a", NodeID: "a",
DesiredState: swarm.TaskStateShutdown, DesiredState: swarm.TaskStateShutdown,
Status: swarm.TaskStatus{State: swarm.TaskStateNew}, Status: swarm.TaskStatus{State: swarm.TaskStateNew},
@ -140,7 +141,8 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// replacement task, not the old task. // replacement task, not the old task.
tasks[0].DesiredState = swarm.TaskStateShutdown tasks[0].DesiredState = swarm.TaskStateShutdown
tasks = append(tasks, tasks = append(tasks,
swarm.Task{ID: "2", swarm.Task{
ID: "2",
NodeID: "b", NodeID: "b",
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStateRunning}, Status: swarm.TaskStatus{State: swarm.TaskStateRunning},
@ -154,7 +156,8 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// Add a new task while the current one is still running, to simulate // Add a new task while the current one is still running, to simulate
// "start-then-stop" updates. // "start-then-stop" updates.
tasks = append(tasks, tasks = append(tasks,
swarm.Task{ID: "3", swarm.Task{
ID: "3",
NodeID: "b", NodeID: "b",
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStatePreparing}, Status: swarm.TaskStatus{State: swarm.TaskStatePreparing},
@ -254,7 +257,8 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// Task with DesiredState beyond Running is ignored // Task with DesiredState beyond Running is ignored
tasks = append(tasks, tasks = append(tasks,
swarm.Task{ID: "1", swarm.Task{
ID: "1",
NodeID: "a", NodeID: "a",
DesiredState: swarm.TaskStateShutdown, DesiredState: swarm.TaskStateShutdown,
Status: swarm.TaskStatus{State: swarm.TaskStateNew}, Status: swarm.TaskStatus{State: swarm.TaskStateNew},
@ -304,7 +308,8 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// replacement task, not the old task. // replacement task, not the old task.
tasks[0].DesiredState = swarm.TaskStateShutdown tasks[0].DesiredState = swarm.TaskStateShutdown
tasks = append(tasks, tasks = append(tasks,
swarm.Task{ID: "2", swarm.Task{
ID: "2",
NodeID: "a", NodeID: "a",
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStateRunning}, Status: swarm.TaskStatus{State: swarm.TaskStateRunning},
@ -318,7 +323,8 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// Add a new task while the current one is still running, to simulate // Add a new task while the current one is still running, to simulate
// "start-then-stop" updates. // "start-then-stop" updates.
tasks = append(tasks, tasks = append(tasks,
swarm.Task{ID: "3", swarm.Task{
ID: "3",
NodeID: "a", NodeID: "a",
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStatePreparing}, Status: swarm.TaskStatus{State: swarm.TaskStatePreparing},

View File

@ -12,7 +12,6 @@ import (
) )
func newRemoveCommand(dockerCli command.Cli) *cobra.Command { func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "rm SERVICE [SERVICE...]", Use: "rm SERVICE [SERVICE...]",
Aliases: []string{"remove"}, Aliases: []string{"remove"},

View File

@ -999,7 +999,6 @@ func updateDNSConfig(flags *pflag.FlagSet, config **swarm.DNSConfig) error {
for _, nameserver := range nameservers { for _, nameserver := range nameservers {
if _, exists := toRemove[nameserver]; !exists { if _, exists := toRemove[nameserver]; !exists {
newConfig.Nameservers = append(newConfig.Nameservers, nameserver) newConfig.Nameservers = append(newConfig.Nameservers, nameserver)
} }
} }
// Sort so that result is predictable. // Sort so that result is predictable.

View File

@ -507,15 +507,19 @@ type secretAPIClientMock struct {
func (s secretAPIClientMock) SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) { func (s secretAPIClientMock) SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) {
return s.listResult, nil return s.listResult, nil
} }
func (s secretAPIClientMock) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) { func (s secretAPIClientMock) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) {
return types.SecretCreateResponse{}, nil return types.SecretCreateResponse{}, nil
} }
func (s secretAPIClientMock) SecretRemove(ctx context.Context, id string) error { func (s secretAPIClientMock) SecretRemove(ctx context.Context, id string) error {
return nil return nil
} }
func (s secretAPIClientMock) SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) { func (s secretAPIClientMock) SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) {
return swarm.Secret{}, []byte{}, nil return swarm.Secret{}, []byte{}, nil
} }
func (s secretAPIClientMock) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { func (s secretAPIClientMock) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error {
return nil return nil
} }

View File

@ -75,7 +75,6 @@ services:
} }
func TestConfigMergeInterpolation(t *testing.T) { func TestConfigMergeInterpolation(t *testing.T) {
for _, tt := range configMergeTests { for _, tt := range configMergeTests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
firstConfig := []byte(tt.first) firstConfig := []byte(tt.first)
@ -102,5 +101,4 @@ func TestConfigMergeInterpolation(t *testing.T) {
assert.Equal(t, cfg, tt.merged) assert.Equal(t, cfg, tt.merged)
}) })
} }
} }

View File

@ -22,7 +22,6 @@ func TestStackPsErrors(t *testing.T) {
taskListFunc func(options types.TaskListOptions) ([]swarm.Task, error) taskListFunc func(options types.TaskListOptions) ([]swarm.Task, error)
expectedError string expectedError string
}{ }{
{ {
args: []string{}, args: []string{},
expectedError: "requires exactly 1 argument", expectedError: "requires exactly 1 argument",

View File

@ -110,7 +110,8 @@ func TestRemoveStackSkipEmpty(t *testing.T) {
cmd.SetArgs([]string{"foo", "bar"}) cmd.SetArgs([]string{"foo", "bar"})
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
expectedList := []string{"Removing service bar_service1", expectedList := []string{
"Removing service bar_service1",
"Removing service bar_service2", "Removing service bar_service2",
"Removing secret bar_secret1", "Removing secret bar_secret1",
"Removing config bar_config1", "Removing config bar_config1",

View File

@ -19,7 +19,7 @@ func (n notFound) NotFound() bool {
} }
func TestValidateExternalNetworks(t *testing.T) { func TestValidateExternalNetworks(t *testing.T) {
var testcases = []struct { testcases := []struct {
inspectResponse types.NetworkResource inspectResponse types.NetworkResource
inspectError error inspectError error
expectedMsg string expectedMsg string

View File

@ -63,7 +63,7 @@ func TestServiceUpdateResolveImageChanged(t *testing.T) {
}, },
}) })
var testcases = []struct { testcases := []struct {
image string image string
expectedQueryRegistry bool expectedQueryRegistry bool
expectedImage string expectedImage string

View File

@ -216,7 +216,8 @@ func TestUpdateSwarmSpecCertAndKey(t *testing.T) {
"--detach", "--detach",
"--ca-cert=" + certfile, "--ca-cert=" + certfile,
"--ca-key=" + keyfile, "--ca-key=" + keyfile,
"--cert-expiry=3m"}) "--cert-expiry=3m",
})
cmd.SetOut(cli.OutBuffer()) cmd.SetOut(cli.OutBuffer())
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
@ -242,7 +243,8 @@ func TestUpdateSwarmSpecCertAndExternalCA(t *testing.T) {
"--rotate", "--rotate",
"--detach", "--detach",
"--ca-cert=" + certfile, "--ca-cert=" + certfile,
"--external-ca=protocol=cfssl,url=https://some.external.ca.example.com"}) "--external-ca=protocol=cfssl,url=https://some.external.ca.example.com",
})
cmd.SetOut(cli.OutBuffer()) cmd.SetOut(cli.OutBuffer())
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
@ -280,7 +282,8 @@ func TestUpdateSwarmSpecCertAndKeyAndExternalCA(t *testing.T) {
"--detach", "--detach",
"--ca-cert=" + certfile, "--ca-cert=" + certfile,
"--ca-key=" + keyfile, "--ca-key=" + keyfile,
"--external-ca=protocol=cfssl,url=https://some.external.ca.example.com"}) "--external-ca=protocol=cfssl,url=https://some.external.ca.example.com",
})
cmd.SetOut(cli.OutBuffer()) cmd.SetOut(cli.OutBuffer())
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())

View File

@ -25,7 +25,6 @@ func newIPNetSliceValue(val []net.IPNet, p *[]net.IPNet) *ipNetSliceValue {
// Set converts, and assigns, the comma-separated IPNet argument string representation as the []net.IPNet value of this flag. // Set converts, and assigns, the comma-separated IPNet argument string representation as the []net.IPNet value of this flag.
// If Set is called on a flag that already has a []net.IPNet assigned, the newly converted values will be appended. // If Set is called on a flag that already has a []net.IPNet assigned, the newly converted values will be appended.
func (s *ipNetSliceValue) Set(val string) error { func (s *ipNetSliceValue) Set(val string) error {
// remove all quote characters // remove all quote characters
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
@ -63,7 +62,6 @@ func (s *ipNetSliceValue) Type() string {
// String defines a "native" format for this net.IPNet slice flag value. // String defines a "native" format for this net.IPNet slice flag value.
func (s *ipNetSliceValue) String() string { func (s *ipNetSliceValue) String() string {
ipNetStrSlice := make([]string, len(*s.value)) ipNetStrSlice := make([]string, len(*s.value))
for i, n := range *s.value { for i, n := range *s.value {
ipNetStrSlice[i] = n.String() ipNetStrSlice[i] = n.String()

View File

@ -69,7 +69,6 @@ func TestIPNetCalledTwice(t *testing.T) {
} }
func TestIPNetBadQuoting(t *testing.T) { func TestIPNetBadQuoting(t *testing.T) {
tests := []struct { tests := []struct {
Want []net.IPNet Want []net.IPNet
FlagArg []string FlagArg []string
@ -126,7 +125,8 @@ func TestIPNetBadQuoting(t *testing.T) {
}, },
FlagArg: []string{ FlagArg: []string{
`"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128 "`, `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128 "`,
" 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128"}, " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b/128",
},
}, },
} }

View File

@ -57,7 +57,8 @@ func runEvents(dockerCli command.Cli, options *eventsOptions) error {
if err != nil { if err != nil {
return cli.StatusError{ return cli.StatusError{
StatusCode: 64, StatusCode: 64,
Status: "Error parsing format: " + err.Error()} Status: "Error parsing format: " + err.Error(),
}
} }
eventOptions := types.EventsOptions{ eventOptions := types.EventsOptions{
Since: options.since, Since: options.since,

View File

@ -514,8 +514,10 @@ func formatInfo(dockerCli command.Cli, info info, format string) error {
tmpl, err := templates.Parse(format) tmpl, err := templates.Parse(format)
if err != nil { if err != nil {
return cli.StatusError{StatusCode: 64, return cli.StatusError{
Status: "template parsing error: " + err.Error()} StatusCode: 64,
Status: "template parsing error: " + err.Error(),
}
} }
err = tmpl.Execute(dockerCli.Out(), info) err = tmpl.Execute(dockerCli.Out(), info)
dockerCli.Out().Write([]byte{'\n'}) dockerCli.Out().Write([]byte{'\n'})

View File

@ -315,7 +315,6 @@ func TestPrettyPrintInfo(t *testing.T) {
prettyGolden: "docker-info-with-labels-empty", prettyGolden: "docker-info-with-labels-empty",
}, },
{ {
doc: "info with swarm", doc: "info with swarm",
dockerInfo: info{ dockerInfo: info{
Info: &infoWithSwarm, Info: &infoWithSwarm,

View File

@ -111,7 +111,7 @@ func inspectSecret(ctx context.Context, dockerCli command.Cli) inspect.GetRefFun
} }
func inspectAll(ctx context.Context, dockerCli command.Cli, getSize bool, typeConstraint string) inspect.GetRefFunc { func inspectAll(ctx context.Context, dockerCli command.Cli, getSize bool, typeConstraint string) inspect.GetRefFunc {
var inspectAutodetect = []struct { inspectAutodetect := []struct {
objectType string objectType string
isSizeSupported bool isSizeSupported bool
isSwarmObject bool isSwarmObject bool

View File

@ -11,7 +11,7 @@ import (
) )
func TestMatchReleasedSignaturesSortOrder(t *testing.T) { func TestMatchReleasedSignaturesSortOrder(t *testing.T) {
var releasesRole = data.DelegationRole{BaseRole: data.BaseRole{Name: trust.ReleasesRole}} releasesRole := data.DelegationRole{BaseRole: data.BaseRole{Name: trust.ReleasesRole}}
targets := []client.TargetSignedStruct{ targets := []client.TargetSignedStruct{
{Target: client.Target{Name: "target10-foo"}, Role: releasesRole}, {Target: client.Target{Name: "target10-foo"}, Role: releasesRole},
{Target: client.Target{Name: "target1-foo"}, Role: releasesRole}, {Target: client.Target{Name: "target1-foo"}, Role: releasesRole},

View File

@ -23,7 +23,8 @@ func TestTrustTag(t *testing.T) {
}{ }{
{ {
trustTagContext{ trustTagContext{
s: SignedTagInfo{Name: trustedTag, s: SignedTagInfo{
Name: trustedTag,
Digest: digest, Digest: digest,
Signers: nil, Signers: nil,
}, },
@ -33,7 +34,8 @@ func TestTrustTag(t *testing.T) {
}, },
{ {
trustTagContext{ trustTagContext{
s: SignedTagInfo{Name: trustedTag, s: SignedTagInfo{
Name: trustedTag,
Digest: digest, Digest: digest,
Signers: nil, Signers: nil,
}, },
@ -44,7 +46,8 @@ func TestTrustTag(t *testing.T) {
// Empty signers makes a row with empty string // Empty signers makes a row with empty string
{ {
trustTagContext{ trustTagContext{
s: SignedTagInfo{Name: trustedTag, s: SignedTagInfo{
Name: trustedTag,
Digest: digest, Digest: digest,
Signers: nil, Signers: nil,
}, },
@ -54,7 +57,8 @@ func TestTrustTag(t *testing.T) {
}, },
{ {
trustTagContext{ trustTagContext{
s: SignedTagInfo{Name: trustedTag, s: SignedTagInfo{
Name: trustedTag,
Digest: digest, Digest: digest,
Signers: []string{"alice", "bob", "claire"}, Signers: []string{"alice", "bob", "claire"},
}, },
@ -65,7 +69,8 @@ func TestTrustTag(t *testing.T) {
// alphabetic signing on Signers // alphabetic signing on Signers
{ {
trustTagContext{ trustTagContext{
s: SignedTagInfo{Name: trustedTag, s: SignedTagInfo{
Name: trustedTag,
Digest: digest, Digest: digest,
Signers: []string{"claire", "bob", "alice"}, Signers: []string{"claire", "bob", "alice"},
}, },
@ -85,7 +90,6 @@ func TestTrustTag(t *testing.T) {
} }
func TestTrustTagContextWrite(t *testing.T) { func TestTrustTagContextWrite(t *testing.T) {
cases := []struct { cases := []struct {
context formatter.Context context formatter.Context
expected string expected string
@ -140,7 +144,6 @@ tag3 bbbbbbbb
// With no trust data, the TagWrite will print an empty table: // With no trust data, the TagWrite will print an empty table:
// it's up to the caller to decide whether or not to print this versus an error // it's up to the caller to decide whether or not to print this versus an error
func TestTrustTagContextEmptyWrite(t *testing.T) { func TestTrustTagContextEmptyWrite(t *testing.T) {
emptyCase := struct { emptyCase := struct {
context formatter.Context context formatter.Context
expected string expected string

View File

@ -8,8 +8,10 @@ import (
"github.com/theupdateframework/notary/tuf/data" "github.com/theupdateframework/notary/tuf/data"
) )
const releasedRoleName = "Repo Admin" const (
const releasesRoleTUFName = "targets/releases" releasedRoleName = "Repo Admin"
releasesRoleTUFName = "targets/releases"
)
// isReleasedTarget checks if a role name is "released": // isReleasedTarget checks if a role name is "released":
// either targets/releases or targets TUF roles // either targets/releases or targets TUF roles

View File

@ -139,7 +139,6 @@ func TestTrustRevokeCommand(t *testing.T) {
assert.Check(t, is.Contains(cli.OutBuffer().String(), tc.expectedMessage)) assert.Check(t, is.Contains(cli.OutBuffer().String(), tc.expectedMessage))
}) })
} }
} }
func TestGetSignableRolesForTargetAndRemoveError(t *testing.T) { func TestGetSignableRolesForTargetAndRemoveError(t *testing.T) {

View File

@ -225,7 +225,6 @@ func TestGetReleasedTargetHashAndSize(t *testing.T) {
oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt}) oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt})
hash, _, _ := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased") hash, _, _ := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased")
assert.Check(t, is.DeepEqual(data.Hashes{notary.SHA256: []byte("released-hash")}, hash)) assert.Check(t, is.DeepEqual(data.Hashes{notary.SHA256: []byte("released-hash")}, hash))
} }
func TestCreateTarget(t *testing.T) { func TestCreateTarget(t *testing.T) {
@ -280,5 +279,4 @@ func TestSignCommandLocalFlag(t *testing.T) {
cmd.SetArgs([]string{"--local", "reg-name.io/image:red"}) cmd.SetArgs([]string{"--local", "reg-name.io/image:red"})
cmd.SetOut(io.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "error contacting notary server: dial tcp: lookup reg-name.io") assert.ErrorContains(t, cmd.Execute(), "error contacting notary server: dial tcp: lookup reg-name.io")
} }

View File

@ -65,7 +65,6 @@ func TestTrustSignerRemoveErrors(t *testing.T) {
cmd.Execute() cmd.Execute()
assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError)) assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError))
} }
} }
func TestRemoveSingleSigner(t *testing.T) { func TestRemoveSingleSigner(t *testing.T) {
@ -89,6 +88,7 @@ func TestRemoveMultipleSigners(t *testing.T) {
"no signer test for repository signed-repo")) "no signer test for repository signed-repo"))
assert.Check(t, is.Contains(cli.OutBuffer().String(), "Removing signer \"test\" from signed-repo...\n")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "Removing signer \"test\" from signed-repo...\n"))
} }
func TestRemoveLastSignerWarning(t *testing.T) { func TestRemoveLastSignerWarning(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository) cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository)

View File

@ -44,7 +44,7 @@ func TestValidateOutputPath(t *testing.T) {
file := filepath.Join(dir, "file") file := filepath.Join(dir, "file")
err = os.WriteFile(file, []byte("hi"), 0644) err = os.WriteFile(file, []byte("hi"), 0644)
assert.NilError(t, err) assert.NilError(t, err)
var testcases = []struct { testcases := []struct {
path string path string
err error err error
}{ }{

View File

@ -146,7 +146,8 @@ func TestClusterVolumeList(t *testing.T) {
Availability: volume.AvailabilityActive, Availability: volume.AvailabilityActive,
}, },
}, },
}, { },
{
Name: "volume2", Name: "volume2",
Scope: "global", Scope: "global",
Driver: "driver1", Driver: "driver1",
@ -165,7 +166,8 @@ func TestClusterVolumeList(t *testing.T) {
VolumeID: "driver1vol2", VolumeID: "driver1vol2",
}, },
}, },
}, { },
{
Name: "volume3", Name: "volume3",
Scope: "global", Scope: "global",
Driver: "driver2", Driver: "driver2",
@ -190,7 +192,8 @@ func TestClusterVolumeList(t *testing.T) {
VolumeID: "driver1vol3", VolumeID: "driver1vol3",
}, },
}, },
}, { },
{
Name: "volume4", Name: "volume4",
Scope: "global", Scope: "global",
Driver: "driver2", Driver: "driver2",

View File

@ -147,7 +147,6 @@ func convertVolumeToMount(
stackVolumes volumes, stackVolumes volumes,
namespace Namespace, namespace Namespace,
) (mount.Mount, error) { ) (mount.Mount, error) {
switch volume.Type { switch volume.Type {
case "volume", "": case "volume", "":
return handleVolumeToMount(volume, stackVolumes, namespace) return handleVolumeToMount(volume, stackVolumes, namespace)

View File

@ -100,7 +100,7 @@ func TestInterpolateWithCast(t *testing.T) {
} }
func TestPathMatches(t *testing.T) { func TestPathMatches(t *testing.T) {
var testcases = []struct { testcases := []struct {
doc string doc string
path Path path Path
pattern Path pattern Path

View File

@ -143,7 +143,7 @@ func loadSections(config map[string]interface{}, configDetails types.ConfigDetai
Version: schema.Version(config), Version: schema.Version(config),
} }
var loaders = []struct { loaders := []struct {
key string key string
fnc func(config map[string]interface{}) error fnc func(config map[string]interface{}) error
}{ }{

View File

@ -170,8 +170,10 @@ func toServiceVolumeConfigsSlice(dst reflect.Value, m map[interface{}]interface{
return nil return nil
} }
type tomapFn func(s interface{}) (map[interface{}]interface{}, error) type (
type writeValueFromMapFn func(reflect.Value, map[interface{}]interface{}) error tomapFn func(s interface{}) (map[interface{}]interface{}, error)
writeValueFromMapFn func(reflect.Value, map[interface{}]interface{}) error
)
func safelyMerge(mergeFn func(dst, src reflect.Value) error) func(dst, src reflect.Value) error { func safelyMerge(mergeFn func(dst, src reflect.Value) error) func(dst, src reflect.Value) error {
return func(dst, src reflect.Value) error { return func(dst, src reflect.Value) error {

View File

@ -938,7 +938,8 @@ func TestLoadMultipleConfigs(t *testing.T) {
}, },
CapAdd: []string{"NET_ADMIN", "SYS_ADMIN"}, CapAdd: []string{"NET_ADMIN", "SYS_ADMIN"},
Environment: types.MappingWithEquals{}, Environment: types.MappingWithEquals{},
}}, },
},
Networks: map[string]types.NetworkConfig{}, Networks: map[string]types.NetworkConfig{},
Volumes: map[string]types.VolumeConfig{}, Volumes: map[string]types.VolumeConfig{},
Secrets: map[string]types.SecretConfig{}, Secrets: map[string]types.SecretConfig{},
@ -1002,7 +1003,8 @@ func TestLoadMultipleNetworks(t *testing.T) {
Name: "foo", Name: "foo",
Image: "baz", Image: "baz",
Environment: types.MappingWithEquals{}, Environment: types.MappingWithEquals{},
}}, },
},
Networks: map[string]types.NetworkConfig{ Networks: map[string]types.NetworkConfig{
"hostnet": { "hostnet": {
Name: "host", Name: "host",

View File

@ -6,8 +6,10 @@ import (
"strings" "strings"
) )
var delimiter = "\\$" var (
var substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?" delimiter = "\\$"
substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?"
)
var patternString = fmt.Sprintf( var patternString = fmt.Sprintf(
"%s(?i:(?P<escaped>%s)|(?P<named>%s)|{(?P<braced>%s)}|(?P<invalid>))", "%s(?i:(?P<escaped>%s)|(?P<named>%s)|{(?P<braced>%s)}|(?P<invalid>))",

View File

@ -236,17 +236,21 @@ func (c *commandConn) Close() error {
func (c *commandConn) LocalAddr() net.Addr { func (c *commandConn) LocalAddr() net.Addr {
return c.localAddr return c.localAddr
} }
func (c *commandConn) RemoteAddr() net.Addr { func (c *commandConn) RemoteAddr() net.Addr {
return c.remoteAddr return c.remoteAddr
} }
func (c *commandConn) SetDeadline(t time.Time) error { func (c *commandConn) SetDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetDeadline(%v)", t) logrus.Debugf("unimplemented call: SetDeadline(%v)", t)
return nil return nil
} }
func (c *commandConn) SetReadDeadline(t time.Time) error { func (c *commandConn) SetReadDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetReadDeadline(%v)", t) logrus.Debugf("unimplemented call: SetReadDeadline(%v)", t)
return nil return nil
} }
func (c *commandConn) SetWriteDeadline(t time.Time) error { func (c *commandConn) SetWriteDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetWriteDeadline(%v)", t) logrus.Debugf("unimplemented call: SetWriteDeadline(%v)", t)
return nil return nil

View File

@ -58,7 +58,7 @@ func TestStoreSaveAndGet(t *testing.T) {
err := store.Save(listRef, ref("exists"), data) err := store.Save(listRef, ref("exists"), data)
assert.NilError(t, err) assert.NilError(t, err)
var testcases = []struct { testcases := []struct {
listRef reference.Reference listRef reference.Reference
manifestRef reference.Reference manifestRef reference.Reference
expected types.ImageManifest expected types.ImageManifest

View File

@ -102,7 +102,7 @@ func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo
return nil, err return nil, err
} }
var cfg = tlsconfig.ClientDefault() cfg := tlsconfig.ClientDefault()
cfg.InsecureSkipVerify = !repoInfo.Index.Secure cfg.InsecureSkipVerify = !repoInfo.Index.Secure
// Get certificate base directory // Get certificate base directory
@ -287,7 +287,6 @@ func GetSignableRoles(repo client.Repository, target *client.Target) ([]data.Rol
} }
return signableRoles, nil return signableRoles, nil
} }
// ImageRefAndAuth contains all reference information and the auth config for an image request // ImageRefAndAuth contains all reference information and the auth config for an image request
@ -384,5 +383,4 @@ func (imgRefAuth *ImageRefAndAuth) Digest() digest.Digest {
// Name returns the image name used to initialize the ImageRefAndAuth // Name returns the image name used to initialize the ImageRefAndAuth
func (imgRefAuth *ImageRefAndAuth) Name() string { func (imgRefAuth *ImageRefAndAuth) Name() string {
return imgRefAuth.original return imgRefAuth.original
} }

View File

@ -40,7 +40,6 @@ func newDockerCommand(dockerCli *command.DockerCli) *cli.TopLevelCommand {
return command.ShowHelp(dockerCli.Err())(cmd, args) return command.ShowHelp(dockerCli.Err())(cmd, args)
} }
return fmt.Errorf("docker: '%s' is not a docker command.\nSee 'docker --help'", args[0]) return fmt.Errorf("docker: '%s' is not a docker command.\nSee 'docker --help'", args[0])
}, },
PersistentPreRunE: func(cmd *cobra.Command, args []string) error { PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return isSupported(cmd, dockerCli) return isSupported(cmd, dockerCli)

View File

@ -255,5 +255,4 @@ func TestCliPluginsVersion(t *testing.T) {
}) })
}) })
} }
} }

View File

@ -26,5 +26,4 @@ func prepare(t *testing.T) (func(args ...string) icmd.Cmd, *configfile.ConfigFil
assert.NilError(t, err) assert.NilError(t, err)
return run, cfgfile, cleanup return run, cfgfile, cleanup
} }

View File

@ -6,9 +6,7 @@ import (
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
) )
var ( var defaultTime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
defaultTime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
)
// Task creates a task with default values . // Task creates a task with default values .
// Any number of task function builder can be pass to augment it. // Any number of task function builder can be pass to augment it.

View File

@ -271,7 +271,8 @@ func (e EmptyTargetsNotaryRepository) ListRoles() ([]client.RoleWithSignatures,
} }
return []client.RoleWithSignatures{ return []client.RoleWithSignatures{
{Role: rootRole}, {Role: rootRole},
{Role: targetsRole}}, nil {Role: targetsRole},
}, nil
} }
// GetDelegationRoles returns the keys and roles of the repository's delegations // GetDelegationRoles returns the keys and roles of the repository's delegations
@ -306,6 +307,7 @@ var loadedReleasesRole = data.DelegationRole{
Threshold: 1, Threshold: 1,
}, },
} }
var loadedAliceRole = data.DelegationRole{ var loadedAliceRole = data.DelegationRole{
BaseRole: data.BaseRole{ BaseRole: data.BaseRole{
Name: "targets/alice", Name: "targets/alice",
@ -313,6 +315,7 @@ var loadedAliceRole = data.DelegationRole{
Threshold: 1, Threshold: 1,
}, },
} }
var loadedBobRole = data.DelegationRole{ var loadedBobRole = data.DelegationRole{
BaseRole: data.BaseRole{ BaseRole: data.BaseRole{
Name: "targets/bob", Name: "targets/bob",
@ -320,6 +323,7 @@ var loadedBobRole = data.DelegationRole{
Threshold: 1, Threshold: 1,
}, },
} }
var loadedDelegationRoles = []data.Role{ var loadedDelegationRoles = []data.Role{
{ {
Name: loadedReleasesRole.Name, Name: loadedReleasesRole.Name,
@ -343,6 +347,7 @@ var loadedDelegationRoles = []data.Role{
}, },
}, },
} }
var loadedTargetsRole = data.DelegationRole{ var loadedTargetsRole = data.DelegationRole{
BaseRole: data.BaseRole{ BaseRole: data.BaseRole{
Name: data.CanonicalTargetsRole, Name: data.CanonicalTargetsRole,
@ -359,14 +364,17 @@ var loadedRedTarget = client.Target{
Name: "red", Name: "red",
Hashes: data.Hashes{"sha256": []byte("red-digest")}, Hashes: data.Hashes{"sha256": []byte("red-digest")},
} }
var loadedBlueTarget = client.Target{ var loadedBlueTarget = client.Target{
Name: "blue", Name: "blue",
Hashes: data.Hashes{"sha256": []byte("blue-digest")}, Hashes: data.Hashes{"sha256": []byte("blue-digest")},
} }
var loadedGreenTarget = client.Target{ var loadedGreenTarget = client.Target{
Name: "green", Name: "green",
Hashes: data.Hashes{"sha256": []byte("green-digest")}, Hashes: data.Hashes{"sha256": []byte("green-digest")},
} }
var loadedTargets = []client.TargetSignedStruct{ var loadedTargets = []client.TargetSignedStruct{
// red is signed by all three delegations // red is signed by all three delegations
{Target: loadedRedTarget, Role: loadedReleasesRole}, {Target: loadedRedTarget, Role: loadedReleasesRole},

View File

@ -113,7 +113,6 @@ func TestEffectiveCapAddCapDrop(t *testing.T) {
add, drop := EffectiveCapAddCapDrop(tc.in.add, tc.in.drop) add, drop := EffectiveCapAddCapDrop(tc.in.add, tc.in.drop)
assert.DeepEqual(t, add, tc.out.add) assert.DeepEqual(t, add, tc.out.add)
assert.DeepEqual(t, drop, tc.out.drop) assert.DeepEqual(t, drop, tc.out.drop)
}) })
} }
} }

View File

@ -94,9 +94,7 @@ func TestParseDockerDaemonHost(t *testing.T) {
} }
func TestParseTCP(t *testing.T) { func TestParseTCP(t *testing.T) {
var ( defaultHTTPHost := "tcp://127.0.0.1:2376"
defaultHTTPHost = "tcp://127.0.0.1:2376"
)
invalids := map[string]string{ invalids := map[string]string{
"tcp:a.b.c.d": "", "tcp:a.b.c.d": "",
"tcp:a.b.c.d/path": "", "tcp:a.b.c.d/path": "",

View File

@ -30,7 +30,6 @@ func TestMountOptString(t *testing.T) {
} }
func TestMountRelative(t *testing.T) { func TestMountRelative(t *testing.T) {
for _, testcase := range []struct { for _, testcase := range []struct {
name string name string
path string path string

View File

@ -230,7 +230,7 @@ type ValidatorFctListType func(val string) ([]string, error)
// ValidateIPAddress validates an Ip address. // ValidateIPAddress validates an Ip address.
func ValidateIPAddress(val string) (string, error) { func ValidateIPAddress(val string) (string, error) {
var ip = net.ParseIP(strings.TrimSpace(val)) ip := net.ParseIP(strings.TrimSpace(val))
if ip != nil { if ip != nil {
return ip.String(), nil return ip.String(), nil
} }

View File

@ -28,7 +28,6 @@ func TestValidateIPAddress(t *testing.T) {
if ret, err := ValidateIPAddress(`random invalid string`); err == nil || ret != "" { if ret, err := ValidateIPAddress(`random invalid string`); err == nil || ret != "" {
t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err) t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err)
} }
} }
func TestMapOpts(t *testing.T) { func TestMapOpts(t *testing.T) {
@ -88,7 +87,6 @@ func TestListOptsWithoutValidator(t *testing.T) {
if len(mapListOpts) != 1 { if len(mapListOpts) != 1 {
t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts) t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts)
} }
} }
func TestListOptsWithValidator(t *testing.T) { func TestListOptsWithValidator(t *testing.T) {

View File

@ -361,7 +361,7 @@ func TestConvertPortToPortConfigWithIP(t *testing.T) {
} }
func assertContains(t *testing.T, portConfigs []swarm.PortConfig, expected swarm.PortConfig) { func assertContains(t *testing.T, portConfigs []swarm.PortConfig, expected swarm.PortConfig) {
var contains = false contains := false
for _, portConfig := range portConfigs { for _, portConfig := range portConfigs {
if portConfig == expected { if portConfig == expected {
contains = true contains = true