forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
70 lines (58 loc) · 1.75 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package utils
import (
"github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
)
// Config holds libcompose top level configuration
type Config struct {
Version string `yaml:"version,omitempty"`
Services RawServiceMap `yaml:"services,omitempty"`
Volumes map[string]interface{} `yaml:"volumes,omitempty"`
Networks map[string]interface{} `yaml:"networks,omitempty"`
}
// RawService is represent a Service in map form unparsed
type RawService map[string]interface{}
// RawServiceMap is a collection of RawServices
type RawServiceMap map[string]RawService
// CreateConfig unmarshals bytes to config and creates config based on version
func CreateConfig(bytes []byte) (*Config, error) {
var config Config
if err := yaml.Unmarshal(bytes, &config); err != nil {
return nil, err
}
if config.Version != "2" {
var baseRawServices RawServiceMap
if err := yaml.Unmarshal(bytes, &baseRawServices); err != nil {
return nil, err
}
config.Services = baseRawServices
}
if config.Volumes == nil {
config.Volumes = make(map[string]interface{})
}
if config.Networks == nil {
config.Networks = make(map[string]interface{})
}
return &config, nil
}
// Convert converts a struct (src) to another one (target) using yaml marshalling/unmarshalling.
// If the structure are not compatible, this will throw an error as the unmarshalling will fail.
func Convert(src, target interface{}) error {
newBytes, err := yaml.Marshal(src)
if err != nil {
return err
}
err = yaml.Unmarshal(newBytes, target)
if err != nil {
logrus.Errorf("Failed to unmarshall: %v\n%s", err, string(newBytes))
}
return err
}
func Contains(collection []string, key string) bool {
for _, value := range collection {
if value == key {
return true
}
}
return false
}