|
| 1 | +/* |
| 2 | + Copyright 2020 The Compose Specification 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 types |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "strings" |
| 22 | +) |
| 23 | + |
| 24 | +// Labels is a mapping type for labels |
| 25 | +type Labels map[string]string |
| 26 | + |
| 27 | +func (l Labels) Add(key, value string) Labels { |
| 28 | + if l == nil { |
| 29 | + l = Labels{} |
| 30 | + } |
| 31 | + l[key] = value |
| 32 | + return l |
| 33 | +} |
| 34 | + |
| 35 | +func (l Labels) AsList() []string { |
| 36 | + s := make([]string, len(l)) |
| 37 | + i := 0 |
| 38 | + for k, v := range l { |
| 39 | + s[i] = fmt.Sprintf("%s=%s", k, v) |
| 40 | + i++ |
| 41 | + } |
| 42 | + return s |
| 43 | +} |
| 44 | + |
| 45 | +// label value can be a string | number | boolean | null (empty) |
| 46 | +func labelValue(e interface{}) string { |
| 47 | + if e == nil { |
| 48 | + return "" |
| 49 | + } |
| 50 | + switch v := e.(type) { |
| 51 | + case string: |
| 52 | + return v |
| 53 | + default: |
| 54 | + return fmt.Sprint(v) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +func (l *Labels) DecodeMapstructure(value interface{}) error { |
| 59 | + switch v := value.(type) { |
| 60 | + case map[string]interface{}: |
| 61 | + labels := make(map[string]string, len(v)) |
| 62 | + for k, e := range v { |
| 63 | + labels[k] = labelValue(e) |
| 64 | + } |
| 65 | + *l = labels |
| 66 | + case []interface{}: |
| 67 | + labels := make(map[string]string, len(v)) |
| 68 | + for _, s := range v { |
| 69 | + k, e, ok := strings.Cut(fmt.Sprint(s), "=") |
| 70 | + if !ok { |
| 71 | + return fmt.Errorf("invalid label %q", v) |
| 72 | + } |
| 73 | + labels[k] = labelValue(e) |
| 74 | + } |
| 75 | + *l = labels |
| 76 | + default: |
| 77 | + return fmt.Errorf("unexpected value type %T for labels", value) |
| 78 | + } |
| 79 | + return nil |
| 80 | +} |
0 commit comments