|
| 1 | +/* |
| 2 | +Copyright 2024 The Kubernetes 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 options |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "runtime" |
| 22 | + "strings" |
| 23 | + |
| 24 | + ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 25 | + "github.com/spf13/cobra" |
| 26 | +) |
| 27 | + |
| 28 | +// PlatformOption represents |
| 29 | +type PlatformOption struct { |
| 30 | + // PlatformStr contains the raw platform argument provided by the user. |
| 31 | + PlatformStr string |
| 32 | + // Platform represents the OCI platform specification, built from PlatformStr. |
| 33 | + Platform *ocispec.Platform |
| 34 | +} |
| 35 | + |
| 36 | +// Parse takes the PlatformStr argument provided by the user |
| 37 | +// to build OCI platform specification. |
| 38 | +func (opt *PlatformOption) Parse(*cobra.Command) error { |
| 39 | + var pStr string |
| 40 | + |
| 41 | + if opt.PlatformStr == "" { |
| 42 | + return nil |
| 43 | + } |
| 44 | + |
| 45 | + platform := &ocispec.Platform{} |
| 46 | + pStr, platform.OSVersion, _ = strings.Cut(opt.PlatformStr, ":") |
| 47 | + parts := strings.Split(pStr, "/") |
| 48 | + |
| 49 | + switch len(parts) { |
| 50 | + case 3: |
| 51 | + platform.Variant = parts[2] |
| 52 | + fallthrough |
| 53 | + case 2: |
| 54 | + platform.Architecture = parts[1] |
| 55 | + case 1: |
| 56 | + platform.Architecture = runtime.GOARCH |
| 57 | + default: |
| 58 | + return fmt.Errorf("failed to parse platform %q: expected format os[/arch[/variant]]", opt.PlatformStr) |
| 59 | + } |
| 60 | + |
| 61 | + platform.OS = parts[0] |
| 62 | + if platform.OS == "" { |
| 63 | + return fmt.Errorf("invalid platform: OS cannot be empty") |
| 64 | + } |
| 65 | + if platform.Architecture == "" { |
| 66 | + return fmt.Errorf("invalid platform: Architecture cannot be empty") |
| 67 | + } |
| 68 | + opt.Platform = platform |
| 69 | + return nil |
| 70 | +} |
0 commit comments