Use friendly random name generator

Signed-off-by: Christopher Crone <christopher.crone@docker.com>
This commit is contained in:
Christopher Crone 2020-05-05 17:55:42 +02:00
parent fce52f66b8
commit 07569bffa9
4 changed files with 34 additions and 5 deletions

View file

@ -29,8 +29,9 @@ package run
import (
"context"
"strings"
"github.com/google/uuid"
"github.com/docker/docker/pkg/namesgenerator"
"github.com/spf13/cobra"
"github.com/docker/api/client"
@ -49,7 +50,7 @@ func Command() *cobra.Command {
}
cmd.Flags().StringArrayVarP(&opts.publish, "publish", "p", []string{}, "Publish a container's port(s)")
cmd.Flags().StringVar(&opts.name, "name", uuid.New().String(), "Assign a name to the container")
cmd.Flags().StringVar(&opts.name, "name", getRandomName(), "Assign a name to the container")
return cmd
}
@ -67,3 +68,8 @@ func runRun(ctx context.Context, image string, opts runOpts) error {
return c.ContainerService().Run(ctx, project)
}
func getRandomName() string {
// Azure supports hyphen but not underscore in names
return strings.Replace(namesgenerator.GetRandomName(0), "_", "-", -1)
}

23
cli/cmd/run/run_test.go Normal file
View file

@ -0,0 +1,23 @@
package run
import (
"regexp"
"testing"
"github.com/stretchr/testify/require"
)
var (
// AzureNameRegex is used to validate container names
// Regex was taken from server side error:
// The container name must contain no more than 63 characters and must match the regex '[a-z0-9]([-a-z0-9]*[a-z0-9])?' (e.g. 'my-name').
AzureNameRegex = regexp.MustCompile("[a-z0-9]([-a-z0-9]*[a-z0-9])")
)
// TestAzureRandomName ensures compliance with Azure naming requirements
func TestAzureRandomName(t *testing.T) {
n := getRandomName()
require.Less(t, len(n), 64)
require.Greater(t, len(n), 1)
require.Regexp(t, AzureNameRegex, n)
}