forked from turnerlabs/fargate
/
main.go
95 lines (81 loc) · 2.09 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package dockercompose
import (
"bytes"
"io/ioutil"
"os/exec"
"github.com/turnerlabs/fargate/console"
yaml "gopkg.in/yaml.v2"
)
//ComposeFile represents a docker-compose.yml file
//that can be manipulated
type ComposeFile struct {
File string
Data DockerCompose
}
//Read loads a docker-compose.yml file
func Read(file string) ComposeFile {
result := ComposeFile{
File: file,
}
result.Read()
return result
}
//New returns an initialized compose file
func New(file string) ComposeFile {
result := ComposeFile{
File: file,
Data: DockerCompose{
Version: "3.7",
Services: make(map[string]*Service),
},
}
return result
}
//Read reads the data structure from the file
//note that all variable interpolations are fully rendered
func (composeFile *ComposeFile) Read() {
console.Debug("running docker-compose config [%s]", composeFile.File)
cmd := exec.Command("docker-compose", "-f", composeFile.File, "config")
var outbuf, errbuf bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
if err := cmd.Start(); err != nil {
console.ErrorExit(err, errbuf.String())
}
if err := cmd.Wait(); err != nil {
console.IssueExit(errbuf.String())
}
//unmarshal the yaml
var compose DockerCompose
err := yaml.Unmarshal(outbuf.Bytes(), &compose)
if err != nil {
console.ErrorExit(err, "error unmarshalling docker-compose.yml")
}
composeFile.Data = compose
}
//AddService adds a service to a compose file
func (composeFile *ComposeFile) AddService(name string) *Service {
result := &Service{}
result.Environment = make(map[string]string)
result.Labels = make(map[string]string)
result.Secrets = make(map[string]string)
result.Ports = []Port{}
composeFile.Data.Services[name] = result
return result
}
//Yaml returns the yaml for this compose file
func (composeFile *ComposeFile) Yaml() ([]byte, error) {
return yaml.Marshal(composeFile.Data)
}
//Write writes the data to a file
func (composeFile *ComposeFile) Write() error {
bits, err := composeFile.Yaml()
if err != nil {
return err
}
err = ioutil.WriteFile(composeFile.File, bits, 0644)
if err != nil {
return err
}
return nil
}