cli/command/container: runPort: sort ports before printing

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-12-01 10:58:40 +01:00
parent c5613ac032
commit 1768240bcd
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
5 changed files with 27 additions and 8 deletions

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"net" "net"
"sort"
"strconv" "strconv"
"strings" "strings"
@ -11,6 +12,7 @@ import (
"github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion" "github.com/docker/cli/cli/command/completion"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/fvbommel/sortorder"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -58,6 +60,7 @@ func runPort(dockerCli command.Cli, opts *portOptions) error {
return err return err
} }
var out []string
if opts.port != "" { if opts.port != "" {
port, proto, _ := strings.Cut(opts.port, "/") port, proto, _ := strings.Cut(opts.port, "/")
if proto == "" { if proto == "" {
@ -71,16 +74,22 @@ func runPort(dockerCli command.Cli, opts *portOptions) error {
return errors.Errorf("Error: No public port '%s' published for %s", opts.port, opts.container) return errors.Errorf("Error: No public port '%s' published for %s", opts.port, opts.container)
} }
for _, frontend := range frontends { for _, frontend := range frontends {
_, _ = fmt.Fprintln(dockerCli.Out(), net.JoinHostPort(frontend.HostIP, frontend.HostPort)) out = append(out, net.JoinHostPort(frontend.HostIP, frontend.HostPort))
} }
return nil } else {
}
for from, frontends := range c.NetworkSettings.Ports { for from, frontends := range c.NetworkSettings.Ports {
for _, frontend := range frontends { for _, frontend := range frontends {
_, _ = fmt.Fprintf(dockerCli.Out(), "%s -> %s\n", from, net.JoinHostPort(frontend.HostIP, frontend.HostPort)) out = append(out, fmt.Sprintf("%s -> %s", from, net.JoinHostPort(frontend.HostIP, frontend.HostPort)))
} }
} }
}
if len(out) > 0 {
sort.Slice(out, func(i, j int) bool {
return sortorder.NaturalLess(out[i], out[j])
})
_, _ = fmt.Fprintln(dockerCli.Out(), strings.Join(out, "\n"))
}
return nil return nil
} }

View File

@ -37,6 +37,10 @@ func TestNewPortCommandOutput(t *testing.T) {
ips: []string{"::", "0.0.0.0"}, ips: []string{"::", "0.0.0.0"},
port: "443/udp", port: "443/udp",
}, },
{
name: "container-port-all-ports",
ips: []string{"::", "0.0.0.0"},
},
} }
for _, tc := range testCases { for _, tc := range testCases {
tc := tc tc := tc

View File

@ -0,0 +1,6 @@
80/tcp -> 0.0.0.0:3456
80/tcp -> [::]:3456
443/tcp -> 0.0.0.0:4567
443/tcp -> [::]:4567
443/udp -> 0.0.0.0:5678
443/udp -> [::]:5678

View File

@ -1,2 +1,2 @@
[::]:5678
0.0.0.0:5678 0.0.0.0:5678
[::]:5678

View File

@ -1,2 +1,2 @@
[::]:3456
0.0.0.0:3456 0.0.0.0:3456
[::]:3456