90 lines
2.2 KiB
Go
90 lines
2.2 KiB
Go
package template
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"text/template"
|
|
)
|
|
|
|
var (
|
|
scaffold = map[string]string{
|
|
"/.gitignore": templateGitignore,
|
|
"/Makefile": templateMakefile,
|
|
"/Dockerfile": templateDockerfile,
|
|
"/docker-compose.yaml": templateDockerCompose,
|
|
"/buf.yaml": templateBuf,
|
|
"/buf.gen.yaml": templateBufGen,
|
|
"/buf.work.yaml": templateBufWork,
|
|
"/go.mod": templateModule,
|
|
"/config_dev.yaml": templateDevYaml,
|
|
"/config_prod.yaml": templateProdYaml,
|
|
"/proto/v1/file_module.proto": templateApiservicesProto,
|
|
"/proto/v1/file_model.proto": templateProto,
|
|
"/proto/v1/buf.yaml": templateBuf,
|
|
"/cmd/serve.go": templateCmdNewServe,
|
|
"/cmd/exec.go": templateCmdExec,
|
|
"/common/time.go": templateCommon,
|
|
"/config/config.go": templateConfig,
|
|
"/register/register.go": templateRouter,
|
|
"/internal/repositories/.gitkeep": "",
|
|
"/services/.gitkeep": "",
|
|
"/gen/.gitkeep": "",
|
|
}
|
|
)
|
|
|
|
type Builder struct {
|
|
Name string
|
|
Path string
|
|
SSH string
|
|
}
|
|
|
|
func (b *Builder) Build() error {
|
|
if err := os.MkdirAll(b.Path, 0755); err != nil {
|
|
return err
|
|
}
|
|
if err := b.write(b.Path+"/"+b.Name+".go", templateMain); err != nil {
|
|
return err
|
|
}
|
|
for sr, v := range scaffold {
|
|
i := strings.LastIndex(sr, "/")
|
|
if i > 0 {
|
|
dir := sr[:i]
|
|
if err := os.MkdirAll(b.Path+dir, 0755); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := b.write(b.Path+sr, v); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (b *Builder) write(name, tpl string) (err error) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
fmt.Println("Failed")
|
|
}
|
|
}()
|
|
fmt.Printf("create %s \n", name)
|
|
data, err := b.parse(tpl)
|
|
if err != nil {
|
|
return
|
|
}
|
|
return os.WriteFile(name, data, 0644)
|
|
}
|
|
|
|
func (b *Builder) parse(s string) ([]byte, error) {
|
|
t, err := template.New("").Parse(s)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := t.Execute(&buf, b); err != nil {
|
|
return nil, err
|
|
}
|
|
return buf.Bytes(), nil
|
|
}
|