-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (100 loc) · 1.98 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
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"embed"
"flag"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
//go:embed templates/*
var embeddedFS embed.FS
type projectInfo struct {
Project string
}
func main() {
project := flag.String("p", "demo", "Project Name")
if flag.Parsed() == false {
flag.Parse()
}
err := copy(*project)
if err != nil {
_ = os.RemoveAll(*project)
log.Fatalf("internal %v", err)
}
err = render(*project, &projectInfo{Project: *project})
if err != nil {
_ = os.RemoveAll(*project)
log.Fatalf("internal %v", err)
}
}
func render(tmplDir string, pi *projectInfo) error {
return filepath.WalkDir(tmplDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if !strings.HasSuffix(d.Name(), ".tmpl") {
return nil
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
err = os.Remove(path)
if err != nil {
return err
}
tmplName := d.Name()
tmpl, err := template.New(tmplName).Parse(string(content))
if err != nil {
return err
}
path, _ = strings.CutSuffix(path, ".tmpl")
localFile, err := os.Create(path)
if err != nil {
return err
}
err = tmpl.Execute(localFile, pi)
if err != nil {
return err
}
return localFile.Close()
})
}
func copy(localDir string) error {
err := os.MkdirAll(localDir, 0755)
if err != nil {
return err
}
return fs.WalkDir(embeddedFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
s, _ := strings.CutPrefix(path, "templates")
localPath := filepath.Join(localDir, s)
if localPath == "" || localPath == "." {
return nil
}
if d.IsDir() {
return os.MkdirAll(localPath, 0755)
}
embeddedFile, err := embeddedFS.Open(path)
if err != nil {
return err
}
defer embeddedFile.Close()
localFile, err := os.Create(localPath)
if err != nil {
return err
}
defer localFile.Close()
_, err = io.Copy(localFile, embeddedFile)
return err
})
}