-
Notifications
You must be signed in to change notification settings - Fork 0
/
scaffold.go
92 lines (79 loc) · 1.85 KB
/
scaffold.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
package renderer
import (
"fmt"
"io"
"os"
"path/filepath"
apiv1 "github.com/jakew/cargo/api/v1"
"gopkg.in/yaml.v2"
)
// WriteScaffolding creates the scaffolding for the end user to modify.
func WriteScaffolding(rootPath, cargofile, tmplfile, configfile, outputfile string) error {
if !isDir(rootPath) {
if err := os.MkdirAll(rootPath, os.ModePerm); err != nil {
return err
}
}
cargopath := filepath.Join(rootPath, cargofile)
tmplpath := filepath.Join(rootPath, tmplfile)
configpath := filepath.Join(rootPath, configfile)
for name, path := range map[string]string{
"cargo file": cargopath,
"template file": tmplpath,
"config file": configpath,
} {
if hasFile(path) {
return fmt.Errorf("%s %s already exists", name, cargopath)
}
}
crg := apiv1.Cargo{
CargoVersion: "v0",
Config: apiv1.Config{
"baseContainer": "alpine",
},
Manifests: []apiv1.Manifest{
{
Dockerfile: tmplfile,
OutputFile: outputfile,
ConfigFiles: []string{
configfile,
},
Config: apiv1.Config{
"message": "Hello World!",
},
},
},
}
cfg := map[string]interface{}{
"alpineTag": "latest",
}
if err := writeFile(cargopath, func(w io.Writer) error {
return yaml.NewEncoder(w).Encode(crg)
}); err != nil {
return err
}
if err := writeFile(configpath, func(w io.Writer) error {
return yaml.NewEncoder(w).Encode(cfg)
}); err != nil {
return err
}
return writeFile(tmplpath, func(w io.Writer) error {
_, err := w.Write([]byte("FROM alpine:{{ .alpineTag }}\nRUN echo \"{{ .message }}\""))
return err
})
}
func writeFile(filename string, fn func(io.Writer) error) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
return fn(f)
}
func isDir(dir string) bool {
fileInfo, err := os.Stat(dir)
if !os.IsNotExist(err) && fileInfo.IsDir() {
return true
}
return false
}