Implement printing published ports

This commit is contained in:
Djordje Lukic 2020-05-15 17:52:19 +02:00
parent 23d2eacf84
commit d8a38afecc
14 changed files with 240 additions and 48 deletions

61
cli/options/run/opts.go Normal file
View file

@ -0,0 +1,61 @@
package run
import (
"strconv"
"github.com/docker/go-connections/nat"
"github.com/docker/api/containers"
)
// Opts contain run command options
type Opts struct {
Name string
Publish []string
}
// ToContainerConfig convert run options to a container configuration
func (r *Opts) ToContainerConfig(image string) (containers.ContainerConfig, error) {
publish, err := r.toPorts()
if err != nil {
return containers.ContainerConfig{}, err
}
return containers.ContainerConfig{
ID: r.Name,
Image: image,
Ports: publish,
}, nil
}
func (r *Opts) toPorts() ([]containers.Port, error) {
_, bindings, err := nat.ParsePortSpecs(r.Publish)
if err != nil {
return nil, err
}
var result []containers.Port
for port, bind := range bindings {
for _, portbind := range bind {
var hostPort uint32
if portbind.HostPort != "" {
hp, err := strconv.Atoi(portbind.HostPort)
if err != nil {
return nil, err
}
hostPort = uint32(hp)
} else {
hostPort = uint32(port.Int())
}
result = append(result, containers.Port{
HostPort: hostPort,
ContainerPort: uint32(port.Int()),
Protocol: port.Proto(),
HostIP: portbind.HostIP,
})
}
}
return result, nil
}

View file

@ -0,0 +1,102 @@
package run
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/docker/api/containers"
)
type RunOptsSuite struct {
suite.Suite
}
func (s *RunOptsSuite) TestPortParse() {
testCases := []struct {
in string
expected []containers.Port
}{
{
in: "80",
expected: []containers.Port{
{
HostPort: 80,
ContainerPort: 80,
Protocol: "tcp",
},
},
},
{
in: "80:80",
expected: []containers.Port{
{
HostPort: 80,
ContainerPort: 80,
Protocol: "tcp",
},
},
},
{
in: "80:80/udp",
expected: []containers.Port{
{
ContainerPort: 80,
HostPort: 80,
Protocol: "udp",
},
},
},
{
in: "8080:80",
expected: []containers.Port{
{
HostPort: 8080,
ContainerPort: 80,
Protocol: "tcp",
},
},
},
{
in: "192.168.0.2:8080:80",
expected: []containers.Port{
{
HostPort: 8080,
ContainerPort: 80,
Protocol: "tcp",
HostIP: "192.168.0.2",
},
},
},
{
in: "80-81:80-81",
expected: []containers.Port{
{
HostPort: 80,
ContainerPort: 80,
Protocol: "tcp",
},
{
HostPort: 81,
ContainerPort: 81,
Protocol: "tcp",
},
},
},
}
for _, testCase := range testCases {
opts := Opts{
Publish: []string{testCase.in},
}
result, err := opts.toPorts()
require.Nil(s.T(), err)
assert.ElementsMatch(s.T(), testCase.expected, result)
}
}
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(RunOptsSuite))
}