From 71d650ee17a7842c75509369f9b03200db906645 Mon Sep 17 00:00:00 2001 From: Arash Deshmeh Date: Sun, 8 Jul 2018 15:08:17 -0400 Subject: [PATCH] refactored cli/compose and cli/command/trust to use sort.Slice and removed custom types used for sorting Signed-off-by: Arash Deshmeh --- cli/command/formatter/trust.go | 15 ------------ cli/command/formatter/trust_test.go | 2 +- cli/command/registry/search.go | 15 ++++-------- cli/command/trust/common.go | 36 ++++++++++------------------- cli/command/trust/inspect_pretty.go | 8 ++++--- cli/compose/convert/service.go | 21 ++++++----------- cli/compose/convert/service_test.go | 19 +-------------- cli/compose/loader/loader_test.go | 10 +++----- 8 files changed, 33 insertions(+), 93 deletions(-) diff --git a/cli/command/formatter/trust.go b/cli/command/formatter/trust.go index c16df2e100..42f9d4509c 100644 --- a/cli/command/formatter/trust.go +++ b/cli/command/formatter/trust.go @@ -133,18 +133,3 @@ func (c *signerInfoContext) Keys() string { func (c *signerInfoContext) Signer() string { return c.s.Name } - -// SignerInfoList helps sort []SignerInfo by signer names -type SignerInfoList []SignerInfo - -func (signerInfoComp SignerInfoList) Len() int { - return len(signerInfoComp) -} - -func (signerInfoComp SignerInfoList) Less(i, j int) bool { - return signerInfoComp[i].Name < signerInfoComp[j].Name -} - -func (signerInfoComp SignerInfoList) Swap(i, j int) { - signerInfoComp[i], signerInfoComp[j] = signerInfoComp[j], signerInfoComp[i] -} diff --git a/cli/command/formatter/trust_test.go b/cli/command/formatter/trust_test.go index 7e1d894fbd..c84ecd2951 100644 --- a/cli/command/formatter/trust_test.go +++ b/cli/command/formatter/trust_test.go @@ -222,7 +222,7 @@ eve foobarbazquxquux, key31, key32 } for _, testcase := range cases { - signerInfo := SignerInfoList{ + signerInfo := []SignerInfo{ {Name: "alice", Keys: []string{"key11", "key12"}}, {Name: "bob", Keys: []string{"key21"}}, {Name: "eve", Keys: []string{"key31", "key32", "foobarbazquxquux"}}, diff --git a/cli/command/registry/search.go b/cli/command/registry/search.go index 1af6fcd5ce..f048752218 100644 --- a/cli/command/registry/search.go +++ b/cli/command/registry/search.go @@ -9,7 +9,6 @@ import ( "github.com/docker/cli/cli/command/formatter" "github.com/docker/cli/opts" "github.com/docker/docker/api/types" - registrytypes "github.com/docker/docker/api/types/registry" "github.com/docker/docker/registry" "github.com/spf13/cobra" ) @@ -81,13 +80,14 @@ func runSearch(dockerCli command.Cli, options searchOptions) error { clnt := dockerCli.Client() - unorderedResults, err := clnt.ImageSearch(ctx, options.term, searchOptions) + results, err := clnt.ImageSearch(ctx, options.term, searchOptions) if err != nil { return err } - results := searchResultsByStars(unorderedResults) - sort.Sort(results) + sort.Slice(results, func(i, j int) bool { + return results[j].StarCount < results[i].StarCount + }) searchCtx := formatter.Context{ Output: dockerCli.Out(), Format: formatter.NewSearchFormat(options.format), @@ -95,10 +95,3 @@ func runSearch(dockerCli command.Cli, options searchOptions) error { } return formatter.SearchWrite(searchCtx, results, options.automated, int(options.stars)) } - -// searchResultsByStars sorts search results in descending order by number of stars. -type searchResultsByStars []registrytypes.SearchResult - -func (r searchResultsByStars) Len() int { return len(r) } -func (r searchResultsByStars) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r searchResultsByStars) Less(i, j int) bool { return r[j].StarCount < r[i].StarCount } diff --git a/cli/command/trust/common.go b/cli/command/trust/common.go index 9173e6eeeb..751259d5cb 100644 --- a/cli/command/trust/common.go +++ b/cli/command/trust/common.go @@ -28,24 +28,10 @@ type trustTagRow struct { Signers []string } -type trustTagRowList []trustTagRow - -func (tagComparator trustTagRowList) Len() int { - return len(tagComparator) -} - -func (tagComparator trustTagRowList) Less(i, j int) bool { - return tagComparator[i].SignedTag < tagComparator[j].SignedTag -} - -func (tagComparator trustTagRowList) Swap(i, j int) { - tagComparator[i], tagComparator[j] = tagComparator[j], tagComparator[i] -} - // trustRepo represents consumable information about a trusted repository type trustRepo struct { Name string - SignedTags trustTagRowList + SignedTags []trustTagRow Signers []trustSigner AdminstrativeKeys []trustSigner } @@ -64,20 +50,20 @@ type trustKey struct { // lookupTrustInfo returns processed signature and role information about a notary repository. // This information is to be pretty printed or serialized into a machine-readable format. -func lookupTrustInfo(cli command.Cli, remote string) (trustTagRowList, []client.RoleWithSignatures, []data.Role, error) { +func lookupTrustInfo(cli command.Cli, remote string) ([]trustTagRow, []client.RoleWithSignatures, []data.Role, error) { ctx := context.Background() imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, nil, image.AuthResolver(cli), remote) if err != nil { - return trustTagRowList{}, []client.RoleWithSignatures{}, []data.Role{}, err + return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err } tag := imgRefAndAuth.Tag() notaryRepo, err := cli.NotaryClient(imgRefAndAuth, trust.ActionsPullOnly) if err != nil { - return trustTagRowList{}, []client.RoleWithSignatures{}, []data.Role{}, trust.NotaryError(imgRefAndAuth.Reference().Name(), err) + return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, trust.NotaryError(imgRefAndAuth.Reference().Name(), err) } if err = clearChangeList(notaryRepo); err != nil { - return trustTagRowList{}, []client.RoleWithSignatures{}, []data.Role{}, err + return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err } defer clearChangeList(notaryRepo) @@ -87,7 +73,7 @@ func lookupTrustInfo(cli command.Cli, remote string) (trustTagRowList, []client. logrus.Debug(trust.NotaryError(remote, err)) // print an empty table if we don't have signed targets, but have an initialized notary repo if _, ok := err.(client.ErrNoSuchTarget); !ok { - return trustTagRowList{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signatures or cannot access %s", remote) + return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signatures or cannot access %s", remote) } } signatureRows := matchReleasedSignatures(allSignedTargets) @@ -95,7 +81,7 @@ func lookupTrustInfo(cli command.Cli, remote string) (trustTagRowList, []client. // get the administrative roles adminRolesWithSigs, err := notaryRepo.ListRoles() if err != nil { - return trustTagRowList{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signers for %s", remote) + return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signers for %s", remote) } // get delegation roles with the canonical key IDs @@ -138,8 +124,8 @@ func getDelegationRoleToKeyMap(rawDelegationRoles []data.Role) map[string][]stri // aggregate all signers for a "released" hash+tagname pair. To be "released," the tag must have been // signed into the "targets" or "targets/releases" role. Output is sorted by tag name -func matchReleasedSignatures(allTargets []client.TargetSignedStruct) trustTagRowList { - signatureRows := trustTagRowList{} +func matchReleasedSignatures(allTargets []client.TargetSignedStruct) []trustTagRow { + signatureRows := []trustTagRow{} // do a first pass to get filter on tags signed into "targets" or "targets/releases" releasedTargetRows := map[trustTagKey][]string{} for _, tgt := range allTargets { @@ -162,6 +148,8 @@ func matchReleasedSignatures(allTargets []client.TargetSignedStruct) trustTagRow for targetKey, signers := range releasedTargetRows { signatureRows = append(signatureRows, trustTagRow{targetKey, signers}) } - sort.Sort(signatureRows) + sort.Slice(signatureRows, func(i, j int) bool { + return signatureRows[i].SignedTag < signatureRows[j].SignedTag + }) return signatureRows } diff --git a/cli/command/trust/inspect_pretty.go b/cli/command/trust/inspect_pretty.go index af146d20d2..f9104ce2c0 100644 --- a/cli/command/trust/inspect_pretty.go +++ b/cli/command/trust/inspect_pretty.go @@ -51,7 +51,7 @@ func printSortedAdminKeys(out io.Writer, adminRoles []client.RoleWithSignatures) } // pretty print with ordered rows -func printSignatures(out io.Writer, signatureRows trustTagRowList) error { +func printSignatures(out io.Writer, signatureRows []trustTagRow) error { trustTagCtx := formatter.Context{ Output: out, Format: formatter.NewTrustTagFormat(), @@ -78,13 +78,15 @@ func printSignerInfo(out io.Writer, roleToKeyIDs map[string][]string) error { Format: formatter.NewSignerInfoFormat(), Trunc: true, } - formattedSignerInfo := formatter.SignerInfoList{} + formattedSignerInfo := []formatter.SignerInfo{} for name, keyIDs := range roleToKeyIDs { formattedSignerInfo = append(formattedSignerInfo, formatter.SignerInfo{ Name: name, Keys: keyIDs, }) } - sort.Sort(formattedSignerInfo) + sort.Slice(formattedSignerInfo, func(i, j int) bool { + return formattedSignerInfo[i].Name < formattedSignerInfo[j].Name + }) return formatter.SignerInfoWrite(signerInfoCtx, formattedSignerInfo) } diff --git a/cli/compose/convert/service.go b/cli/compose/convert/service.go index 08865968e3..06d9dea9ae 100644 --- a/cli/compose/convert/service.go +++ b/cli/compose/convert/service.go @@ -202,12 +202,6 @@ func sortStrings(strs []string) []string { return strs } -type byNetworkTarget []swarm.NetworkAttachmentConfig - -func (a byNetworkTarget) Len() int { return len(a) } -func (a byNetworkTarget) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byNetworkTarget) Less(i, j int) bool { return a[i].Target < a[j].Target } - func convertServiceNetworks( networks map[string]*composetypes.ServiceNetworkConfig, networkConfigs networkMap, @@ -246,7 +240,9 @@ func convertServiceNetworks( nets = append(nets, netAttachConfig) } - sort.Sort(byNetworkTarget(nets)) + sort.Slice(nets, func(i, j int) bool { + return nets[i].Target < nets[j].Target + }) return nets, nil } @@ -536,12 +532,6 @@ func convertResources(source composetypes.Resources) (*swarm.ResourceRequirement return resources, nil } -type byPublishedPort []swarm.PortConfig - -func (a byPublishedPort) Len() int { return len(a) } -func (a byPublishedPort) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byPublishedPort) Less(i, j int) bool { return a[i].PublishedPort < a[j].PublishedPort } - func convertEndpointSpec(endpointMode string, source []composetypes.ServicePortConfig) (*swarm.EndpointSpec, error) { portConfigs := []swarm.PortConfig{} for _, port := range source { @@ -554,7 +544,10 @@ func convertEndpointSpec(endpointMode string, source []composetypes.ServicePortC portConfigs = append(portConfigs, portConfig) } - sort.Sort(byPublishedPort(portConfigs)) + sort.Slice(portConfigs, func(i, j int) bool { + return portConfigs[i].PublishedPort < portConfigs[j].PublishedPort + }) + return &swarm.EndpointSpec{ Mode: swarm.ResolutionMode(strings.ToLower(endpointMode)), Ports: portConfigs, diff --git a/cli/compose/convert/service_test.go b/cli/compose/convert/service_test.go index 7e5fa4e18a..be8e24b634 100644 --- a/cli/compose/convert/service_test.go +++ b/cli/compose/convert/service_test.go @@ -247,11 +247,8 @@ func TestConvertServiceNetworks(t *testing.T) { }, } - sortedConfigs := byTargetSort(configs) - sort.Sort(&sortedConfigs) - assert.NilError(t, err) - assert.Check(t, is.DeepEqual(expected, []swarm.NetworkAttachmentConfig(sortedConfigs))) + assert.Check(t, is.DeepEqual(expected, configs)) } func TestConvertServiceNetworksCustomDefault(t *testing.T) { @@ -277,20 +274,6 @@ func TestConvertServiceNetworksCustomDefault(t *testing.T) { assert.Check(t, is.DeepEqual(expected, []swarm.NetworkAttachmentConfig(configs))) } -type byTargetSort []swarm.NetworkAttachmentConfig - -func (s byTargetSort) Len() int { - return len(s) -} - -func (s byTargetSort) Less(i, j int) bool { - return strings.Compare(s[i].Target, s[j].Target) < 0 -} - -func (s byTargetSort) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - func TestConvertDNSConfigEmpty(t *testing.T) { dnsConfig, err := convertDNSConfig(nil, nil) diff --git a/cli/compose/loader/loader_test.go b/cli/compose/loader/loader_test.go index 7b72ad768c..c2c84bbcc1 100644 --- a/cli/compose/loader/loader_test.go +++ b/cli/compose/loader/loader_test.go @@ -985,16 +985,12 @@ services: } func serviceSort(services []types.ServiceConfig) []types.ServiceConfig { - sort.Sort(servicesByName(services)) + sort.Slice(services, func(i, j int) bool { + return services[i].Name < services[j].Name + }) return services } -type servicesByName []types.ServiceConfig - -func (sbn servicesByName) Len() int { return len(sbn) } -func (sbn servicesByName) Swap(i, j int) { sbn[i], sbn[j] = sbn[j], sbn[i] } -func (sbn servicesByName) Less(i, j int) bool { return sbn[i].Name < sbn[j].Name } - func TestLoadAttachableNetwork(t *testing.T) { config, err := loadYAML(` version: "3.2"