Skip to content

Commit d028ee3

Browse files
committed
ParseAll: refactor
Avoid using `strings.Split`, and error on empty values. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 8f5e31a commit d028ee3

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

platforms.go

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -280,13 +280,9 @@ func Parse(specifier string) (specs.Platform, error) {
280280
}
281281
p.OSVersion = osVersion
282282
if osOptions[3] != "" {
283-
rawFeatures := strings.Split(osOptions[3][1:], "+")
284-
p.OSFeatures = make([]string, len(rawFeatures))
285-
for i, f := range rawFeatures {
286-
p.OSFeatures[i], err = decodeOSOption(f)
287-
if err != nil {
288-
return specs.Platform{}, fmt.Errorf("%q has an invalid OS feature %q: %w", specifier, f, err)
289-
}
283+
p.OSFeatures, err = parseOSFeatures(osOptions[3][1:])
284+
if err != nil {
285+
return specs.Platform{}, fmt.Errorf("%q has invalid OS features: %w", specifier, err)
290286
}
291287
}
292288
} else {
@@ -346,6 +342,30 @@ func Parse(specifier string) (specs.Platform, error) {
346342
return specs.Platform{}, fmt.Errorf("%q: cannot parse platform specifier: %w", specifier, errInvalidArgument)
347343
}
348344

345+
func parseOSFeatures(s string) ([]string, error) {
346+
if s == "" {
347+
return nil, nil
348+
}
349+
350+
var features []string
351+
for raw := range strings.SplitSeq(s, "+") {
352+
raw = strings.TrimSpace(raw)
353+
if raw == "" {
354+
return nil, fmt.Errorf("empty os feature: %w", errInvalidArgument)
355+
}
356+
feature, err := decodeOSOption(raw)
357+
if err != nil {
358+
return nil, fmt.Errorf("invalid os feature %q: %w", raw, err)
359+
}
360+
if feature == "" {
361+
continue
362+
}
363+
features = append(features, feature)
364+
}
365+
366+
return features, nil
367+
}
368+
349369
// MustParse is like Parses but panics if the specifier cannot be parsed.
350370
// Simplifies initialization of global variables.
351371
func MustParse(specifier string) specs.Platform {
@@ -371,6 +391,9 @@ func FormatAll(platform specs.Platform) string {
371391
if platform.OS == "" {
372392
return "unknown"
373393
}
394+
if platform.OSVersion == "" && len(platform.OSFeatures) == 0 {
395+
return path.Join(platform.OS, platform.Architecture, platform.Variant)
396+
}
374397

375398
var b strings.Builder
376399
b.WriteString(platform.OS)

0 commit comments

Comments
 (0)