Skip to content

Commit 4f7f42d

Browse files
committed
cli/command/stack/swarm: GetStacks: tidy up
Preserve the original order by avoiding the intermediate map[string] and keeping an index for the first occurrence of a stack; this also avoids looping multiple times. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 5a23ff9 commit 4f7f42d

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

cli/command/stack/swarm/list.go

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,37 +9,31 @@ import (
99
"github.com/pkg/errors"
1010
)
1111

12-
// GetStacks lists the swarm stacks.
12+
// GetStacks lists the swarm stacks with the number of services they contain.
1313
//
1414
// Deprecated: this function was for internal use and will be removed in the next release.
1515
func GetStacks(ctx context.Context, apiClient client.ServiceAPIClient) ([]*formatter.Stack, error) {
16-
services, err := apiClient.ServiceList(
17-
ctx,
18-
client.ServiceListOptions{Filters: getAllStacksFilter()})
16+
services, err := apiClient.ServiceList(ctx, client.ServiceListOptions{
17+
Filters: getAllStacksFilter(),
18+
})
1919
if err != nil {
2020
return nil, err
2121
}
22-
m := make(map[string]*formatter.Stack)
23-
for _, service := range services {
24-
labels := service.Spec.Labels
25-
name, ok := labels[convert.LabelNamespace]
22+
23+
idx := make(map[string]int, len(services))
24+
out := make([]*formatter.Stack, 0, len(services))
25+
26+
for _, svc := range services {
27+
name, ok := svc.Spec.Labels[convert.LabelNamespace]
2628
if !ok {
27-
return nil, errors.Errorf("cannot get label %s for service %s",
28-
convert.LabelNamespace, service.ID)
29+
return nil, errors.New("cannot get label " + convert.LabelNamespace + " for service " + svc.ID)
2930
}
30-
ztack, ok := m[name]
31-
if !ok {
32-
m[name] = &formatter.Stack{
33-
Name: name,
34-
Services: 1,
35-
}
36-
} else {
37-
ztack.Services++
31+
if i, ok := idx[name]; ok {
32+
out[i].Services++
33+
continue
3834
}
35+
idx[name] = len(out)
36+
out = append(out, &formatter.Stack{Name: name, Services: 1})
3937
}
40-
stacks := make([]*formatter.Stack, 0, len(m))
41-
for _, stack := range m {
42-
stacks = append(stacks, stack)
43-
}
44-
return stacks, nil
38+
return out, nil
4539
}

0 commit comments

Comments
 (0)