/
validation.go
82 lines (71 loc) · 2.68 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package validation
import (
"fmt"
"strings"
"github.com/openshift/source-to-image/pkg/api"
)
// ValidateConfig returns a list of error from validation.
func ValidateConfig(config *api.Config) []ValidationError {
allErrs := []ValidationError{}
if len(config.BuilderImage) == 0 {
allErrs = append(allErrs, NewFieldRequired("builderImage"))
}
switch config.BuilderPullPolicy {
case api.PullNever, api.PullAlways, api.PullIfNotPresent:
default:
allErrs = append(allErrs, NewFieldInvalidValue("builderPullPolicy"))
}
if config.DockerConfig == nil || len(config.DockerConfig.Endpoint) == 0 {
allErrs = append(allErrs, NewFieldRequired("dockerConfig.endpoint"))
}
if config.DockerNetworkMode != "" && !validateDockerNetworkMode(config.DockerNetworkMode) {
allErrs = append(allErrs, NewFieldInvalidValue("dockerNetworkMode"))
}
return allErrs
}
// validateDockerNetworkMode checks wether the network mode conforms to the docker remote API specification (v1.19)
// Supported values are: bridge, host, and container:<name|id>
func validateDockerNetworkMode(mode api.DockerNetworkMode) bool {
switch mode {
case api.DockerNetworkModeBridge, api.DockerNetworkModeHost:
return true
}
if strings.HasPrefix(string(mode), api.DockerNetworkModeContainerPrefix) {
return true
}
return false
}
// NewFieldRequired returns a *ValidationError indicating "value required"
func NewFieldRequired(field string) ValidationError {
return ValidationError{ValidationErrorTypeRequired, field}
}
// NewFieldInvalidValue returns a ValidationError indicating "invalid value"
func NewFieldInvalidValue(field string) ValidationError {
return ValidationError{ValidationErrorInvalidValue, field}
}
// ValidationErrorType is a machine readable value providing more detail about why
// a field is invalid.
type ValidationErrorType string
const (
// ValidationErrorTypeRequired is used to report required values that are not
// provided (e.g. empty strings, null values, or empty arrays).
ValidationErrorTypeRequired ValidationErrorType = "FieldValueRequired"
// ValidationErrorInvalidValue is used to report values that do not conform to
// the expected schema.
ValidationErrorInvalidValue ValidationErrorType = "InvalidValue"
)
// ValidationError is an implementation of the 'error' interface, which represents an error of validation.
type ValidationError struct {
Type ValidationErrorType
Field string
}
func (v ValidationError) Error() string {
switch v.Type {
case ValidationErrorInvalidValue:
return fmt.Sprintf("Invalid value specified for %q", v.Field)
case ValidationErrorTypeRequired:
return fmt.Sprintf("Required value not specified for %q", v.Field)
default:
return fmt.Sprintf("%s: %s", v.Type, v.Field)
}
}