golangci-lint: govet: enable shadow check

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-11-20 13:04:09 +01:00
parent 606cbd60a1
commit 2d61f70f00
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
9 changed files with 81 additions and 74 deletions

View File

@ -42,7 +42,10 @@ linters-settings:
gocyclo: gocyclo:
min-complexity: 16 min-complexity: 16
govet: govet:
check-shadowing: false check-shadowing: true
settings:
shadow:
strict: true
lll: lll:
line-length: 200 line-length: 200
nakedret: nakedret:
@ -128,6 +131,12 @@ issues:
- errcheck - errcheck
- gosec - gosec
# Allow "err" and "ok" vars to shadow existing declarations, otherwise we get too many false positives.
- text: '^shadow: declaration of "(err|ok)" shadows declaration'
linters:
- govet
# Maximum issues count per one linter. Set to 0 to disable. Default is 50. # Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0 max-issues-per-linter: 0

View File

@ -198,7 +198,7 @@ func TestParseWithVolumes(t *testing.T) {
t.Fatalf("Error parsing volume flags, %q should not mount-bind anything. Received %v", tryit, hostConfig.Binds) t.Fatalf("Error parsing volume flags, %q should not mount-bind anything. Received %v", tryit, hostConfig.Binds)
} else if _, exists := config.Volumes[arr[0]]; !exists { } else if _, exists := config.Volumes[arr[0]]; !exists {
t.Fatalf("Error parsing volume flags, %s is missing from volumes. Received %v", arr[0], config.Volumes) t.Fatalf("Error parsing volume flags, %s is missing from volumes. Received %v", arr[0], config.Volumes)
} else if _, exists := config.Volumes[arr[1]]; !exists { } else if _, exists := config.Volumes[arr[1]]; !exists { //nolint:govet // ignore shadow-check
t.Fatalf("Error parsing volume flags, %s is missing from volumes. Received %v", arr[1], config.Volumes) t.Fatalf("Error parsing volume flags, %s is missing from volumes. Received %v", arr[1], config.Volumes)
} }

View File

@ -77,13 +77,13 @@ func runPush(dockerCli command.Cli, opts pushOpts) error {
return errors.Errorf("%s not found", targetRef) return errors.Errorf("%s not found", targetRef)
} }
pushRequest, err := buildPushRequest(manifests, targetRef, opts.insecure) req, err := buildPushRequest(manifests, targetRef, opts.insecure)
if err != nil { if err != nil {
return err return err
} }
ctx := context.Background() ctx := context.Background()
if err := pushList(ctx, dockerCli, pushRequest); err != nil { if err := pushList(ctx, dockerCli, req); err != nil {
return err return err
} }
if opts.purge { if opts.purge {

View File

@ -49,17 +49,17 @@ func TestManifestPushErrors(t *testing.T) {
} }
func TestManifestPush(t *testing.T) { func TestManifestPush(t *testing.T) {
store := store.NewStore(t.TempDir()) manifestStore := store.NewStore(t.TempDir())
registry := newFakeRegistryClient() registry := newFakeRegistryClient()
cli := test.NewFakeCli(nil) cli := test.NewFakeCli(nil)
cli.SetManifestStore(store) cli.SetManifestStore(manifestStore)
cli.SetRegistryClient(registry) cli.SetRegistryClient(registry)
namedRef := ref(t, "alpine:3.0") namedRef := ref(t, "alpine:3.0")
imageManifest := fullImageManifest(t, namedRef) imageManifest := fullImageManifest(t, namedRef)
err := store.Save(ref(t, "list:v1"), namedRef, imageManifest) err := manifestStore.Save(ref(t, "list:v1"), namedRef, imageManifest)
assert.NilError(t, err) assert.NilError(t, err)
cmd := newPushListCommand(cli) cmd := newPushListCommand(cli)

View File

@ -70,7 +70,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
} }
p := &mockProgress{} p := &mockProgress{}
updaterTester := updaterTester{ ut := updaterTester{
t: t, t: t,
updater: &replicatedProgressUpdater{ updater: &replicatedProgressUpdater{
progressOut: p, progressOut: p,
@ -82,7 +82,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
tasks := []swarm.Task{} tasks := []swarm.Task{}
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
{ID: "1/1", Action: " "}, {ID: "1/1", Action: " "},
@ -97,14 +97,14 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
DesiredState: swarm.TaskStateShutdown, DesiredState: swarm.TaskStateShutdown,
Status: swarm.TaskStatus{State: swarm.TaskStateNew}, Status: swarm.TaskStatus{State: swarm.TaskStateNew},
}) })
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
}) })
// Task with valid DesiredState and State updates progress bar // Task with valid DesiredState and State updates progress bar
tasks[0].DesiredState = swarm.TaskStateRunning tasks[0].DesiredState = swarm.TaskStateRunning
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "1/1", Action: "new ", Current: 1, Total: 9, HideCounts: true}, {ID: "1/1", Action: "new ", Current: 1, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -113,7 +113,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// If the task exposes an error, we should show that instead of the // If the task exposes an error, we should show that instead of the
// progress bar. // progress bar.
tasks[0].Status.Err = "something is wrong" tasks[0].Status.Err = "something is wrong"
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "1/1", Action: "something is wrong"}, {ID: "1/1", Action: "something is wrong"},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -122,7 +122,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// When the task reaches running, update should return true // When the task reaches running, update should return true
tasks[0].Status.Err = "" tasks[0].Status.Err = ""
tasks[0].Status.State = swarm.TaskStateRunning tasks[0].Status.State = swarm.TaskStateRunning
updaterTester.testUpdater(tasks, true, ut.testUpdater(tasks, true,
[]progress.Progress{ []progress.Progress{
{ID: "1/1", Action: "running ", Current: 9, Total: 9, HideCounts: true}, {ID: "1/1", Action: "running ", Current: 9, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "1 out of 1 tasks"}, {ID: "overall progress", Action: "1 out of 1 tasks"},
@ -131,7 +131,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
// If the task fails, update should return false again // If the task fails, update should return false again
tasks[0].Status.Err = "task failed" tasks[0].Status.Err = "task failed"
tasks[0].Status.State = swarm.TaskStateFailed tasks[0].Status.State = swarm.TaskStateFailed
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "1/1", Action: "task failed"}, {ID: "1/1", Action: "task failed"},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -147,7 +147,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStateRunning}, Status: swarm.TaskStatus{State: swarm.TaskStateRunning},
}) })
updaterTester.testUpdater(tasks, true, ut.testUpdater(tasks, true,
[]progress.Progress{ []progress.Progress{
{ID: "1/1", Action: "running ", Current: 9, Total: 9, HideCounts: true}, {ID: "1/1", Action: "running ", Current: 9, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "1 out of 1 tasks"}, {ID: "overall progress", Action: "1 out of 1 tasks"},
@ -162,7 +162,7 @@ func TestReplicatedProgressUpdaterOneReplica(t *testing.T) {
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStatePreparing}, Status: swarm.TaskStatus{State: swarm.TaskStatePreparing},
}) })
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "1/1", Action: "preparing", Current: 6, Total: 9, HideCounts: true}, {ID: "1/1", Action: "preparing", Current: 6, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -183,7 +183,7 @@ func TestReplicatedProgressUpdaterManyReplicas(t *testing.T) {
} }
p := &mockProgress{} p := &mockProgress{}
updaterTester := updaterTester{ ut := updaterTester{
t: t, t: t,
updater: &replicatedProgressUpdater{ updater: &replicatedProgressUpdater{
progressOut: p, progressOut: p,
@ -196,7 +196,7 @@ func TestReplicatedProgressUpdaterManyReplicas(t *testing.T) {
tasks := []swarm.Task{} tasks := []swarm.Task{}
// No per-task progress bars because there are too many replicas // No per-task progress bars because there are too many replicas
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", replicas)}, {ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", replicas)},
{ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", replicas)}, {ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", replicas)},
@ -215,13 +215,13 @@ func TestReplicatedProgressUpdaterManyReplicas(t *testing.T) {
if i%2 == 1 { if i%2 == 1 {
tasks[i].NodeID = "b" tasks[i].NodeID = "b"
} }
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", i, replicas)}, {ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", i, replicas)},
}) })
tasks[i].Status.State = swarm.TaskStateRunning tasks[i].Status.State = swarm.TaskStateRunning
updaterTester.testUpdater(tasks, uint64(i) == replicas-1, ut.testUpdater(tasks, uint64(i) == replicas-1,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", i+1, replicas)}, {ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", i+1, replicas)},
}) })
@ -238,7 +238,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
} }
p := &mockProgress{} p := &mockProgress{}
updaterTester := updaterTester{ ut := updaterTester{
t: t, t: t,
updater: &globalProgressUpdater{ updater: &globalProgressUpdater{
progressOut: p, progressOut: p,
@ -250,7 +250,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
tasks := []swarm.Task{} tasks := []swarm.Task{}
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: "waiting for new tasks"}, {ID: "overall progress", Action: "waiting for new tasks"},
}) })
@ -263,7 +263,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
DesiredState: swarm.TaskStateShutdown, DesiredState: swarm.TaskStateShutdown,
Status: swarm.TaskStatus{State: swarm.TaskStateNew}, Status: swarm.TaskStatus{State: swarm.TaskStateNew},
}) })
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -271,7 +271,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// Task with valid DesiredState and State updates progress bar // Task with valid DesiredState and State updates progress bar
tasks[0].DesiredState = swarm.TaskStateRunning tasks[0].DesiredState = swarm.TaskStateRunning
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "a", Action: "new ", Current: 1, Total: 9, HideCounts: true}, {ID: "a", Action: "new ", Current: 1, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -280,7 +280,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// If the task exposes an error, we should show that instead of the // If the task exposes an error, we should show that instead of the
// progress bar. // progress bar.
tasks[0].Status.Err = "something is wrong" tasks[0].Status.Err = "something is wrong"
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "a", Action: "something is wrong"}, {ID: "a", Action: "something is wrong"},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -289,7 +289,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// When the task reaches running, update should return true // When the task reaches running, update should return true
tasks[0].Status.Err = "" tasks[0].Status.Err = ""
tasks[0].Status.State = swarm.TaskStateRunning tasks[0].Status.State = swarm.TaskStateRunning
updaterTester.testUpdater(tasks, true, ut.testUpdater(tasks, true,
[]progress.Progress{ []progress.Progress{
{ID: "a", Action: "running ", Current: 9, Total: 9, HideCounts: true}, {ID: "a", Action: "running ", Current: 9, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "1 out of 1 tasks"}, {ID: "overall progress", Action: "1 out of 1 tasks"},
@ -298,7 +298,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
// If the task fails, update should return false again // If the task fails, update should return false again
tasks[0].Status.Err = "task failed" tasks[0].Status.Err = "task failed"
tasks[0].Status.State = swarm.TaskStateFailed tasks[0].Status.State = swarm.TaskStateFailed
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "a", Action: "task failed"}, {ID: "a", Action: "task failed"},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -314,7 +314,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStateRunning}, Status: swarm.TaskStatus{State: swarm.TaskStateRunning},
}) })
updaterTester.testUpdater(tasks, true, ut.testUpdater(tasks, true,
[]progress.Progress{ []progress.Progress{
{ID: "a", Action: "running ", Current: 9, Total: 9, HideCounts: true}, {ID: "a", Action: "running ", Current: 9, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "1 out of 1 tasks"}, {ID: "overall progress", Action: "1 out of 1 tasks"},
@ -329,7 +329,7 @@ func TestGlobalProgressUpdaterOneNode(t *testing.T) {
DesiredState: swarm.TaskStateRunning, DesiredState: swarm.TaskStateRunning,
Status: swarm.TaskStatus{State: swarm.TaskStatePreparing}, Status: swarm.TaskStatus{State: swarm.TaskStatePreparing},
}) })
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "a", Action: "preparing", Current: 6, Total: 9, HideCounts: true}, {ID: "a", Action: "preparing", Current: 6, Total: 9, HideCounts: true},
{ID: "overall progress", Action: "0 out of 1 tasks"}, {ID: "overall progress", Action: "0 out of 1 tasks"},
@ -348,7 +348,7 @@ func TestGlobalProgressUpdaterManyNodes(t *testing.T) {
} }
p := &mockProgress{} p := &mockProgress{}
updaterTester := updaterTester{ ut := updaterTester{
t: t, t: t,
updater: &globalProgressUpdater{ updater: &globalProgressUpdater{
progressOut: p, progressOut: p,
@ -359,12 +359,12 @@ func TestGlobalProgressUpdaterManyNodes(t *testing.T) {
} }
for i := 0; i != nodes; i++ { for i := 0; i != nodes; i++ {
updaterTester.activeNodes[strconv.Itoa(i)] = struct{}{} ut.activeNodes[strconv.Itoa(i)] = struct{}{}
} }
tasks := []swarm.Task{} tasks := []swarm.Task{}
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: "waiting for new tasks"}, {ID: "overall progress", Action: "waiting for new tasks"},
}) })
@ -379,7 +379,7 @@ func TestGlobalProgressUpdaterManyNodes(t *testing.T) {
}) })
} }
updaterTester.testUpdater(tasks, false, ut.testUpdater(tasks, false,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", nodes)}, {ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", nodes)},
{ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", nodes)}, {ID: "overall progress", Action: fmt.Sprintf("0 out of %d tasks", nodes)},
@ -387,7 +387,7 @@ func TestGlobalProgressUpdaterManyNodes(t *testing.T) {
for i := 0; i != nodes; i++ { for i := 0; i != nodes; i++ {
tasks[i].Status.State = swarm.TaskStateRunning tasks[i].Status.State = swarm.TaskStateRunning
updaterTester.testUpdater(tasks, i == nodes-1, ut.testUpdater(tasks, i == nodes-1,
[]progress.Progress{ []progress.Progress{
{ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", i+1, nodes)}, {ID: "overall progress", Action: fmt.Sprintf("%d out of %d tasks", i+1, nodes)},
}) })

View File

@ -35,7 +35,7 @@ type clientInfo struct {
Warnings []string Warnings []string
} }
type info struct { type dockerInfo struct {
// This field should/could be ServerInfo but is anonymous to // This field should/could be ServerInfo but is anonymous to
// preserve backwards compatibility in the JSON rendering // preserve backwards compatibility in the JSON rendering
// which has ServerInfo immediately within the top-level // which has ServerInfo immediately within the top-level
@ -48,7 +48,7 @@ type info struct {
ClientErrors []string `json:",omitempty"` ClientErrors []string `json:",omitempty"`
} }
func (i *info) clientPlatform() string { func (i *dockerInfo) clientPlatform() string {
if i.ClientInfo != nil && i.ClientInfo.Platform != nil { if i.ClientInfo != nil && i.ClientInfo.Platform != nil {
return i.ClientInfo.Platform.Name return i.ClientInfo.Platform.Name
} }
@ -78,7 +78,7 @@ func NewInfoCommand(dockerCli command.Cli) *cobra.Command {
} }
func runInfo(cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error { func runInfo(cmd *cobra.Command, dockerCli command.Cli, opts *infoOptions) error {
info := info{ info := dockerInfo{
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
// Don't pass a dockerCLI to newClientVersion(), because we currently // Don't pass a dockerCLI to newClientVersion(), because we currently
// don't include negotiated API version, and want to avoid making an // don't include negotiated API version, and want to avoid making an
@ -129,7 +129,7 @@ var placeHolders = regexp.MustCompile(`\.[a-zA-Z]`)
// If only client-side information is used in the template, we can skip // If only client-side information is used in the template, we can skip
// connecting to the daemon. This allows (e.g.) to only get cli-plugin // connecting to the daemon. This allows (e.g.) to only get cli-plugin
// information, without also making a (potentially expensive) API call. // information, without also making a (potentially expensive) API call.
func needsServerInfo(template string, info info) bool { func needsServerInfo(template string, info dockerInfo) bool {
if len(template) == 0 || placeHolders.FindString(template) == "" { if len(template) == 0 || placeHolders.FindString(template) == "" {
// The template is empty, or does not contain formatting fields // The template is empty, or does not contain formatting fields
// (e.g. `table` or `raw` or `{{ json .}}`). Assume we need server-side // (e.g. `table` or `raw` or `{{ json .}}`). Assume we need server-side
@ -160,7 +160,7 @@ func needsServerInfo(template string, info info) bool {
return err != nil return err != nil
} }
func prettyPrintInfo(streams command.Streams, info info) error { func prettyPrintInfo(streams command.Streams, info dockerInfo) error {
// Only append the platform info if it's not empty, to prevent printing a trailing space. // Only append the platform info if it's not empty, to prevent printing a trailing space.
if p := info.clientPlatform(); p != "" { if p := info.clientPlatform(); p != "" {
fprintln(streams.Out(), "Client:", p) fprintln(streams.Out(), "Client:", p)
@ -215,7 +215,7 @@ func prettyPrintClientInfo(streams command.Streams, info clientInfo) {
} }
//nolint:gocyclo //nolint:gocyclo
func prettyPrintServerInfo(streams command.Streams, info *info) []error { func prettyPrintServerInfo(streams command.Streams, info *dockerInfo) []error {
var errs []error var errs []error
output := streams.Out() output := streams.Out()
@ -452,7 +452,7 @@ func printSwarmInfo(output io.Writer, info system.Info) {
} }
} }
func printServerWarnings(stdErr io.Writer, info *info) { func printServerWarnings(stdErr io.Writer, info *dockerInfo) {
if versions.LessThan(info.ClientInfo.APIVersion, "1.42") { if versions.LessThan(info.ClientInfo.APIVersion, "1.42") {
printSecurityOptionsWarnings(stdErr, *info.Info) printSecurityOptionsWarnings(stdErr, *info.Info)
} }
@ -530,7 +530,7 @@ func printServerWarningsLegacy(stdErr io.Writer, info system.Info) {
} }
} }
func formatInfo(output io.Writer, info info, format string) error { func formatInfo(output io.Writer, info dockerInfo, format string) error {
if format == formatter.JSONFormatKey { if format == formatter.JSONFormatKey {
format = formatter.JSONFormat format = formatter.JSONFormat
} }

View File

@ -267,7 +267,7 @@ func TestPrettyPrintInfo(t *testing.T) {
for _, tc := range []struct { for _, tc := range []struct {
doc string doc string
dockerInfo info dockerInfo dockerInfo
prettyGolden string prettyGolden string
warningsGolden string warningsGolden string
@ -276,7 +276,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}{ }{
{ {
doc: "info without swarm", doc: "info without swarm",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &sampleInfoNoSwarm, Info: &sampleInfoNoSwarm,
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
clientVersion: clientVersion{ clientVersion: clientVersion{
@ -292,7 +292,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "info with plugins", doc: "info with plugins",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &sampleInfoNoSwarm, Info: &sampleInfoNoSwarm,
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
clientVersion: clientVersion{Context: "default"}, clientVersion: clientVersion{Context: "default"},
@ -305,7 +305,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "info with nil labels", doc: "info with nil labels",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &sampleInfoLabelsNil, Info: &sampleInfoLabelsNil,
ClientInfo: &clientInfo{clientVersion: clientVersion{Context: "default"}}, ClientInfo: &clientInfo{clientVersion: clientVersion{Context: "default"}},
}, },
@ -313,7 +313,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "info with empty labels", doc: "info with empty labels",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &sampleInfoLabelsEmpty, Info: &sampleInfoLabelsEmpty,
ClientInfo: &clientInfo{clientVersion: clientVersion{Context: "default"}}, ClientInfo: &clientInfo{clientVersion: clientVersion{Context: "default"}},
}, },
@ -321,7 +321,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "info with swarm", doc: "info with swarm",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &infoWithSwarm, Info: &infoWithSwarm,
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
clientVersion: clientVersion{Context: "default"}, clientVersion: clientVersion{Context: "default"},
@ -333,7 +333,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "info with legacy warnings", doc: "info with legacy warnings",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &infoWithWarningsLinux, Info: &infoWithWarningsLinux,
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
clientVersion: clientVersion{ clientVersion: clientVersion{
@ -350,7 +350,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "info with daemon warnings", doc: "info with daemon warnings",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &sampleInfoDaemonWarnings, Info: &sampleInfoDaemonWarnings,
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
clientVersion: clientVersion{ clientVersion: clientVersion{
@ -367,7 +367,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "errors for both", doc: "errors for both",
dockerInfo: info{ dockerInfo: dockerInfo{
ServerErrors: []string{"a server error occurred"}, ServerErrors: []string{"a server error occurred"},
ClientErrors: []string{"a client error occurred"}, ClientErrors: []string{"a client error occurred"},
}, },
@ -378,7 +378,7 @@ func TestPrettyPrintInfo(t *testing.T) {
}, },
{ {
doc: "bad security info", doc: "bad security info",
dockerInfo: info{ dockerInfo: dockerInfo{
Info: &sampleInfoBadSecurity, Info: &sampleInfoBadSecurity,
ServerErrors: []string{"a server error occurred"}, ServerErrors: []string{"a server error occurred"},
ClientInfo: &clientInfo{Debug: false}, ClientInfo: &clientInfo{Debug: false},
@ -424,7 +424,7 @@ func BenchmarkPrettyPrintInfo(b *testing.B) {
infoWithSwarm := sampleInfoNoSwarm infoWithSwarm := sampleInfoNoSwarm
infoWithSwarm.Swarm = sampleSwarmInfo infoWithSwarm.Swarm = sampleSwarmInfo
dockerInfo := info{ info := dockerInfo{
Info: &infoWithSwarm, Info: &infoWithSwarm,
ClientInfo: &clientInfo{ ClientInfo: &clientInfo{
clientVersion: clientVersion{ clientVersion: clientVersion{
@ -439,7 +439,7 @@ func BenchmarkPrettyPrintInfo(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = prettyPrintInfo(cli, dockerInfo) _ = prettyPrintInfo(cli, info)
cli.ResetOutputBuffers() cli.ResetOutputBuffers()
} }
} }
@ -470,7 +470,7 @@ func TestFormatInfo(t *testing.T) {
tc := tc tc := tc
t.Run(tc.doc, func(t *testing.T) { t.Run(tc.doc, func(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
info := info{ info := dockerInfo{
Info: &sampleInfoNoSwarm, Info: &sampleInfoNoSwarm,
ClientInfo: &clientInfo{Debug: true}, ClientInfo: &clientInfo{Debug: true},
} }
@ -531,7 +531,7 @@ func TestNeedsServerInfo(t *testing.T) {
}, },
} }
inf := info{ClientInfo: &clientInfo{}} inf := dockerInfo{ClientInfo: &clientInfo{}}
for _, tc := range tests { for _, tc := range tests {
tc := tc tc := tc
t.Run(tc.doc, func(t *testing.T) { t.Run(tc.doc, func(t *testing.T) {

View File

@ -114,10 +114,10 @@ var testKeys = map[string][]byte{
func TestLoadKeyFromPath(t *testing.T) { func TestLoadKeyFromPath(t *testing.T) {
skip.If(t, runtime.GOOS == "windows") skip.If(t, runtime.GOOS == "windows")
for keyID, keyBytes := range testKeys { for keyID, keyBytes := range testKeys {
privKeyID, privKeyFixture := keyID, keyBytes keyID, keyBytes := keyID, keyBytes
t.Run(fmt.Sprintf("load-key-id-%s-from-path", keyID), func(t *testing.T) { t.Run(fmt.Sprintf("load-key-id-%s-from-path", keyID), func(t *testing.T) {
privKeyFilepath := filepath.Join(t.TempDir(), "privkey.pem") privKeyFilepath := filepath.Join(t.TempDir(), "privkey.pem")
assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms)) assert.NilError(t, os.WriteFile(privKeyFilepath, keyBytes, notary.PrivNoExecPerms))
keyStorageDir := t.TempDir() keyStorageDir := t.TempDir()
@ -135,7 +135,7 @@ func TestLoadKeyFromPath(t *testing.T) {
assert.Check(t, loadPrivKeyBytesToStore(privKeyBytes, privKeyImporters, privKeyFilepath, "signer-name", cannedPasswordRetriever)) assert.Check(t, loadPrivKeyBytesToStore(privKeyBytes, privKeyImporters, privKeyFilepath, "signer-name", cannedPasswordRetriever))
// check that the appropriate ~/<trust_dir>/private/<key_id>.key file exists // check that the appropriate ~/<trust_dir>/private/<key_id>.key file exists
expectedImportKeyPath := filepath.Join(keyStorageDir, notary.PrivDir, privKeyID+"."+notary.KeyExtension) expectedImportKeyPath := filepath.Join(keyStorageDir, notary.PrivDir, keyID+"."+notary.KeyExtension)
_, err = os.Stat(expectedImportKeyPath) _, err = os.Stat(expectedImportKeyPath)
assert.NilError(t, err) assert.NilError(t, err)
@ -152,7 +152,7 @@ func TestLoadKeyFromPath(t *testing.T) {
decryptedKey, err := tufutils.ParsePKCS8ToTufKey(keyPEM.Bytes, []byte(passwd)) decryptedKey, err := tufutils.ParsePKCS8ToTufKey(keyPEM.Bytes, []byte(passwd))
assert.NilError(t, err) assert.NilError(t, err)
fixturePEM, _ := pem.Decode(privKeyFixture) fixturePEM, _ := pem.Decode(keyBytes)
assert.Check(t, is.DeepEqual(fixturePEM.Bytes, decryptedKey.Private())) assert.Check(t, is.DeepEqual(fixturePEM.Bytes, decryptedKey.Private()))
}) })
} }
@ -161,11 +161,11 @@ func TestLoadKeyFromPath(t *testing.T) {
func TestLoadKeyTooPermissive(t *testing.T) { func TestLoadKeyTooPermissive(t *testing.T) {
skip.If(t, runtime.GOOS == "windows") skip.If(t, runtime.GOOS == "windows")
for keyID, keyBytes := range testKeys { for keyID, keyBytes := range testKeys {
keyID, privKeyFixture := keyID, keyBytes keyID, keyBytes := keyID, keyBytes
t.Run(fmt.Sprintf("load-key-id-%s-too-permissive", keyID), func(t *testing.T) { t.Run(fmt.Sprintf("load-key-id-%s-too-permissive", keyID), func(t *testing.T) {
privKeyDir := t.TempDir() privKeyDir := t.TempDir()
privKeyFilepath := filepath.Join(privKeyDir, "privkey477.pem") privKeyFilepath := filepath.Join(privKeyDir, "privkey477.pem")
assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0o477)) assert.NilError(t, os.WriteFile(privKeyFilepath, keyBytes, 0o477))
// import the key to our keyStorageDir // import the key to our keyStorageDir
_, err := getPrivKeyBytesFromPath(privKeyFilepath) _, err := getPrivKeyBytesFromPath(privKeyFilepath)
@ -173,27 +173,27 @@ func TestLoadKeyTooPermissive(t *testing.T) {
assert.Error(t, err, expected) assert.Error(t, err, expected)
privKeyFilepath = filepath.Join(privKeyDir, "privkey667.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey667.pem")
assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0o677)) assert.NilError(t, os.WriteFile(privKeyFilepath, keyBytes, 0o677))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath)
assert.Error(t, err, expected) assert.Error(t, err, expected)
privKeyFilepath = filepath.Join(privKeyDir, "privkey777.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey777.pem")
assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0o777)) assert.NilError(t, os.WriteFile(privKeyFilepath, keyBytes, 0o777))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath)
assert.Error(t, err, expected) assert.Error(t, err, expected)
privKeyFilepath = filepath.Join(privKeyDir, "privkey400.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey400.pem")
assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0o400)) assert.NilError(t, os.WriteFile(privKeyFilepath, keyBytes, 0o400))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
assert.NilError(t, err) assert.NilError(t, err)
privKeyFilepath = filepath.Join(privKeyDir, "privkey600.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey600.pem")
assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0o600)) assert.NilError(t, os.WriteFile(privKeyFilepath, keyBytes, 0o600))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -6,17 +6,15 @@ import (
"strings" "strings"
) )
var ( const (
delimiter = "\\$" delimiter = "\\$"
substitution = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?" subst = "[_a-z][_a-z0-9]*(?::?[-?][^}]*)?"
) )
var patternString = fmt.Sprintf( var defaultPattern = regexp.MustCompile(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>))",
delimiter, delimiter, substitution, substitution, delimiter, delimiter, subst, subst,
) ))
var defaultPattern = regexp.MustCompile(patternString)
// DefaultSubstituteFuncs contains the default SubstituteFunc used by the docker cli // DefaultSubstituteFuncs contains the default SubstituteFunc used by the docker cli
var DefaultSubstituteFuncs = []SubstituteFunc{ var DefaultSubstituteFuncs = []SubstituteFunc{