Shorten names for better reading

This commit is contained in:
Tim Hockin 2015-11-10 12:59:41 -08:00
parent 87a35047dd
commit 7fb8f60735
13 changed files with 284 additions and 284 deletions

View File

@ -123,7 +123,7 @@ func validateObject(obj runtime.Object) (errors field.ErrorList) {
} }
errors = expvalidation.ValidateDaemonSet(t) errors = expvalidation.ValidateDaemonSet(t)
default: default:
return field.ErrorList{field.NewInternalError(field.NewPath(""), fmt.Errorf("no validation defined for %#v", obj))} return field.ErrorList{field.InternalError(field.NewPath(""), fmt.Errorf("no validation defined for %#v", obj))}
} }
return errors return errors
} }

View File

@ -92,7 +92,7 @@ func TestNewInvalid(t *testing.T) {
Details *unversioned.StatusDetails Details *unversioned.StatusDetails
}{ }{
{ {
field.NewDuplicateError(field.NewPath("field[0].name"), "bar"), field.Duplicate(field.NewPath("field[0].name"), "bar"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -103,7 +103,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewInvalidError(field.NewPath("field[0].name"), "bar", "detail"), field.Invalid(field.NewPath("field[0].name"), "bar", "detail"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -114,7 +114,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewNotFoundError(field.NewPath("field[0].name"), "bar"), field.NotFound(field.NewPath("field[0].name"), "bar"),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -125,7 +125,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewNotSupportedError(field.NewPath("field[0].name"), "bar", nil), field.NotSupported(field.NewPath("field[0].name"), "bar", nil),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",
@ -136,7 +136,7 @@ func TestNewInvalid(t *testing.T) {
}, },
}, },
{ {
field.NewRequiredError(field.NewPath("field[0].name")), field.Required(field.NewPath("field[0].name")),
&unversioned.StatusDetails{ &unversioned.StatusDetails{
Kind: "kind", Kind: "kind",
Name: "name", Name: "name",

View File

@ -57,11 +57,11 @@ func validateCommonFields(obj, old runtime.Object) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
objectMeta, err := api.ObjectMetaFor(obj) objectMeta, err := api.ObjectMetaFor(obj)
if err != nil { if err != nil {
return append(allErrs, field.NewInternalError(field.NewPath("metadata"), err)) return append(allErrs, field.InternalError(field.NewPath("metadata"), err))
} }
oldObjectMeta, err := api.ObjectMetaFor(old) oldObjectMeta, err := api.ObjectMetaFor(old)
if err != nil { if err != nil {
return append(allErrs, field.NewInternalError(field.NewPath("metadata"), err)) return append(allErrs, field.InternalError(field.NewPath("metadata"), err))
} }
allErrs = append(allErrs, validation.ValidateObjectMetaUpdate(objectMeta, oldObjectMeta, field.NewPath("metadata"))...) allErrs = append(allErrs, validation.ValidateObjectMetaUpdate(objectMeta, oldObjectMeta, field.NewPath("metadata"))...)

View File

@ -28,14 +28,14 @@ func ValidateEvent(event *api.Event) field.ErrorList {
// There is no namespace required for node. // There is no namespace required for node.
if event.InvolvedObject.Kind == "Node" && if event.InvolvedObject.Kind == "Node" &&
event.Namespace != "" { event.Namespace != "" {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "not required for node")) allErrs = append(allErrs, field.Invalid(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "not required for node"))
} }
if event.InvolvedObject.Kind != "Node" && if event.InvolvedObject.Kind != "Node" &&
event.Namespace != event.InvolvedObject.Namespace { event.Namespace != event.InvolvedObject.Namespace {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "does not match involvedObject")) allErrs = append(allErrs, field.Invalid(field.NewPath("involvedObject", "namespace"), event.InvolvedObject.Namespace, "does not match involvedObject"))
} }
if !validation.IsDNS1123Subdomain(event.Namespace) { if !validation.IsDNS1123Subdomain(event.Namespace) {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("namespace"), event.Namespace, "")) allErrs = append(allErrs, field.Invalid(field.NewPath("namespace"), event.Namespace, ""))
} }
return allErrs return allErrs
} }

File diff suppressed because it is too large Load Diff

View File

@ -42,21 +42,21 @@ func ValidateHorizontalPodAutoscalerName(name string, prefix bool) (bool, string
func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec, fldPath *field.Path) field.ErrorList { func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAutoscalerSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 { if autoscaler.MinReplicas != nil && *autoscaler.MinReplicas < 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("minReplicas"), autoscaler.MinReplicas, `must be greater than or equal to 1`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("minReplicas"), autoscaler.MinReplicas, `must be greater than or equal to 1`))
} }
if autoscaler.MaxReplicas < 1 { if autoscaler.MaxReplicas < 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to 1`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to 1`))
} }
if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas { if autoscaler.MinReplicas != nil && autoscaler.MaxReplicas < *autoscaler.MinReplicas {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to minReplicas`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxReplicas"), autoscaler.MaxReplicas, `must be greater than or equal to minReplicas`))
} }
if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 { if autoscaler.CPUUtilization != nil && autoscaler.CPUUtilization.TargetPercentage < 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("cpuUtilization", "targetPercentage"), autoscaler.CPUUtilization.TargetPercentage, `must be greater than or equal to 1`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("cpuUtilization", "targetPercentage"), autoscaler.CPUUtilization.TargetPercentage, `must be greater than or equal to 1`))
} }
if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef, fldPath.Child("scaleRef")); len(refErrs) > 0 { if refErrs := ValidateSubresourceReference(autoscaler.ScaleRef, fldPath.Child("scaleRef")); len(refErrs) > 0 {
allErrs = append(allErrs, refErrs...) allErrs = append(allErrs, refErrs...)
} else if autoscaler.ScaleRef.Subresource != "scale" { } else if autoscaler.ScaleRef.Subresource != "scale" {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("scaleRef", "subresource"), autoscaler.ScaleRef.Subresource, []string{"scale"})) allErrs = append(allErrs, field.NotSupported(fldPath.Child("scaleRef", "subresource"), autoscaler.ScaleRef.Subresource, []string{"scale"}))
} }
return allErrs return allErrs
} }
@ -64,21 +64,21 @@ func validateHorizontalPodAutoscalerSpec(autoscaler extensions.HorizontalPodAuto
func ValidateSubresourceReference(ref extensions.SubresourceReference, fldPath *field.Path) field.ErrorList { func ValidateSubresourceReference(ref extensions.SubresourceReference, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(ref.Kind) == 0 { if len(ref.Kind) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("kind"))) allErrs = append(allErrs, field.Required(fldPath.Child("kind")))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Kind); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("kind"), ref.Kind, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("kind"), ref.Kind, msg))
} }
if len(ref.Name) == 0 { if len(ref.Name) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("name"))) allErrs = append(allErrs, field.Required(fldPath.Child("name")))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Name); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("name"), ref.Name, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), ref.Name, msg))
} }
if len(ref.Subresource) == 0 { if len(ref.Subresource) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("subresource"))) allErrs = append(allErrs, field.Required(fldPath.Child("subresource")))
} else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok { } else if ok, msg := apivalidation.IsValidPathSegmentName(ref.Subresource); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("subresource"), ref.Subresource, msg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("subresource"), ref.Subresource, msg))
} }
return allErrs return allErrs
} }
@ -122,10 +122,10 @@ func ValidateThirdPartyResource(obj *extensions.ThirdPartyResource) field.ErrorL
for ix := range obj.Versions { for ix := range obj.Versions {
version := &obj.Versions[ix] version := &obj.Versions[ix]
if len(version.Name) == 0 { if len(version.Name) == 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("versions").Index(ix).Child("name"), version, "can not be empty")) allErrs = append(allErrs, field.Invalid(field.NewPath("versions").Index(ix).Child("name"), version, "can not be empty"))
} }
if versions.Has(version.Name) { if versions.Has(version.Name) {
allErrs = append(allErrs, field.NewDuplicateError(field.NewPath("versions").Index(ix).Child("name"), version)) allErrs = append(allErrs, field.Duplicate(field.NewPath("versions").Index(ix).Child("name"), version))
} }
versions.Insert(version.Name) versions.Insert(version.Name)
} }
@ -173,7 +173,7 @@ func ValidateDaemonSetTemplateUpdate(podTemplate, oldPodTemplate *api.PodTemplat
// In particular, we do not allow updates to container images at this point. // In particular, we do not allow updates to container images at this point.
if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) { if !api.Semantic.DeepEqual(oldPodTemplate.Spec, podSpec) {
// TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff // TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("spec"), "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector")) allErrs = append(allErrs, field.Invalid(fldPath.Child("spec"), "content of spec is not printed out, please refer to the \"details\"", "may not update fields other than spec.nodeSelector"))
} }
return allErrs return allErrs
} }
@ -185,13 +185,13 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path)
allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...)
if spec.Template == nil { if spec.Template == nil {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("template"))) allErrs = append(allErrs, field.Required(fldPath.Child("template")))
return allErrs return allErrs
} }
selector, err := extensions.LabelSelectorAsSelector(spec.Selector) selector, err := extensions.LabelSelectorAsSelector(spec.Selector)
if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) { if err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template")) allErrs = append(allErrs, field.Invalid(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template"))
} }
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template, fldPath.Child("template"))...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(spec.Template, fldPath.Child("template"))...)
@ -199,7 +199,7 @@ func ValidateDaemonSetSpec(spec *extensions.DaemonSetSpec, fldPath *field.Path)
allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, fldPath.Child("template", "spec", "volumes"))...) allErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, fldPath.Child("template", "spec", "volumes"))...)
// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec(). // RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().
if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways { if spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("template", "spec", "restartPolicy"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)})) allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))
} }
return allErrs return allErrs
@ -221,7 +221,7 @@ func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fldPath *fiel
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if intOrPercent.Type == intstr.String { if intOrPercent.Type == intstr.String {
if !validation.IsValidPercent(intOrPercent.StrVal) { if !validation.IsValidPercent(intOrPercent.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath, intOrPercent, "value should be int(5) or percentage(5%)")) allErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, "value should be int(5) or percentage(5%)"))
} }
} else if intOrPercent.Type == intstr.Int { } else if intOrPercent.Type == intstr.Int {
allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntValue()), fldPath)...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(intOrPercent.IntValue()), fldPath)...)
@ -251,7 +251,7 @@ func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fldPath *field
if !isPercent || value <= 100 { if !isPercent || value <= 100 {
return nil return nil
} }
allErrs = append(allErrs, field.NewInvalidError(fldPath, intOrStringValue, "should not be more than 100%")) allErrs = append(allErrs, field.Invalid(fldPath, intOrStringValue, "should not be more than 100%"))
return allErrs return allErrs
} }
@ -261,7 +261,7 @@ func ValidateRollingUpdateDeployment(rollingUpdate *extensions.RollingUpdateDepl
allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child("maxSurge"))...) allErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child("maxSurge"))...)
if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 { if getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 && getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 {
// Both MaxSurge and MaxUnavailable cannot be zero. // Both MaxSurge and MaxUnavailable cannot be zero.
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxUnavailable"), rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well")) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxUnavailable"), rollingUpdate.MaxUnavailable, "cannot be 0 when maxSurge is 0 as well"))
} }
// Validate that MaxUnavailable is not more than 100%. // Validate that MaxUnavailable is not more than 100%.
allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child("maxUnavailable"))...) allErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child("maxUnavailable"))...)
@ -276,7 +276,7 @@ func ValidateDeploymentStrategy(strategy *extensions.DeploymentStrategy, fldPath
} }
switch strategy.Type { switch strategy.Type {
case extensions.RecreateDeploymentStrategyType: case extensions.RecreateDeploymentStrategyType:
allErrs = append(allErrs, field.NewForbiddenError(fldPath.Child("rollingUpdate"), "should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType)) allErrs = append(allErrs, field.Forbidden(fldPath.Child("rollingUpdate"), "should be nil when strategy type is "+extensions.RecreateDeploymentStrategyType))
case extensions.RollingUpdateDeploymentStrategyType: case extensions.RollingUpdateDeploymentStrategyType:
allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, fldPath.Child("rollingUpdate"))...) allErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, fldPath.Child("rollingUpdate"))...)
} }
@ -316,7 +316,7 @@ func ValidateThirdPartyResourceDataUpdate(update, old *extensions.ThirdPartyReso
func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) field.ErrorList { func ValidateThirdPartyResourceData(obj *extensions.ThirdPartyResourceData) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(obj.Name) == 0 { if len(obj.Name) == 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("name"), obj.Name, "must be non-empty")) allErrs = append(allErrs, field.Invalid(field.NewPath("name"), obj.Name, "must be non-empty"))
} }
return allErrs return allErrs
} }
@ -338,7 +338,7 @@ func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorL
allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), fldPath.Child("completions"))...) allErrs = append(allErrs, apivalidation.ValidatePositiveField(int64(*spec.Completions), fldPath.Child("completions"))...)
} }
if spec.Selector == nil { if spec.Selector == nil {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("selector"))) allErrs = append(allErrs, field.Required(fldPath.Child("selector")))
} else { } else {
allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...) allErrs = append(allErrs, ValidateLabelSelector(spec.Selector, fldPath.Child("selector"))...)
} }
@ -346,14 +346,14 @@ func ValidateJobSpec(spec *extensions.JobSpec, fldPath *field.Path) field.ErrorL
if selector, err := extensions.LabelSelectorAsSelector(spec.Selector); err == nil { if selector, err := extensions.LabelSelectorAsSelector(spec.Selector); err == nil {
labels := labels.Set(spec.Template.Labels) labels := labels.Set(spec.Template.Labels)
if !selector.Matches(labels) { if !selector.Matches(labels) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template")) allErrs = append(allErrs, field.Invalid(fldPath.Child("template", "metadata", "labels"), spec.Template.Labels, "selector does not match template"))
} }
} }
allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child("template"))...) allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child("template"))...)
if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure && if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure &&
spec.Template.Spec.RestartPolicy != api.RestartPolicyNever { spec.Template.Spec.RestartPolicy != api.RestartPolicyNever {
allErrs = append(allErrs, field.NewNotSupportedError(fldPath.Child("template", "spec", "restartPolicy"), allErrs = append(allErrs, field.NotSupported(fldPath.Child("template", "spec", "restartPolicy"),
spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)})) spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)}))
} }
return allErrs return allErrs
@ -413,7 +413,7 @@ func ValidateIngressSpec(spec *extensions.IngressSpec, fldPath *field.Path) fiel
if spec.Backend != nil { if spec.Backend != nil {
allErrs = append(allErrs, validateIngressBackend(spec.Backend, fldPath.Child("backend"))...) allErrs = append(allErrs, validateIngressBackend(spec.Backend, fldPath.Child("backend"))...)
} else if len(spec.Rules) == 0 { } else if len(spec.Rules) == 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("rules"), spec.Rules, "Either a default backend or a set of host rules are required for ingress.")) allErrs = append(allErrs, field.Invalid(fldPath.Child("rules"), spec.Rules, "Either a default backend or a set of host rules are required for ingress."))
} }
if len(spec.Rules) > 0 { if len(spec.Rules) > 0 {
allErrs = append(allErrs, validateIngressRules(spec.Rules, fldPath.Child("rules"))...) allErrs = append(allErrs, validateIngressRules(spec.Rules, fldPath.Child("rules"))...)
@ -438,17 +438,17 @@ func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) field.
func validateIngressRules(IngressRules []extensions.IngressRule, fldPath *field.Path) field.ErrorList { func validateIngressRules(IngressRules []extensions.IngressRule, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(IngressRules) == 0 { if len(IngressRules) == 0 {
return append(allErrs, field.NewRequiredError(fldPath)) return append(allErrs, field.Required(fldPath))
} }
for i, ih := range IngressRules { for i, ih := range IngressRules {
if len(ih.Host) > 0 { if len(ih.Host) > 0 {
// TODO: Ports and ips are allowed in the host part of a url // TODO: Ports and ips are allowed in the host part of a url
// according to RFC 3986, consider allowing them. // according to RFC 3986, consider allowing them.
if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid { if valid, errMsg := apivalidation.NameIsDNSSubdomain(ih.Host, false); !valid {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Index(i).Child("host"), ih.Host, errMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, errMsg))
} }
if isIP := (net.ParseIP(ih.Host) != nil); isIP { if isIP := (net.ParseIP(ih.Host) != nil); isIP {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Index(i).Child("host"), ih.Host, "Host must be a DNS name, not ip address")) allErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child("host"), ih.Host, "Host must be a DNS name, not ip address"))
} }
} }
allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue, fldPath.Index(0))...) allErrs = append(allErrs, validateIngressRuleValue(&ih.IngressRuleValue, fldPath.Index(0))...)
@ -467,12 +467,12 @@ func validateIngressRuleValue(ingressRule *extensions.IngressRuleValue, fldPath
func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue, fldPath *field.Path) field.ErrorList { func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRuleValue, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if len(httpIngressRuleValue.Paths) == 0 { if len(httpIngressRuleValue.Paths) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("paths"))) allErrs = append(allErrs, field.Required(fldPath.Child("paths")))
} }
for i, rule := range httpIngressRuleValue.Paths { for i, rule := range httpIngressRuleValue.Paths {
if len(rule.Path) > 0 { if len(rule.Path) > 0 {
if !strings.HasPrefix(rule.Path, "/") { if !strings.HasPrefix(rule.Path, "/") {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must begin with /")) allErrs = append(allErrs, field.Invalid(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must begin with /"))
} }
// TODO: More draconian path regex validation. // TODO: More draconian path regex validation.
// Path must be a valid regex. This is the basic requirement. // Path must be a valid regex. This is the basic requirement.
@ -485,7 +485,7 @@ func validateHTTPIngressRuleValue(httpIngressRuleValue *extensions.HTTPIngressRu
// the user is confusing url regexes with path regexes. // the user is confusing url regexes with path regexes.
_, err := regexp.CompilePOSIX(rule.Path) _, err := regexp.CompilePOSIX(rule.Path)
if err != nil { if err != nil {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must be a valid regex.")) allErrs = append(allErrs, field.Invalid(fldPath.Child("paths").Index(i).Child("path"), rule.Path, "must be a valid regex."))
} }
} }
allErrs = append(allErrs, validateIngressBackend(&rule.Backend, fldPath.Child("backend"))...) allErrs = append(allErrs, validateIngressBackend(&rule.Backend, fldPath.Child("backend"))...)
@ -499,19 +499,19 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P
// All backends must reference a single local service by name, and a single service port by name or number. // All backends must reference a single local service by name, and a single service port by name or number.
if len(backend.ServiceName) == 0 { if len(backend.ServiceName) == 0 {
return append(allErrs, field.NewRequiredError(fldPath.Child("serviceName"))) return append(allErrs, field.Required(fldPath.Child("serviceName")))
} else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok { } else if ok, errMsg := apivalidation.ValidateServiceName(backend.ServiceName, false); !ok {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("serviceName"), backend.ServiceName, errMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("serviceName"), backend.ServiceName, errMsg))
} }
if backend.ServicePort.Type == intstr.String { if backend.ServicePort.Type == intstr.String {
if !validation.IsDNS1123Label(backend.ServicePort.StrVal) { if !validation.IsDNS1123Label(backend.ServicePort.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.DNS1123LabelErrorMsg))
} }
if !validation.IsValidPortName(backend.ServicePort.StrVal) { if !validation.IsValidPortName(backend.ServicePort.StrVal) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort.StrVal, apivalidation.PortNameErrorMsg))
} }
} else if !validation.IsValidPortNum(backend.ServicePort.IntValue()) { } else if !validation.IsValidPortNum(backend.ServicePort.IntValue()) {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("servicePort"), backend.ServicePort, apivalidation.PortRangeErrorMsg)) allErrs = append(allErrs, field.Invalid(fldPath.Child("servicePort"), backend.ServicePort, apivalidation.PortRangeErrorMsg))
} }
return allErrs return allErrs
} }
@ -519,23 +519,23 @@ func validateIngressBackend(backend *extensions.IngressBackend, fldPath *field.P
func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPath *field.Path) field.ErrorList { func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if spec.MinNodes < 0 { if spec.MinNodes < 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("minNodes"), spec.MinNodes, `must be non-negative`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("minNodes"), spec.MinNodes, `must be non-negative`))
} }
if spec.MaxNodes < spec.MinNodes { if spec.MaxNodes < spec.MinNodes {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("maxNodes"), spec.MaxNodes, `must be greater than or equal to minNodes`)) allErrs = append(allErrs, field.Invalid(fldPath.Child("maxNodes"), spec.MaxNodes, `must be greater than or equal to minNodes`))
} }
if len(spec.TargetUtilization) == 0 { if len(spec.TargetUtilization) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("targetUtilization"))) allErrs = append(allErrs, field.Required(fldPath.Child("targetUtilization")))
} }
for _, target := range spec.TargetUtilization { for _, target := range spec.TargetUtilization {
if len(target.Resource) == 0 { if len(target.Resource) == 0 {
allErrs = append(allErrs, field.NewRequiredError(fldPath.Child("targetUtilization", "resource"))) allErrs = append(allErrs, field.Required(fldPath.Child("targetUtilization", "resource")))
} }
if target.Value <= 0 { if target.Value <= 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("targetUtilization", "value"), target.Value, "must be greater than 0")) allErrs = append(allErrs, field.Invalid(fldPath.Child("targetUtilization", "value"), target.Value, "must be greater than 0"))
} }
if target.Value > 1 { if target.Value > 1 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("targetUtilization", "value"), target.Value, "must be less or equal 1")) allErrs = append(allErrs, field.Invalid(fldPath.Child("targetUtilization", "value"), target.Value, "must be less or equal 1"))
} }
} }
return allErrs return allErrs
@ -544,10 +544,10 @@ func validateClusterAutoscalerSpec(spec extensions.ClusterAutoscalerSpec, fldPat
func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) field.ErrorList { func ValidateClusterAutoscaler(autoscaler *extensions.ClusterAutoscaler) field.ErrorList {
allErrs := field.ErrorList{} allErrs := field.ErrorList{}
if autoscaler.Name != "ClusterAutoscaler" { if autoscaler.Name != "ClusterAutoscaler" {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("metadata", "name"), autoscaler.Name, `name must be ClusterAutoscaler`)) allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "name"), autoscaler.Name, `name must be ClusterAutoscaler`))
} }
if autoscaler.Namespace != api.NamespaceDefault { if autoscaler.Namespace != api.NamespaceDefault {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("metadata", "namespace"), autoscaler.Namespace, `namespace must be default`)) allErrs = append(allErrs, field.Invalid(field.NewPath("metadata", "namespace"), autoscaler.Namespace, `namespace must be default`))
} }
allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec, field.NewPath("spec"))...) allErrs = append(allErrs, validateClusterAutoscalerSpec(autoscaler.Spec, field.NewPath("spec"))...)
return allErrs return allErrs
@ -570,14 +570,14 @@ func ValidateLabelSelectorRequirement(sr extensions.LabelSelectorRequirement, fl
switch sr.Operator { switch sr.Operator {
case extensions.LabelSelectorOpIn, extensions.LabelSelectorOpNotIn: case extensions.LabelSelectorOpIn, extensions.LabelSelectorOpNotIn:
if len(sr.Values) == 0 { if len(sr.Values) == 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("values"), sr.Values, "must be non-empty when operator is In or NotIn")) allErrs = append(allErrs, field.Invalid(fldPath.Child("values"), sr.Values, "must be non-empty when operator is In or NotIn"))
} }
case extensions.LabelSelectorOpExists, extensions.LabelSelectorOpDoesNotExist: case extensions.LabelSelectorOpExists, extensions.LabelSelectorOpDoesNotExist:
if len(sr.Values) > 0 { if len(sr.Values) > 0 {
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("values"), sr.Values, "must be empty when operator is Exists or DoesNotExist")) allErrs = append(allErrs, field.Invalid(fldPath.Child("values"), sr.Values, "must be empty when operator is Exists or DoesNotExist"))
} }
default: default:
allErrs = append(allErrs, field.NewInvalidError(fldPath.Child("operator"), sr.Operator, "not a valid pod selector operator")) allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid pod selector operator"))
} }
allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, fldPath.Child("key"))...) allErrs = append(allErrs, apivalidation.ValidateLabelName(sr.Key, fldPath.Child("key"))...)
return allErrs return allErrs
@ -588,7 +588,7 @@ func ValidateScale(scale *extensions.Scale) field.ErrorList {
allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain, field.NewPath("metadata"))...) allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&scale.ObjectMeta, true, apivalidation.NameIsDNSSubdomain, field.NewPath("metadata"))...)
if scale.Spec.Replicas < 0 { if scale.Spec.Replicas < 0 {
allErrs = append(allErrs, field.NewInvalidError(field.NewPath("spec", "replicas"), scale.Spec.Replicas, "must be non-negative")) allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "replicas"), scale.Spec.Replicas, "must be non-negative"))
} }
return allErrs return allErrs

View File

@ -274,11 +274,11 @@ func TestCheckInvalidErr(t *testing.T) {
expected string expected string
}{ }{
{ {
errors.NewInvalid("Invalid1", "invalidation", field.ErrorList{field.NewInvalidError(field.NewPath("field"), "single", "details")}), errors.NewInvalid("Invalid1", "invalidation", field.ErrorList{field.Invalid(field.NewPath("field"), "single", "details")}),
`Error from server: Invalid1 "invalidation" is invalid: field: invalid value 'single', Details: details`, `Error from server: Invalid1 "invalidation" is invalid: field: invalid value 'single', Details: details`,
}, },
{ {
errors.NewInvalid("Invalid2", "invalidation", field.ErrorList{field.NewInvalidError(field.NewPath("field1"), "multi1", "details"), field.NewInvalidError(field.NewPath("field2"), "multi2", "details")}), errors.NewInvalid("Invalid2", "invalidation", field.ErrorList{field.Invalid(field.NewPath("field1"), "multi1", "details"), field.Invalid(field.NewPath("field2"), "multi2", "details")}),
`Error from server: Invalid2 "invalidation" is invalid: [field1: invalid value 'multi1', Details: details, field2: invalid value 'multi2', Details: details]`, `Error from server: Invalid2 "invalidation" is invalid: [field1: invalid value 'multi1', Details: details, field2: invalid value 'multi2', Details: details]`,
}, },
{ {

View File

@ -319,7 +319,7 @@ func filterInvalidPods(pods []*api.Pod, source string, recorder record.EventReco
if names.Has(name) { if names.Has(name) {
// TODO: when validation becomes versioned, this gets a bit // TODO: when validation becomes versioned, this gets a bit
// more complicated. // more complicated.
errlist = append(errlist, field.NewDuplicateError(field.NewPath("metadata", "name"), pod.Name)) errlist = append(errlist, field.Duplicate(field.NewPath("metadata", "name"), pod.Name))
} else { } else {
names.Insert(name) names.Insert(name)
} }

View File

@ -135,11 +135,11 @@ func (r *BindingREST) Create(ctx api.Context, obj runtime.Object) (out runtime.O
// TODO: move me to a binding strategy // TODO: move me to a binding strategy
if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" { if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" {
// TODO: When validation becomes versioned, this gets more complicated. // TODO: When validation becomes versioned, this gets more complicated.
return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.NewNotSupportedError(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", ""})}) return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.NotSupported(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", ""})})
} }
if len(binding.Target.Name) == 0 { if len(binding.Target.Name) == 0 {
// TODO: When validation becomes versioned, this gets more complicated. // TODO: When validation becomes versioned, this gets more complicated.
return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.NewRequiredError(field.NewPath("target", "name"))}) return nil, errors.NewInvalid("binding", binding.Name, field.ErrorList{field.Required(field.NewPath("target", "name"))})
} }
err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations) err = r.assignPod(ctx, binding.Name, binding.Target.Name, binding.Annotations)
out = &unversioned.Status{Status: unversioned.StatusSuccess} out = &unversioned.Status{Status: unversioned.StatusSuccess}

View File

@ -95,7 +95,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
// Try to respect the requested IP. // Try to respect the requested IP.
if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil { if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil {
// TODO: when validation becomes versioned, this gets more complicated. // TODO: when validation becomes versioned, this gets more complicated.
el := field.ErrorList{field.NewInvalidError(field.NewPath("spec", "clusterIP"), service.Spec.ClusterIP, err.Error())} el := field.ErrorList{field.Invalid(field.NewPath("spec", "clusterIP"), service.Spec.ClusterIP, err.Error())}
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
releaseServiceIP = true releaseServiceIP = true
@ -108,7 +108,7 @@ func (rs *REST) Create(ctx api.Context, obj runtime.Object) (runtime.Object, err
err := nodePortOp.Allocate(servicePort.NodePort) err := nodePortOp.Allocate(servicePort.NodePort)
if err != nil { if err != nil {
// TODO: when validation becomes versioned, this gets more complicated. // TODO: when validation becomes versioned, this gets more complicated.
el := field.ErrorList{field.NewInvalidError(field.NewPath("spec", "ports").Index(i).Child("nodePort"), servicePort.NodePort, err.Error())} el := field.ErrorList{field.Invalid(field.NewPath("spec", "ports").Index(i).Child("nodePort"), servicePort.NodePort, err.Error())}
return nil, errors.NewInvalid("Service", service.Name, el) return nil, errors.NewInvalid("Service", service.Name, el)
} }
} else if assignNodePorts { } else if assignNodePorts {
@ -229,7 +229,7 @@ func (rs *REST) Update(ctx api.Context, obj runtime.Object) (runtime.Object, boo
if !contains(oldNodePorts, nodePort) { if !contains(oldNodePorts, nodePort) {
err := nodePortOp.Allocate(nodePort) err := nodePortOp.Allocate(nodePort)
if err != nil { if err != nil {
el := field.ErrorList{field.NewInvalidError(field.NewPath("spec", "ports").Index(i).Child("nodePort"), nodePort, err.Error())} el := field.ErrorList{field.Invalid(field.NewPath("spec", "ports").Index(i).Child("nodePort"), nodePort, err.Error())}
return nil, false, errors.NewInvalid("Service", service.Name, el) return nil, false, errors.NewInvalid("Service", service.Name, el)
} }
} }

View File

@ -50,7 +50,7 @@ func ParseWatchResourceVersion(resourceVersion string) (uint64, error) {
return 0, errors.NewInvalid("", "", field.ErrorList{ return 0, errors.NewInvalid("", "", field.ErrorList{
// Validation errors are supposed to return version-specific field // Validation errors are supposed to return version-specific field
// paths, but this is probably close enough. // paths, but this is probably close enough.
field.NewInvalidError(field.NewPath("resourceVersion"), resourceVersion, err.Error()), field.Invalid(field.NewPath("resourceVersion"), resourceVersion, err.Error()),
}) })
} }
return version + 1, nil return version + 1, nil

View File

@ -72,22 +72,22 @@ const (
// NewRequiredError. // NewRequiredError.
ErrorTypeRequired ErrorType = "FieldValueRequired" ErrorTypeRequired ErrorType = "FieldValueRequired"
// ErrorTypeDuplicate is used to report collisions of values that must be // ErrorTypeDuplicate is used to report collisions of values that must be
// unique (e.g. unique IDs). See NewDuplicateError. // unique (e.g. unique IDs). See Duplicate().
ErrorTypeDuplicate ErrorType = "FieldValueDuplicate" ErrorTypeDuplicate ErrorType = "FieldValueDuplicate"
// ErrorTypeInvalid is used to report malformed values (e.g. failed regex // ErrorTypeInvalid is used to report malformed values (e.g. failed regex
// match, too long, out of bounds). See NewInvalidError. // match, too long, out of bounds). See Invalid().
ErrorTypeInvalid ErrorType = "FieldValueInvalid" ErrorTypeInvalid ErrorType = "FieldValueInvalid"
// ErrorTypeNotSupported is used to report unknown values for enumerated // ErrorTypeNotSupported is used to report unknown values for enumerated
// fields (e.g. a list of valid values). See NewNotSupportedError. // fields (e.g. a list of valid values). See NotSupported().
ErrorTypeNotSupported ErrorType = "FieldValueNotSupported" ErrorTypeNotSupported ErrorType = "FieldValueNotSupported"
// ErrorTypeForbidden is used to report valid (as per formatting rules) // ErrorTypeForbidden is used to report valid (as per formatting rules)
// values which would be accepted under some conditions, but which are not // values which would be accepted under some conditions, but which are not
// permitted by the current conditions (such as security policy). See // permitted by the current conditions (such as security policy). See
// NewForbiddenError. // Forbidden().
ErrorTypeForbidden ErrorType = "FieldValueForbidden" ErrorTypeForbidden ErrorType = "FieldValueForbidden"
// ErrorTypeTooLong is used to report that the given value is too long. // ErrorTypeTooLong is used to report that the given value is too long.
// This is similar to ErrorTypeInvalid, but the error will not include the // This is similar to ErrorTypeInvalid, but the error will not include the
// too-long value. See NewTooLongError. // too-long value. See TooLong().
ErrorTypeTooLong ErrorType = "FieldValueTooLong" ErrorTypeTooLong ErrorType = "FieldValueTooLong"
// ErrorTypeInternal is used to report other errors that are not related // ErrorTypeInternal is used to report other errors that are not related
// to user input. // to user input.
@ -121,33 +121,33 @@ func (t ErrorType) String() string {
// NewNotFoundError returns a *Error indicating "value not found". This is // NewNotFoundError returns a *Error indicating "value not found". This is
// used to report failure to find a requested value (e.g. looking up an ID). // used to report failure to find a requested value (e.g. looking up an ID).
func NewNotFoundError(field *Path, value interface{}) *Error { func NotFound(field *Path, value interface{}) *Error {
return &Error{ErrorTypeNotFound, field.String(), value, ""} return &Error{ErrorTypeNotFound, field.String(), value, ""}
} }
// NewRequiredError returns a *Error indicating "value required". This is used // NewRequiredError returns a *Error indicating "value required". This is used
// to report required values that are not provided (e.g. empty strings, null // to report required values that are not provided (e.g. empty strings, null
// values, or empty arrays). // values, or empty arrays).
func NewRequiredError(field *Path) *Error { func Required(field *Path) *Error {
return &Error{ErrorTypeRequired, field.String(), "", ""} return &Error{ErrorTypeRequired, field.String(), "", ""}
} }
// NewDuplicateError returns a *Error indicating "duplicate value". This is // NewDuplicateError returns a *Error indicating "duplicate value". This is
// used to report collisions of values that must be unique (e.g. names or IDs). // used to report collisions of values that must be unique (e.g. names or IDs).
func NewDuplicateError(field *Path, value interface{}) *Error { func Duplicate(field *Path, value interface{}) *Error {
return &Error{ErrorTypeDuplicate, field.String(), value, ""} return &Error{ErrorTypeDuplicate, field.String(), value, ""}
} }
// NewInvalidError returns a *Error indicating "invalid value". This is used // NewInvalidError returns a *Error indicating "invalid value". This is used
// to report malformed values (e.g. failed regex match, too long, out of bounds). // to report malformed values (e.g. failed regex match, too long, out of bounds).
func NewInvalidError(field *Path, value interface{}, detail string) *Error { func Invalid(field *Path, value interface{}, detail string) *Error {
return &Error{ErrorTypeInvalid, field.String(), value, detail} return &Error{ErrorTypeInvalid, field.String(), value, detail}
} }
// NewNotSupportedError returns a *Error indicating "unsupported value". // NewNotSupportedError returns a *Error indicating "unsupported value".
// This is used to report unknown values for enumerated fields (e.g. a list of // This is used to report unknown values for enumerated fields (e.g. a list of
// valid values). // valid values).
func NewNotSupportedError(field *Path, value interface{}, validValues []string) *Error { func NotSupported(field *Path, value interface{}, validValues []string) *Error {
detail := "" detail := ""
if validValues != nil && len(validValues) > 0 { if validValues != nil && len(validValues) > 0 {
detail = "supported values: " + strings.Join(validValues, ", ") detail = "supported values: " + strings.Join(validValues, ", ")
@ -159,7 +159,7 @@ func NewNotSupportedError(field *Path, value interface{}, validValues []string)
// report valid (as per formatting rules) values which would be accepted under // report valid (as per formatting rules) values which would be accepted under
// some conditions, but which are not permitted by current conditions (e.g. // some conditions, but which are not permitted by current conditions (e.g.
// security policy). // security policy).
func NewForbiddenError(field *Path, value interface{}) *Error { func Forbidden(field *Path, value interface{}) *Error {
return &Error{ErrorTypeForbidden, field.String(), value, ""} return &Error{ErrorTypeForbidden, field.String(), value, ""}
} }
@ -167,14 +167,14 @@ func NewForbiddenError(field *Path, value interface{}) *Error {
// report that the given value is too long. This is similar to // report that the given value is too long. This is similar to
// NewInvalidError, but the returned error will not include the too-long // NewInvalidError, but the returned error will not include the too-long
// value. // value.
func NewTooLongError(field *Path, value interface{}, maxLength int) *Error { func TooLong(field *Path, value interface{}, maxLength int) *Error {
return &Error{ErrorTypeTooLong, field.String(), value, fmt.Sprintf("must have at most %d characters", maxLength)} return &Error{ErrorTypeTooLong, field.String(), value, fmt.Sprintf("must have at most %d characters", maxLength)}
} }
// NewInternalError returns a *Error indicating "internal error". This is used // NewInternalError returns a *Error indicating "internal error". This is used
// to signal that an error was found that was not directly related to user // to signal that an error was found that was not directly related to user
// input. The err argument must be non-nil. // input. The err argument must be non-nil.
func NewInternalError(field *Path, err error) *Error { func InternalError(field *Path, err error) *Error {
return &Error{ErrorTypeInternal, field.String(), nil, err.Error()} return &Error{ErrorTypeInternal, field.String(), nil, err.Error()}
} }

View File

@ -28,27 +28,27 @@ func TestMakeFuncs(t *testing.T) {
expected ErrorType expected ErrorType
}{ }{
{ {
func() *Error { return NewInvalidError(NewPath("f"), "v", "d") }, func() *Error { return Invalid(NewPath("f"), "v", "d") },
ErrorTypeInvalid, ErrorTypeInvalid,
}, },
{ {
func() *Error { return NewNotSupportedError(NewPath("f"), "v", nil) }, func() *Error { return NotSupported(NewPath("f"), "v", nil) },
ErrorTypeNotSupported, ErrorTypeNotSupported,
}, },
{ {
func() *Error { return NewDuplicateError(NewPath("f"), "v") }, func() *Error { return Duplicate(NewPath("f"), "v") },
ErrorTypeDuplicate, ErrorTypeDuplicate,
}, },
{ {
func() *Error { return NewNotFoundError(NewPath("f"), "v") }, func() *Error { return NotFound(NewPath("f"), "v") },
ErrorTypeNotFound, ErrorTypeNotFound,
}, },
{ {
func() *Error { return NewRequiredError(NewPath("f")) }, func() *Error { return Required(NewPath("f")) },
ErrorTypeRequired, ErrorTypeRequired,
}, },
{ {
func() *Error { return NewInternalError(NewPath("f"), fmt.Errorf("e")) }, func() *Error { return InternalError(NewPath("f"), fmt.Errorf("e")) },
ErrorTypeInternal, ErrorTypeInternal,
}, },
} }
@ -62,7 +62,7 @@ func TestMakeFuncs(t *testing.T) {
} }
func TestErrorUsefulMessage(t *testing.T) { func TestErrorUsefulMessage(t *testing.T) {
s := NewInvalidError(NewPath("foo"), "bar", "deet").Error() s := Invalid(NewPath("foo"), "bar", "deet").Error()
t.Logf("message: %v", s) t.Logf("message: %v", s)
for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} { for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} {
if !strings.Contains(s, part) { if !strings.Contains(s, part) {
@ -76,7 +76,7 @@ func TestErrorUsefulMessage(t *testing.T) {
Inner interface{} Inner interface{}
KV map[string]int KV map[string]int
} }
s = NewInvalidError( s = Invalid(
NewPath("foo"), NewPath("foo"),
&complicated{ &complicated{
Baz: 1, Baz: 1,
@ -102,8 +102,8 @@ func TestToAggregate(t *testing.T) {
testCases := []ErrorList{ testCases := []ErrorList{
nil, nil,
{}, {},
{NewInvalidError(NewPath("f"), "v", "d")}, {Invalid(NewPath("f"), "v", "d")},
{NewInvalidError(NewPath("f"), "v", "d"), NewInternalError(NewPath(""), fmt.Errorf("e"))}, {Invalid(NewPath("f"), "v", "d"), InternalError(NewPath(""), fmt.Errorf("e"))},
} }
for i, tc := range testCases { for i, tc := range testCases {
agg := tc.ToAggregate() agg := tc.ToAggregate()
@ -121,9 +121,9 @@ func TestToAggregate(t *testing.T) {
func TestErrListFilter(t *testing.T) { func TestErrListFilter(t *testing.T) {
list := ErrorList{ list := ErrorList{
NewInvalidError(NewPath("test.field"), "", ""), Invalid(NewPath("test.field"), "", ""),
NewInvalidError(NewPath("field.test"), "", ""), Invalid(NewPath("field.test"), "", ""),
NewDuplicateError(NewPath("test"), "value"), Duplicate(NewPath("test"), "value"),
} }
if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 { if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 {
t.Errorf("should not filter") t.Errorf("should not filter")