format code with gofumpt

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-09-29 17:21:51 +02:00
parent fed93645f1
commit 1da95ff6aa
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
93 changed files with 199 additions and 177 deletions

View File

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

View File

@ -6,6 +6,7 @@ package manager
func trimExeSuffix(s string) (string, error) {
return s, nil
}
func addExeSuffix(s string) string {
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")
return cmd
}
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) {
defaultVersion := "v1.55"
var testcases = []struct {
testcases := []struct {
doc string
pingFunc func() (types.Ping, error)
expectedServer ServerInfo
@ -222,7 +222,7 @@ func TestInitializeFromClientHangs(t *testing.T) {
func TestExperimentalCLI(t *testing.T) {
defaultVersion := "v1.55"
var testcases = []struct {
testcases := []struct {
doc string
configfile string
}{

View File

@ -29,7 +29,8 @@ func TestConfigCreateErrors(t *testing.T) {
args: []string{"too_few"},
expectedError: "requires exactly 2 arguments",
},
{args: []string{"too", "many", "arguments"},
{
args: []string{"too", "many", "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`,
},
// Table format
{formatter.Context{Format: NewFormat("table", false)},
{
formatter.Context{Format: NewFormat("table", false)},
`ID NAME CREATED UPDATED
1 passwords Less than a second ago Less than a second ago
2 id_rsa Less than a second ago Less than a second ago
`},
{formatter.Context{Format: NewFormat("table {{.Name}}", true)},
`,
},
{
formatter.Context{Format: NewFormat("table {{.Name}}", true)},
`NAME
passwords
id_rsa
`},
{formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
`,
},
{
formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
`1-passwords
2-id_rsa
`},
`,
},
}
configs := []swarm.Config{
{ID: "1",
{
ID: "1",
Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()},
Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "passwords"}}},
{ID: "2",
Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "passwords"}},
},
{
ID: "2",
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 {
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 nil
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -184,7 +184,6 @@ func TestParseRunWithInvalidArgs(t *testing.T) {
//nolint:gocyclo
func TestParseWithVolumes(t *testing.T) {
// A single volume
arr, tryit := setupPlatformVolume([]string{`/tmp`}, []string{`c:\tmp`})
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])
}
}
}
// 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)
}
}
}
func TestParseNetworkConfig(t *testing.T) {
@ -956,7 +953,6 @@ func TestConvertToStandardNotation(t *testing.T) {
for key, ports := range valid {
convertedPorts, err := convertToStandardNotation(ports)
if err != nil {
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)
if err != nil {
return err
}

View File

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

View File

@ -15,5 +15,4 @@ func TestShow(t *testing.T) {
cli.OutBuffer().Reset()
assert.NilError(t, runShow(cli))
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: "verylongimagename"}, true, "verylongimagename", ctx.Image},
{types.Container{Image: "verylongimagename"}, false, "verylongimagename", ctx.Image},
{types.Container{
Image: "a5a665ff33eced1e0803148700880edab4",
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
{
types.Container{
Image: "a5a665ff33eced1e0803148700880edab4",
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
true,
"a5a665ff33ec",
ctx.Image,
},
{types.Container{
Image: "a5a665ff33eced1e0803148700880edab4",
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
{
types.Container{
Image: "a5a665ff33eced1e0803148700880edab4",
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
false,
"a5a665ff33eced1e0803148700880edab4",
ctx.Image,
@ -446,7 +448,8 @@ func TestDisplayablePorts(t *testing.T) {
Type: "tcp",
},
},
"9988/tcp"},
"9988/tcp",
},
{
[]types.Port{
{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -48,7 +48,6 @@ func (r *IDResolver) get(ctx context.Context, t interface{}, id string) (string,
default:
return "", errors.Errorf("unsupported type")
}
}
// 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) {
tarArchive, relDockerfile, err := GetContextFromReader(io.NopCloser(strings.NewReader(dockerfileContents)), "")
if err != nil {
t.Fatalf("Error when executing GetContextFromReader: %s", err)
}
@ -253,7 +252,7 @@ func chdir(t *testing.T, dir string) {
}
func TestIsArchive(t *testing.T) {
var testcases = []struct {
testcases := []struct {
doc string
header []byte
expected bool
@ -285,7 +284,7 @@ func TestIsArchive(t *testing.T) {
}
func TestDetectArchiveReader(t *testing.T) {
var testcases = []struct {
testcases := []struct {
file string
desc string
expected bool

View File

@ -82,7 +82,7 @@ func TestRunBuildResetsUidAndGidInContext(t *testing.T) {
{Name: "Dockerfile"},
{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
})
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,
options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) {
options types.ImageRemoveOptions,
) ([]types.ImageDeleteResponseItem, error) {
if cli.imageRemoveFunc != nil {
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,
options types.ImageImportOptions) (io.ReadCloser, error) {
options types.ImageImportOptions,
) (io.ReadCloser, error) {
if cli.imageImportFunc != nil {
return cli.imageImportFunc(source, ref, options)
}

View File

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

View File

@ -44,7 +44,6 @@ func NewLoadCommand(dockerCli command.Cli) *cobra.Command {
}
func runLoad(dockerCli command.Cli, opts loadOptions) error {
var input io.Reader = dockerCli.In()
if opts.input != "" {
// 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 fatalErr = false
fatalErr := false
for _, img := range images {
dels, err := client.ImageRemove(ctx, img, options)
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)
if err != nil {
return nil, err
}
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 {
targetRef, err := normalizeReference(opts.target)
if err != nil {
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) {
var (
ip net.IP
)
var ip net.IP
_, s, err := net.ParseCIDR(subnet)
if err != nil {

View File

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

View File

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

View File

@ -75,7 +75,8 @@ func TestNetworkList(t *testing.T) {
return []types.NetworkResource{
*NetworkResource(NetworkResourceName("network-2-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
clusterInfo swarm.ClusterInfo
}{
// Errors
{
context: formatter.Context{Format: "{{InvalidFunction}}"},

View File

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

View File

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

View File

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

View File

@ -12,7 +12,6 @@ import (
)
func TestRemoveErrors(t *testing.T) {
testCases := []struct {
args []string
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 {
serverAddress = registry.ConvertToHostname(serverAddress)
}
var authconfig = configtypes.AuthConfig{}
authconfig := configtypes.AuthConfig{}
var err error
if checkCredStore {
authconfig, err = cli.ConfigFile().GetAuthConfig(serverAddress)

View File

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

View File

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

View File

@ -24,10 +24,12 @@ func TestSecretCreateErrors(t *testing.T) {
secretCreateFunc func(swarm.SecretSpec) (types.SecretCreateResponse, error)
expectedError string
}{
{args: []string{"too", "many", "arguments"},
{
args: []string{"too", "many", "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",
},
{

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`,
},
// Table format
{formatter.Context{Format: NewFormat("table", false)},
{
formatter.Context{Format: NewFormat("table", false)},
`ID NAME DRIVER CREATED UPDATED
1 passwords Less than a second ago Less than a second ago
2 id_rsa Less than a second ago Less than a second ago
`},
{formatter.Context{Format: NewFormat("table {{.Name}}", true)},
`,
},
{
formatter.Context{Format: NewFormat("table {{.Name}}", true)},
`NAME
passwords
id_rsa
`},
{formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
`,
},
{
formatter.Context{Format: NewFormat("{{.ID}}-{{.Name}}", false)},
`1-passwords
2-id_rsa
`},
`,
},
}
secrets := []swarm.Secret{
{ID: "1",
{
ID: "1",
Meta: swarm.Meta{CreatedAt: time.Now(), UpdatedAt: time.Now()},
Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "passwords"}}},
{ID: "2",
Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "passwords"}},
},
{
ID: "2",
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 {
tc := tc

View File

@ -273,6 +273,7 @@ func (ctx *serviceInspectContext) HasLogDriver() bool {
func (ctx *serviceInspectContext) HasLogDriverName() bool {
return ctx.Service.Spec.TaskTemplate.LogDriver.Name != ""
}
func (ctx *serviceInspectContext) LogDriverName() string {
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)
}
}
func TestServiceContextWriteJSONField(t *testing.T) {
services := []swarm.Service{
{

View File

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

View File

@ -91,7 +91,8 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// Task with DesiredState beyond Running is ignored
tasks = append(tasks,
swarm.Task{ID: "1",
swarm.Task{
ID: "1",
NodeID: "a",
DesiredState: swarm.TaskStateShutdown,
Status: swarm.TaskStatus{State: swarm.TaskStateNew},
@ -140,7 +141,8 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// replacement task, not the old task.
tasks[0].DesiredState = swarm.TaskStateShutdown
tasks = append(tasks,
swarm.Task{ID: "2",
swarm.Task{
ID: "2",
NodeID: "b",
DesiredState: 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
// "start-then-stop" updates.
tasks = append(tasks,
swarm.Task{ID: "3",
swarm.Task{
ID: "3",
NodeID: "b",
DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStatePreparing},
@ -254,7 +257,8 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// Task with DesiredState beyond Running is ignored
tasks = append(tasks,
swarm.Task{ID: "1",
swarm.Task{
ID: "1",
NodeID: "a",
DesiredState: swarm.TaskStateShutdown,
Status: swarm.TaskStatus{State: swarm.TaskStateNew},
@ -304,7 +308,8 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// replacement task, not the old task.
tasks[0].DesiredState = swarm.TaskStateShutdown
tasks = append(tasks,
swarm.Task{ID: "2",
swarm.Task{
ID: "2",
NodeID: "a",
DesiredState: 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
// "start-then-stop" updates.
tasks = append(tasks,
swarm.Task{ID: "3",
swarm.Task{
ID: "3",
NodeID: "a",
DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStatePreparing},

View File

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

View File

@ -999,7 +999,6 @@ func updateDNSConfig(flags *pflag.FlagSet, config **swarm.DNSConfig) error {
for _, nameserver := range nameservers {
if _, exists := toRemove[nameserver]; !exists {
newConfig.Nameservers = append(newConfig.Nameservers, nameserver)
}
}
// 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) {
return s.listResult, nil
}
func (s secretAPIClientMock) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) {
return types.SecretCreateResponse{}, nil
}
func (s secretAPIClientMock) SecretRemove(ctx context.Context, id string) error {
return nil
}
func (s secretAPIClientMock) SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) {
return swarm.Secret{}, []byte{}, nil
}
func (s secretAPIClientMock) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error {
return nil
}

View File

@ -75,7 +75,6 @@ services:
}
func TestConfigMergeInterpolation(t *testing.T) {
for _, tt := range configMergeTests {
t.Run(tt.name, func(t *testing.T) {
firstConfig := []byte(tt.first)
@ -102,5 +101,4 @@ func TestConfigMergeInterpolation(t *testing.T) {
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)
expectedError string
}{
{
args: []string{},
expectedError: "requires exactly 1 argument",

View File

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

View File

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

View File

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

View File

@ -216,7 +216,8 @@ func TestUpdateSwarmSpecCertAndKey(t *testing.T) {
"--detach",
"--ca-cert=" + certfile,
"--ca-key=" + keyfile,
"--cert-expiry=3m"})
"--cert-expiry=3m",
})
cmd.SetOut(cli.OutBuffer())
assert.NilError(t, cmd.Execute())
@ -242,7 +243,8 @@ func TestUpdateSwarmSpecCertAndExternalCA(t *testing.T) {
"--rotate",
"--detach",
"--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())
assert.NilError(t, cmd.Execute())
@ -280,7 +282,8 @@ func TestUpdateSwarmSpecCertAndKeyAndExternalCA(t *testing.T) {
"--detach",
"--ca-cert=" + certfile,
"--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())
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.
// 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 {
// remove all quote characters
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
@ -63,7 +62,6 @@ func (s *ipNetSliceValue) Type() string {
// String defines a "native" format for this net.IPNet slice flag value.
func (s *ipNetSliceValue) String() string {
ipNetStrSlice := make([]string, len(*s.value))
for i, n := range *s.value {
ipNetStrSlice[i] = n.String()

View File

@ -69,7 +69,6 @@ func TestIPNetCalledTwice(t *testing.T) {
}
func TestIPNetBadQuoting(t *testing.T) {
tests := []struct {
Want []net.IPNet
FlagArg []string
@ -126,7 +125,8 @@ func TestIPNetBadQuoting(t *testing.T) {
},
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",
},
},
}

View File

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

View File

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

View File

@ -315,7 +315,6 @@ func TestPrettyPrintInfo(t *testing.T) {
prettyGolden: "docker-info-with-labels-empty",
},
{
doc: "info with swarm",
dockerInfo: info{
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 {
var inspectAutodetect = []struct {
inspectAutodetect := []struct {
objectType string
isSizeSupported bool
isSwarmObject bool

View File

@ -11,7 +11,7 @@ import (
)
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{
{Target: client.Target{Name: "target10-foo"}, Role: releasesRole},
{Target: client.Target{Name: "target1-foo"}, Role: releasesRole},

View File

@ -23,7 +23,8 @@ func TestTrustTag(t *testing.T) {
}{
{
trustTagContext{
s: SignedTagInfo{Name: trustedTag,
s: SignedTagInfo{
Name: trustedTag,
Digest: digest,
Signers: nil,
},
@ -33,7 +34,8 @@ func TestTrustTag(t *testing.T) {
},
{
trustTagContext{
s: SignedTagInfo{Name: trustedTag,
s: SignedTagInfo{
Name: trustedTag,
Digest: digest,
Signers: nil,
},
@ -44,7 +46,8 @@ func TestTrustTag(t *testing.T) {
// Empty signers makes a row with empty string
{
trustTagContext{
s: SignedTagInfo{Name: trustedTag,
s: SignedTagInfo{
Name: trustedTag,
Digest: digest,
Signers: nil,
},
@ -54,7 +57,8 @@ func TestTrustTag(t *testing.T) {
},
{
trustTagContext{
s: SignedTagInfo{Name: trustedTag,
s: SignedTagInfo{
Name: trustedTag,
Digest: digest,
Signers: []string{"alice", "bob", "claire"},
},
@ -65,7 +69,8 @@ func TestTrustTag(t *testing.T) {
// alphabetic signing on Signers
{
trustTagContext{
s: SignedTagInfo{Name: trustedTag,
s: SignedTagInfo{
Name: trustedTag,
Digest: digest,
Signers: []string{"claire", "bob", "alice"},
},
@ -85,7 +90,6 @@ func TestTrustTag(t *testing.T) {
}
func TestTrustTagContextWrite(t *testing.T) {
cases := []struct {
context formatter.Context
expected string
@ -140,7 +144,6 @@ tag3 bbbbbbbb
// 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
func TestTrustTagContextEmptyWrite(t *testing.T) {
emptyCase := struct {
context formatter.Context
expected string

View File

@ -8,8 +8,10 @@ import (
"github.com/theupdateframework/notary/tuf/data"
)
const releasedRoleName = "Repo Admin"
const releasesRoleTUFName = "targets/releases"
const (
releasedRoleName = "Repo Admin"
releasesRoleTUFName = "targets/releases"
)
// isReleasedTarget checks if a role name is "released":
// 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))
})
}
}
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})
hash, _, _ := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased")
assert.Check(t, is.DeepEqual(data.Hashes{notary.SHA256: []byte("released-hash")}, hash))
}
func TestCreateTarget(t *testing.T) {
@ -280,5 +279,4 @@ func TestSignCommandLocalFlag(t *testing.T) {
cmd.SetArgs([]string{"--local", "reg-name.io/image:red"})
cmd.SetOut(io.Discard)
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()
assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError))
}
}
func TestRemoveSingleSigner(t *testing.T) {
@ -89,6 +88,7 @@ func TestRemoveMultipleSigners(t *testing.T) {
"no signer test for repository signed-repo"))
assert.Check(t, is.Contains(cli.OutBuffer().String(), "Removing signer \"test\" from signed-repo...\n"))
}
func TestRemoveLastSignerWarning(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{})
cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -170,8 +170,10 @@ func toServiceVolumeConfigsSlice(dst reflect.Value, m map[interface{}]interface{
return nil
}
type tomapFn func(s interface{}) (map[interface{}]interface{}, error)
type writeValueFromMapFn func(reflect.Value, map[interface{}]interface{}) error
type (
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 {
return func(dst, src reflect.Value) error {

View File

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

View File

@ -6,8 +6,10 @@ import (
"strings"
)
var delimiter = "\\$"
var substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?"
var (
delimiter = "\\$"
substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?"
)
var patternString = fmt.Sprintf(
"%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 {
return c.localAddr
}
func (c *commandConn) RemoteAddr() net.Addr {
return c.remoteAddr
}
func (c *commandConn) SetDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetDeadline(%v)", t)
return nil
}
func (c *commandConn) SetReadDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetReadDeadline(%v)", t)
return nil
}
func (c *commandConn) SetWriteDeadline(t time.Time) error {
logrus.Debugf("unimplemented call: SetWriteDeadline(%v)", t)
return nil

View File

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

View File

@ -102,7 +102,7 @@ func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo
return nil, err
}
var cfg = tlsconfig.ClientDefault()
cfg := tlsconfig.ClientDefault()
cfg.InsecureSkipVerify = !repoInfo.Index.Secure
// Get certificate base directory
@ -287,7 +287,6 @@ func GetSignableRoles(repo client.Repository, target *client.Target) ([]data.Rol
}
return signableRoles, nil
}
// 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
func (imgRefAuth *ImageRefAndAuth) Name() string {
return imgRefAuth.original
}

View File

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

View File

@ -6,9 +6,7 @@ import (
"github.com/docker/docker/api/types/swarm"
)
var (
defaultTime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
)
var defaultTime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
// Task creates a task with default values .
// 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{
{Role: rootRole},
{Role: targetsRole}}, nil
{Role: targetsRole},
}, nil
}
// GetDelegationRoles returns the keys and roles of the repository's delegations
@ -306,6 +307,7 @@ var loadedReleasesRole = data.DelegationRole{
Threshold: 1,
},
}
var loadedAliceRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: "targets/alice",
@ -313,6 +315,7 @@ var loadedAliceRole = data.DelegationRole{
Threshold: 1,
},
}
var loadedBobRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: "targets/bob",
@ -320,6 +323,7 @@ var loadedBobRole = data.DelegationRole{
Threshold: 1,
},
}
var loadedDelegationRoles = []data.Role{
{
Name: loadedReleasesRole.Name,
@ -343,6 +347,7 @@ var loadedDelegationRoles = []data.Role{
},
},
}
var loadedTargetsRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: data.CanonicalTargetsRole,
@ -359,14 +364,17 @@ var loadedRedTarget = client.Target{
Name: "red",
Hashes: data.Hashes{"sha256": []byte("red-digest")},
}
var loadedBlueTarget = client.Target{
Name: "blue",
Hashes: data.Hashes{"sha256": []byte("blue-digest")},
}
var loadedGreenTarget = client.Target{
Name: "green",
Hashes: data.Hashes{"sha256": []byte("green-digest")},
}
var loadedTargets = []client.TargetSignedStruct{
// red is signed by all three delegations
{Target: loadedRedTarget, Role: loadedReleasesRole},

View File

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

View File

@ -94,9 +94,7 @@ func TestParseDockerDaemonHost(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{
"tcp:a.b.c.d": "",
"tcp:a.b.c.d/path": "",

View File

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

View File

@ -230,7 +230,7 @@ type ValidatorFctListType func(val string) ([]string, error)
// ValidateIPAddress validates an Ip address.
func ValidateIPAddress(val string) (string, error) {
var ip = net.ParseIP(strings.TrimSpace(val))
ip := net.ParseIP(strings.TrimSpace(val))
if ip != 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 != "" {
t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err)
}
}
func TestMapOpts(t *testing.T) {
@ -88,7 +87,6 @@ func TestListOptsWithoutValidator(t *testing.T) {
if len(mapListOpts) != 1 {
t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts)
}
}
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) {
var contains = false
contains := false
for _, portConfig := range portConfigs {
if portConfig == expected {
contains = true