-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.go
More file actions
251 lines (219 loc) · 6.12 KB
/
init.go
File metadata and controls
251 lines (219 loc) · 6.12 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
Copyright 2022 The Apex Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cli
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
"github.com/tcnksm/go-input"
"gopkg.in/yaml.v3"
)
type InitCmd struct {
fromNew bool
Template string `arg:"" help:"The template for the project to create." default:"@apexlang/basic"`
Dir string `type:"existingdir" help:"The project directory" default:"."`
Spec string `type:"existingfile" help:"An optional specification file to copy into the project"`
Variables map[string]string `arg:"" help:"Variables to pass to the template." optional:""`
}
func (c *InitCmd) Run(ctx *Context) error {
if strings.Contains(c.Template, "..") {
return fmt.Errorf("invalid template %s", c.Template)
}
homeDir, err := getHomeDirectory()
if err != nil {
return err
}
templatePart := strings.ReplaceAll(c.Template, "/", string(filepath.Separator))
templatePath := filepath.Join(homeDir, "templates", templatePart)
// If a short name was provided and does not exist,
// assume its a first-party template and prepend "@apexlang/".
if !strings.HasPrefix(templatePart, "@") {
if _, err := os.Stat(templatePath); err != nil && os.IsNotExist(err) {
templatePart = filepath.Join("@apexlang", templatePart)
templatePath = filepath.Join(homeDir, "templates", templatePart)
}
}
templateDir, err := os.Stat(templatePath)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("template %s is not installed", c.Template)
}
return err
}
if !templateDir.IsDir() {
return fmt.Errorf("%s is not a template directory", templatePath)
}
projectDirInfo, projectDirErr := os.Stat(c.Dir)
if c.fromNew {
if projectDirErr == nil {
return fmt.Errorf("%s already exists", c.Dir)
}
fmt.Printf("Creating project directory %s\n", c.Dir)
if err = os.MkdirAll(c.Dir, 0777); err != nil {
return err
}
} else {
if projectDirErr != nil {
return projectDirErr
}
if !projectDirInfo.IsDir() {
return fmt.Errorf("%s is not a directory", c.Dir)
}
}
if c.Variables == nil {
c.Variables = map[string]string{}
}
// project name defaults to directory name
if _, ok := c.Variables["name"]; !ok {
name := filepath.Base(c.Dir)
c.Variables["name"] = name
}
templateBytes, err := os.ReadFile(filepath.Join(templatePath, ".template"))
if err != nil {
return err
}
var template Template
if err = yaml.Unmarshal(templateBytes, &template); err != nil {
return err
}
ui := &input.UI{
Writer: os.Stdout,
Reader: os.Stdin,
}
for _, variable := range template.Variables {
if _, ok := c.Variables[variable.Name]; !ok {
value, err := ui.Ask(variable.Prompt, &input.Options{
Default: variable.Default,
Required: variable.Required,
Loop: variable.Loop,
HideOrder: true,
})
if err != nil {
return err
}
c.Variables[variable.Name] = value
}
}
err = c.copy(templatePath, c.Dir, c.Variables)
if err != nil {
return err
}
if c.Spec != "" {
if template.SpecLocation == "" {
template.SpecLocation = "spec.apex"
}
specFilename := filepath.Join(c.Dir, filepath.Clean(template.SpecLocation))
specBytes, err := os.ReadFile(c.Spec)
if err != nil {
return err
}
err = os.WriteFile(specFilename, specBytes, 0644)
if err != nil {
return err
}
}
// TODO: Make dynamic (and secure)
switch c.Template {
case "@apexlang/local":
cmd := exec.Command("npm", "install")
cmd.Dir = filepath.Join(c.Dir, "codegen")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return err
}
case "@apexlang/module":
cmd := exec.Command("npm", "install")
cmd.Dir = c.Dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return err
}
}
return nil
}
func (c *InitCmd) copy(source, destination string, variables map[string]string) error {
return filepath.Walk(source, func(path string, info os.FileInfo, ferr error) error {
var relPath string = strings.Replace(path, source, "", 1)
if relPath == "" {
return nil
}
sourcePath := filepath.Join(source, relPath)
stat, err := os.Stat(sourcePath)
if err != nil {
return err
}
if info.IsDir() {
dstPath := filepath.Join(destination, relPath)
dstPath, err = injectPathVariables(dstPath, variables)
if err != nil {
return err
}
return os.MkdirAll(dstPath, stat.Mode())
} else {
base := filepath.Base(sourcePath)
if base == ".keep" || base == ".gitkeep" ||
base == ".template" || strings.HasPrefix(base, ".git") {
return nil
}
data, err := os.ReadFile(sourcePath)
if err != nil {
return err
}
if filepath.Ext(relPath) == ".tmpl" {
tmpl, err := template.New(relPath).Parse(string(data))
if err != nil {
return err
}
var buf bytes.Buffer
if err = tmpl.Execute(&buf, c.Variables); err != nil {
return err
}
data = buf.Bytes()
relPath = relPath[:len(relPath)-5]
}
dstPath := filepath.Join(destination, relPath)
dstPath, err = injectPathVariables(dstPath, variables)
if err != nil {
return err
}
if !c.fromNew {
// If the file exists, skip writing it.
if _, err := os.Stat(dstPath); err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
return nil // File exists so skip.
}
}
return os.WriteFile(dstPath, data, stat.Mode())
}
})
}
func injectPathVariables(dstPath string, variables map[string]string) (string, error) {
tmpl, err := template.New("destPath").Parse(dstPath)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err = tmpl.Execute(&buf, variables); err != nil {
return "", err
}
return buf.String(), nil
}