Add labels to containers on run

This commit is contained in:
Djordje Lukic 2020-05-18 10:33:01 +02:00
parent 0c6b6beec4
commit fcb4b606e2
10 changed files with 258 additions and 167 deletions

View file

@ -53,6 +53,7 @@ func Command() *cobra.Command {
cmd.Flags().StringArrayVarP(&opts.Publish, "publish", "p", []string{}, "Publish a container's port(s). [HOST_PORT:]CONTAINER_PORT")
cmd.Flags().StringVar(&opts.Name, "name", getRandomName(), "Assign a name to the container")
cmd.Flags().StringArrayVarP(&opts.Labels, "label", "l", []string{}, "Set meta data on a container")
return cmd
}

View file

@ -1,7 +1,9 @@
package run
import (
"fmt"
"strconv"
"strings"
"github.com/docker/go-connections/nat"
@ -12,6 +14,7 @@ import (
type Opts struct {
Name string
Publish []string
Labels []string
}
// ToContainerConfig convert run options to a container configuration
@ -21,10 +24,16 @@ func (r *Opts) ToContainerConfig(image string) (containers.ContainerConfig, erro
return containers.ContainerConfig{}, err
}
labels, err := toLabels(r.Labels)
if err != nil {
return containers.ContainerConfig{}, err
}
return containers.ContainerConfig{
ID: r.Name,
Image: image,
Ports: publish,
ID: r.Name,
Image: image,
Ports: publish,
Labels: labels,
}, nil
}
@ -59,3 +68,16 @@ func (r *Opts) toPorts() ([]containers.Port, error) {
return result, nil
}
func toLabels(labels []string) (map[string]string, error) {
result := map[string]string{}
for _, label := range labels {
parts := strings.Split(label, "=")
if len(parts) != 2 {
return nil, fmt.Errorf("wrong label format %q", label)
}
result[parts[0]] = parts[1]
}
return result, nil
}

View file

@ -1,6 +1,7 @@
package run
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
@ -97,6 +98,48 @@ func (s *RunOptsSuite) TestPortParse() {
}
}
func (s *RunOptsSuite) TestLabels() {
testCases := []struct {
in []string
expected map[string]string
expectedError error
}{
{
in: []string{"label=value"},
expected: map[string]string{
"label": "value",
},
expectedError: nil,
},
{
in: []string{"label=value", "label=value2"},
expected: map[string]string{
"label": "value2",
},
expectedError: nil,
},
{
in: []string{"label=value", "label2=value2"},
expected: map[string]string{
"label": "value",
"label2": "value2",
},
expectedError: nil,
},
{
in: []string{"label"},
expected: nil,
expectedError: errors.New(`wrong label format "label"`),
},
}
for _, testCase := range testCases {
result, err := toLabels(testCase.in)
assert.Equal(s.T(), testCase.expectedError, err)
assert.Equal(s.T(), testCase.expected, result)
}
}
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(RunOptsSuite))
}