@@ -30,6 +30,10 @@ import (
3030 cdi "tags.cncf.io/container-device-interface/specs-go"
3131)
3232
33+ type validator interface {
34+ Validate (* cdi.Spec ) error
35+ }
36+
3337type options struct {
3438 outputFormat string
3539 validator validator
@@ -106,6 +110,10 @@ func Save(raw *cdi.Spec, path string, opts ...Option) error {
106110func WriteTo (raw * cdi.Spec , w io.Writer , opts ... Option ) (int64 , error ) {
107111 o := populateOptions (opts ... )
108112
113+ if err := o .Validate (raw ); err != nil {
114+ return 0 , fmt .Errorf ("spec validation failed: %w" , err )
115+ }
116+
109117 data , err := o .marshal (raw )
110118 if err != nil {
111119 return 0 , fmt .Errorf ("failed to marshal spec: %w" , err )
@@ -243,3 +251,21 @@ func (o *options) marshal(v any) ([]byte, error) {
243251 return nil , fmt .Errorf ("invalid output format: %q" , o .outputFormat )
244252 }
245253}
254+
255+ // Validate a CDI specification using the supplied options.
256+ // If no validator is specified, validation always succeeds.
257+ func (o * options ) Validate (raw * cdi.Spec ) error {
258+ if o == nil || o .validator == nil {
259+ return nil
260+ }
261+ return o .validator .Validate (raw )
262+ }
263+
264+ type validatorFunction func (* cdi.Spec ) error
265+
266+ func (v validatorFunction ) Validate (raw * cdi.Spec ) error {
267+ if v == nil {
268+ return nil
269+ }
270+ return v (raw )
271+ }
0 commit comments