validate build-arg

Signed-off-by: sakeven <jc5930@sina.cn>
This commit is contained in:
sakeven 2016-08-29 21:10:32 +08:00
parent 2cce7bf33a
commit 5426510bea
3 changed files with 52 additions and 1 deletions

View File

@ -62,7 +62,7 @@ func NewBuildCommand(dockerCli *command.DockerCli) *cobra.Command {
ulimits := make(map[string]*units.Ulimit)
options := buildOptions{
tags: opts.NewListOpts(validateTag),
buildArgs: opts.NewListOpts(runconfigopts.ValidateEnv),
buildArgs: opts.NewListOpts(runconfigopts.ValidateArg),
ulimits: runconfigopts.NewUlimitOpt(&ulimits),
}

View File

@ -46,6 +46,21 @@ func doesEnvExist(name string) bool {
return false
}
// ValidateArg validates a build-arg variable and returns it.
// Build-arg is in the form of <varname>=<value> where <varname> is required.
func ValidateArg(val string) (string, error) {
arr := strings.Split(val, "=")
if len(arr) > 1 && isNotEmpty(arr[0]) {
return val, nil
}
return "", fmt.Errorf("bad format for build-arg: %s", val)
}
func isNotEmpty(val string) bool {
return len(val) > 0
}
// ValidateExtraHost validates that the specified string is a valid extrahost and returns it.
// ExtraHost is in the form of name:ip where the ip has to be a valid ip (IPv4 or IPv6).
func ValidateExtraHost(val string) (string, error) {

View File

@ -61,6 +61,42 @@ func TestValidateEnv(t *testing.T) {
}
}
func TestValidateArg(t *testing.T) {
valids := map[string]string{
"_=a": "_=a",
"var1=value1": "var1=value1",
"_var1=value1": "_var1=value1",
"var2=value2=value3": "var2=value2=value3",
"var3=abc!qwe": "var3=abc!qwe",
"var_4=value 4": "var_4=value 4",
"var_5=": "var_5=",
}
for value, expected := range valids {
actual, err := ValidateArg(value)
if err != nil {
t.Fatal(err)
}
if actual != expected {
t.Fatalf("Expected [%v], got [%v]", expected, actual)
}
}
invalid := map[string]string{
"foo": "bad format",
"=foo": "bad format",
"cc c": "bad format",
}
for value, expectedError := range invalid {
if _, err := ValidateArg(value); err == nil {
t.Fatalf("ValidateArg(`%s`) should have failed validation", value)
} else {
if !strings.Contains(err.Error(), expectedError) {
t.Fatalf("ValidateArg(`%s`) error should contain %q", value, expectedError)
}
}
}
}
func TestValidateExtraHosts(t *testing.T) {
valid := []string{
`myhost:192.168.0.1`,