|
| 1 | +/* |
| 2 | + Copyright © 2024 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 producer |
| 18 | + |
| 19 | +import ( |
| 20 | + "encoding/json" |
| 21 | + "fmt" |
| 22 | + "os" |
| 23 | + "path/filepath" |
| 24 | + |
| 25 | + "sigs.k8s.io/yaml" |
| 26 | + |
| 27 | + cdi "tags.cncf.io/container-device-interface/specs-go" |
| 28 | +) |
| 29 | + |
| 30 | +type spec struct { |
| 31 | + *cdi.Spec |
| 32 | + format specFormat |
| 33 | +} |
| 34 | + |
| 35 | +// save saves a CDI spec to the specified filename. |
| 36 | +func (s *spec) save(filename string, overwrite bool) error { |
| 37 | + data, err := s.contents() |
| 38 | + if err != nil { |
| 39 | + return fmt.Errorf("failed to marshal Spec file: %w", err) |
| 40 | + } |
| 41 | + |
| 42 | + dir := filepath.Dir(filename) |
| 43 | + if dir != "" { |
| 44 | + if err := os.MkdirAll(dir, 0o755); err != nil { |
| 45 | + return fmt.Errorf("failed to create Spec dir: %w", err) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + tmp, err := os.CreateTemp(dir, "spec.*.tmp") |
| 50 | + if err != nil { |
| 51 | + return fmt.Errorf("failed to create Spec file: %w", err) |
| 52 | + } |
| 53 | + _, err = tmp.Write(data) |
| 54 | + tmp.Close() |
| 55 | + if err != nil { |
| 56 | + return fmt.Errorf("failed to write Spec file: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + err = renameIn(dir, filepath.Base(tmp.Name()), filepath.Base(filename), overwrite) |
| 60 | + if err != nil { |
| 61 | + _ = os.Remove(tmp.Name()) |
| 62 | + return fmt.Errorf("failed to write Spec file: %w", err) |
| 63 | + } |
| 64 | + return nil |
| 65 | +} |
| 66 | + |
| 67 | +// contents returns the raw contents of a CDI specification. |
| 68 | +func (s *spec) contents() ([]byte, error) { |
| 69 | + switch s.format { |
| 70 | + case SpecFormatYAML: |
| 71 | + data, err := yaml.Marshal(s.Spec) |
| 72 | + if err != nil { |
| 73 | + return nil, err |
| 74 | + } |
| 75 | + data = append([]byte("---\n"), data...) |
| 76 | + return data, nil |
| 77 | + case SpecFormatJSON: |
| 78 | + return json.Marshal(s.Spec) |
| 79 | + default: |
| 80 | + return nil, fmt.Errorf("undefined CDI spec format %v", s.format) |
| 81 | + } |
| 82 | +} |
0 commit comments