|  | 
|  | 1 | +/* | 
|  | 2 | +   Copyright © 2022 The CDI Authors | 
|  | 3 | +
 | 
|  | 4 | +   Licensed under the Apache License, Version 2.0 (the "License"); | 
|  | 5 | +   you may not use this file except in compliance with the License. | 
|  | 6 | +   You may obtain a copy of the License at | 
|  | 7 | +
 | 
|  | 8 | +       http://www.apache.org/licenses/LICENSE-2.0 | 
|  | 9 | +
 | 
|  | 10 | +   Unless required by applicable law or agreed to in writing, software | 
|  | 11 | +   distributed under the License is distributed on an "AS IS" BASIS, | 
|  | 12 | +   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 
|  | 13 | +   See the License for the specific language governing permissions and | 
|  | 14 | +   limitations under the License. | 
|  | 15 | +*/ | 
|  | 16 | + | 
|  | 17 | +package validate | 
|  | 18 | + | 
|  | 19 | +import ( | 
|  | 20 | +	"github.com/container-orchestrated-devices/container-device-interface/schema" | 
|  | 21 | +	raw "github.com/container-orchestrated-devices/container-device-interface/specs-go" | 
|  | 22 | +) | 
|  | 23 | + | 
|  | 24 | +const ( | 
|  | 25 | +	// DefaultExternalSchema is the default JSON schema to load for validation. | 
|  | 26 | +	DefaultExternalSchema = "/etc/cdi/schema/schema.json" | 
|  | 27 | +) | 
|  | 28 | + | 
|  | 29 | +// WithSchema returns a CDI Spec validator that uses the given Schema. | 
|  | 30 | +func WithSchema(s *schema.Schema) func(*raw.Spec) error { | 
|  | 31 | +	if s == nil { | 
|  | 32 | +		return func(*raw.Spec) error { | 
|  | 33 | +			return nil | 
|  | 34 | +		} | 
|  | 35 | +	} | 
|  | 36 | +	return func(spec *raw.Spec) error { | 
|  | 37 | +		return s.ValidateType(spec) | 
|  | 38 | +	} | 
|  | 39 | +} | 
|  | 40 | + | 
|  | 41 | +// WithNamedSchema loads the named JSON schema and returns a CDI Spec | 
|  | 42 | +// validator for it. If loading the schema fails a dummy validator is | 
|  | 43 | +// returned. | 
|  | 44 | +func WithNamedSchema(name string) func(*raw.Spec) error { | 
|  | 45 | +	s, _ := schema.Load(name) | 
|  | 46 | +	return WithSchema(s) | 
|  | 47 | +} | 
|  | 48 | + | 
|  | 49 | +// WithDefaultSchema returns a CDI Spec validator that uses the default | 
|  | 50 | +// external JSON schema, or the default builtin one if the external one | 
|  | 51 | +// fails to load. | 
|  | 52 | +func WithDefaultSchema() func(*raw.Spec) error { | 
|  | 53 | +	s, err := schema.Load(DefaultExternalSchema) | 
|  | 54 | +	if err == nil { | 
|  | 55 | +		return WithSchema(s) | 
|  | 56 | +	} | 
|  | 57 | +	return WithSchema(schema.BuiltinSchema()) | 
|  | 58 | +} | 
0 commit comments