Merge pull request #52047 from thaJeztah/swarm_portspec_sorting

api/types/swarm: PortConfig: add Compare method
This commit is contained in:
Paweł Gronowski
2026-02-27 16:27:40 +00:00
committed by GitHub
3 changed files with 138 additions and 0 deletions

View File

@@ -1,6 +1,7 @@
package swarm
import (
"cmp"
"net/netip"
"github.com/moby/moby/api/types/network"
@@ -41,6 +42,27 @@ type PortConfig struct {
PublishMode PortConfigPublishMode `json:",omitempty"`
}
// Compare returns the lexical ordering of p and other, and can be used
// with [slices.SortFunc].
//
// The comparison is performed in the following priority order:
// 1. PublishedPort (host port)
// 2. TargetPort (container port)
// 3. Protocol
// 4. PublishMode
func (p PortConfig) Compare(other PortConfig) int {
if n := cmp.Compare(p.PublishedPort, other.PublishedPort); n != 0 {
return n
}
if n := cmp.Compare(p.TargetPort, other.TargetPort); n != 0 {
return n
}
if n := cmp.Compare(p.Protocol, other.Protocol); n != 0 {
return n
}
return cmp.Compare(p.PublishMode, other.PublishMode)
}
// PortConfigPublishMode represents the mode in which the port is to
// be published.
type PortConfigPublishMode string

View File

@@ -0,0 +1,94 @@
package swarm_test
import (
"slices"
"testing"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/swarm"
"gotest.tools/v3/assert"
)
func TestPortConfigCompareSort(t *testing.T) {
tests := []struct {
doc string
ports []swarm.PortConfig
expected []swarm.PortConfig
}{
{
doc: "sort ports lexicographically",
ports: []swarm.PortConfig{
{
PublishedPort: 443,
TargetPort: 443,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 80,
TargetPort: 8080,
Protocol: network.UDP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 80,
TargetPort: 9090,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 80,
TargetPort: 8080,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 80,
TargetPort: 8080,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeHost,
},
},
expected: []swarm.PortConfig{
{
PublishedPort: 80,
TargetPort: 8080,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeHost,
},
{
PublishedPort: 80,
TargetPort: 8080,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 80,
TargetPort: 8080,
Protocol: network.UDP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 80,
TargetPort: 9090,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
{
PublishedPort: 443,
TargetPort: 443,
Protocol: network.TCP,
PublishMode: swarm.PortConfigPublishModeIngress,
},
},
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
got := slices.Clone(tc.ports)
slices.SortFunc(got, swarm.PortConfig.Compare)
assert.DeepEqual(t, tc.expected, got)
})
}
}