-
Notifications
You must be signed in to change notification settings - Fork 5
/
gootstrap.go
90 lines (75 loc) · 2.18 KB
/
gootstrap.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
package gootstrap
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
texttemplate "text/template"
"github.com/NeowayLabs/gootstrap/template"
)
// Config used by template functions
type Config struct {
Project string
Module string
DockerImg string
GoVersion string
CILintVersion string
AlpineVersion string
}
// CreateProject creates a project
func CreateProject(cfg Config, rootdir string) error {
files := map[string]string{
"go.sum": "",
"go.mod": template.GoMod,
"README.md": template.Readme,
"Makefile": template.Makefile,
"Dockerfile": template.Dockerfile,
"hack/Dockerfile": template.DockerfileDev,
"hack/githooks/pre-commit": template.GitHookPreCommit,
".gitignore": template.GitIgnore,
".dockerignore": template.DockerIgnore,
".gitlab-ci.yml": template.GitlabCI,
"cmd/{{.Project}}/{{.Project}}.go": template.Cmd,
}
for pathtmpl, contenttmpl := range files {
path, err := execTemplate(pathtmpl, pathtmpl, cfg)
if err != nil {
return err
}
contents, err := execTemplate(path, contenttmpl, cfg)
if err != nil {
return err
}
if err := writeFile(filepath.Join(rootdir, path), contents); err != nil {
return err
}
}
return nil
}
func writeFile(path string, contents string) error {
dir := filepath.Dir(path)
if err := ensureDir(dir); err != nil {
return err
}
if _, err := os.Stat(path); err == nil {
fmt.Printf("file[%s] already exists, it will not be touched, nothing to do\n", path)
return nil
}
return ioutil.WriteFile(path, []byte(contents), 0644)
}
func execTemplate(name string, templ string, cfg Config) (string, error) {
tmpl, err := texttemplate.New(name).Parse(templ)
if err != nil {
return "", fmt.Errorf("error creating %s template: %s", name, err)
}
buf := &bytes.Buffer{}
err = tmpl.Execute(buf, cfg)
if err != nil {
return "", fmt.Errorf("error executing %s template: %s", name, err)
}
return buf.String(), nil
}
func ensureDir(dir string) error {
return os.MkdirAll(dir, 0755)
}