github.com/cptung/libcompose@v0.4.3/labels/labels.go (about) 1 package labels 2 3 import ( 4 "encoding/json" 5 "fmt" 6 7 "github.com/docker/libcompose/utils" 8 ) 9 10 // Label represents a docker label. 11 type Label string 12 13 // Libcompose default labels. 14 const ( 15 NUMBER = Label("com.docker.compose.container-number") 16 ONEOFF = Label("com.docker.compose.oneoff") 17 PROJECT = Label("com.docker.compose.project") 18 SERVICE = Label("com.docker.compose.service") 19 HASH = Label("com.docker.compose.config-hash") 20 VERSION = Label("com.docker.compose.version") 21 ) 22 23 // EqString returns a label json string representation with the specified value. 24 func (f Label) EqString(value string) string { 25 return LabelFilterString(string(f), value) 26 } 27 28 // Eq returns a label map representation with the specified value. 29 func (f Label) Eq(value string) map[string][]string { 30 return LabelFilter(string(f), value) 31 } 32 33 // AndString returns a json list of labels by merging the two specified values (left and right) serialized as string. 34 func AndString(left, right string) string { 35 leftMap := map[string][]string{} 36 rightMap := map[string][]string{} 37 38 // Ignore errors 39 json.Unmarshal([]byte(left), &leftMap) 40 json.Unmarshal([]byte(right), &rightMap) 41 42 for k, v := range rightMap { 43 existing, ok := leftMap[k] 44 if ok { 45 leftMap[k] = append(existing, v...) 46 } else { 47 leftMap[k] = v 48 } 49 } 50 51 result, _ := json.Marshal(leftMap) 52 53 return string(result) 54 } 55 56 // And returns a map of labels by merging the two specified values (left and right). 57 func And(left, right map[string][]string) map[string][]string { 58 result := map[string][]string{} 59 for k, v := range left { 60 result[k] = v 61 } 62 63 for k, v := range right { 64 existing, ok := result[k] 65 if ok { 66 result[k] = append(existing, v...) 67 } else { 68 result[k] = v 69 } 70 } 71 72 return result 73 } 74 75 // Str returns the label name. 76 func (f Label) Str() string { 77 return string(f) 78 } 79 80 // LabelFilterString returns a label json string representation of the specifed couple (key,value) 81 // that is used as filter for docker. 82 func LabelFilterString(key, value string) string { 83 return utils.FilterString(map[string][]string{ 84 "label": {fmt.Sprintf("%s=%s", key, value)}, 85 }) 86 } 87 88 // LabelFilter returns a label map representation of the specifed couple (key,value) 89 // that is used as filter for docker. 90 func LabelFilter(key, value string) map[string][]string { 91 return map[string][]string{ 92 "label": {fmt.Sprintf("%s=%s", key, value)}, 93 } 94 }