-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_setup.go
More file actions
603 lines (520 loc) · 16 KB
/
cmd_setup.go
File metadata and controls
603 lines (520 loc) · 16 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
package main
import (
"archive/zip"
"bufio"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
)
// ──────────────────────────────────────────────
// Constants
// ──────────────────────────────────────────────
const (
setupTemplateRepo = "caiolandgraf/grove-base"
setupTemplateBranch = "main"
)
// ──────────────────────────────────────────────
// Command definition
// ──────────────────────────────────────────────
var setupModuleFlag string
var setupCmd = &cobra.Command{
Use: "setup [project-name]",
Short: "Scaffold a new Grove project from the official template",
Long: bold("setup") + ` downloads and scaffolds a complete Grove project
from the official template repository on GitHub.
If you omit the project name, Grove will prompt you for it.
` + colorGray + `Examples:` + colorReset + `
grove setup my-api
grove setup my-api --module github.com/acme/my-api
grove setup # prompt for project name`,
Args: cobra.RangeArgs(0, 1),
RunE: runSetup,
}
func init() {
setupCmd.Flags().StringVar(
&setupModuleFlag,
"module", "",
"Go module path (defaults to project name)",
)
}
// ──────────────────────────────────────────────
// Spinner
// ──────────────────────────────────────────────
var spinFrames = []rune{'⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'}
type step struct {
label string
stopCh chan struct{}
doneCh chan struct{}
}
func startStep(label string) *step {
s := &step{
label: label,
stopCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
go func() {
defer close(s.doneCh)
tick := time.NewTicker(80 * time.Millisecond)
defer tick.Stop()
i := 0
for {
select {
case <-s.stopCh:
return
case <-tick.C:
fmt.Printf(
"\r\033[2K %s%c%s %s",
colorCyan, spinFrames[i%len(spinFrames)], colorReset,
s.label,
)
i++
}
}
}()
return s
}
func (s *step) succeed(extra string) {
close(s.stopCh)
<-s.doneCh
if extra != "" {
fmt.Printf(
"\r\033[2K %s✓%s %-36s %s\n",
colorGreen, colorReset,
s.label,
colorDim+extra+colorReset,
)
} else {
fmt.Printf("\r\033[2K %s✓%s %s\n", colorGreen, colorReset, s.label)
}
}
func (s *step) fail(extra string) {
close(s.stopCh)
<-s.doneCh
line := s.label
if extra != "" {
line += " " + colorDim + extra + colorReset
}
fmt.Printf("\r\033[2K %s✕%s %s\n", colorRed, colorReset, line)
}
// ──────────────────────────────────────────────
// Main runner
// ──────────────────────────────────────────────
func runSetup(_ *cobra.Command, args []string) error {
projectName, err := resolveProjectName(args)
if err != nil {
return err
}
modulePath := setupModuleFlag
if modulePath == "" {
modulePath = projectName
}
// Validate target directory
if _, err := os.Stat(projectName); err == nil {
return fmt.Errorf("directory %q already exists", projectName)
}
printSetupHeader(projectName, modulePath)
obs := promptObservability()
// Hide cursor for the entire setup flow
fmt.Print("\033[?25l")
defer fmt.Print("\033[?25h")
// Cleanup on failure
succeeded := false
defer func() {
if !succeeded {
_ = os.RemoveAll(projectName)
}
}()
// ── Step 1: Download ───────────────────────────────────────────────────
s := startStep("Downloading template")
zipPath, size, err := downloadTemplate()
if err != nil {
s.fail(err.Error())
return fmt.Errorf("download failed: %w", err)
}
s.succeed(fmtBytes(size))
defer os.Remove(zipPath)
// ── Step 2: Extract ────────────────────────────────────────────────────
s = startStep("Extracting files")
fileCount, err := extractTemplate(zipPath, projectName)
if err != nil {
s.fail(err.Error())
return fmt.Errorf("extraction failed: %w", err)
}
s.succeed(fmt.Sprintf("%d files", fileCount))
// ── Step 3: Configure observability ───────────────────────────────────
s = startStep("Configuring observability")
if err := configureObservability(projectName, obs); err != nil {
s.fail(err.Error())
return fmt.Errorf("observability configuration failed: %w", err)
}
s.succeed(obs.summary())
// ── Step 4: Configure module ───────────────────────────────────────────
s = startStep("Configuring module")
if err := configureModule(projectName, modulePath); err != nil {
s.fail(err.Error())
return fmt.Errorf("configuration failed: %w", err)
}
s.succeed(modulePath)
// ── Step 5: Install dependencies ──────────────────────────────────────
s = startStep("Installing dependencies")
start := time.Now()
if err := runGoModTidy(projectName); err != nil {
s.fail(err.Error())
return fmt.Errorf("go mod tidy failed: %w", err)
}
s.succeed(fmtDuration(time.Since(start)))
// ── Step 6: Add gest library to go.mod ────────────────────────────────
s = startStep("Installing gest")
start = time.Now()
if err := runGoGetGest(projectName); err != nil {
// Non-fatal: the user can run `go get` manually later.
s.fail("run `go get " + gestModule + "` manually")
} else {
s.succeed(fmtDuration(time.Since(start)))
}
// ── Step 7: Install gest CLI globally ─────────────────────────────────
s = startStep("Installing gest CLI")
start = time.Now()
if err := runGoInstallGestCLI(); err != nil {
// Non-fatal: grove test falls back to go test -v when absent.
s.fail("run `go install " + gestCLIModule + "` manually")
} else {
s.succeed(fmtDuration(time.Since(start)))
}
succeeded = true
printSetupSuccess(projectName)
return nil
}
func resolveProjectName(args []string) (string, error) {
if len(args) > 0 {
name := strings.TrimSpace(args[0])
if name == "" {
return "", fmt.Errorf("project name cannot be empty")
}
return name, nil
}
return promptProjectName()
}
func promptProjectName() (string, error) {
info, err := os.Stdin.Stat()
if err != nil || (info.Mode()&os.ModeCharDevice) == 0 {
return "", fmt.Errorf(
"project name is required when stdin is not a TTY",
)
}
fmt.Println()
fmt.Println(" " + bold("Project name"))
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf(" %s ", gray("Enter project name:"))
input, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
name := strings.TrimSpace(input)
if name == "" {
fmt.Println(" " + warn("Please enter a project name."))
if err == io.EOF {
return "", fmt.Errorf("project name cannot be empty")
}
continue
}
return name, nil
}
}
// ──────────────────────────────────────────────
// Download
// ──────────────────────────────────────────────
func downloadTemplate() (tmpFile string, size int64, err error) {
url := fmt.Sprintf(
"https://github.com/%s/archive/refs/heads/%s.zip",
setupTemplateRepo, setupTemplateBranch,
)
resp, err := http.Get(url) //nolint:noctx
if err != nil {
return "", 0, fmt.Errorf("network error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", 0, fmt.Errorf("HTTP %s", resp.Status)
}
f, err := os.CreateTemp("", "grove-setup-*.zip")
if err != nil {
return "", 0, err
}
defer f.Close()
size, err = io.Copy(f, resp.Body)
if err != nil {
_ = os.Remove(f.Name())
return "", 0, fmt.Errorf("download error: %w", err)
}
return f.Name(), size, nil
}
// ──────────────────────────────────────────────
// Extraction
// ──────────────────────────────────────────────
// setupSkipPaths are paths (relative to the repo root) that should never be
// copied into the new project.
var setupSkipPaths = []string{
"bin/",
"tmp/",
"grove", // compiled binary at repo root
}
func extractTemplate(zipPath, destDir string) (int, error) {
r, err := zip.OpenReader(zipPath)
if err != nil {
return 0, err
}
defer r.Close()
// GitHub ZIPs always have a single top-level directory named
// "{repo}-{branch}/". Find it so we can strip it.
prefix := ""
for _, f := range r.File {
if idx := strings.Index(f.Name, "/"); idx >= 0 {
prefix = f.Name[:idx+1]
break
}
}
count := 0
for _, f := range r.File {
rel := strings.TrimPrefix(f.Name, prefix)
if rel == "" {
continue
}
if setupShouldSkip(rel) {
continue
}
dest := filepath.Join(destDir, filepath.FromSlash(rel))
if f.FileInfo().IsDir() {
if err := os.MkdirAll(dest, 0o755); err != nil {
return count, err
}
continue
}
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return count, err
}
if err := extractFile(f, dest); err != nil {
return count, err
}
count++
}
return count, nil
}
func extractFile(f *zip.File, dest string) error {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, rc)
return err
}
func setupShouldSkip(rel string) bool {
for _, skip := range setupSkipPaths {
if rel == skip || strings.HasPrefix(rel, skip) {
return true
}
}
return false
}
// ──────────────────────────────────────────────
// Module configuration
// ──────────────────────────────────────────────
func configureModule(projectDir, newModule string) error {
goModPath := filepath.Join(projectDir, "go.mod")
raw, err := os.ReadFile(goModPath)
if err != nil {
return fmt.Errorf("cannot read go.mod: %w", err)
}
// Extract the original module name declared in go.mod
oldModule := ""
for _, line := range strings.Split(string(raw), "\n") {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "module ") {
oldModule = strings.TrimSpace(
strings.TrimPrefix(trimmed, "module "),
)
break
}
}
if oldModule == "" {
return fmt.Errorf("module directive not found in go.mod")
}
if oldModule == newModule {
return nil // nothing to do
}
return filepath.WalkDir(
projectDir,
func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if d.Name() == ".git" {
return filepath.SkipDir
}
return nil
}
name := d.Name()
if name != "go.mod" && !strings.HasSuffix(name, ".go") {
return nil
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
replaced := strings.ReplaceAll(
string(content),
oldModule,
newModule,
)
if replaced == string(content) {
return nil // nothing changed
}
return os.WriteFile(path, []byte(replaced), 0o644)
},
)
}
// ──────────────────────────────────────────────
// go mod tidy
// ──────────────────────────────────────────────
func runGoModTidy(projectDir string) error {
if _, err := exec.LookPath("go"); err != nil {
return fmt.Errorf("go binary not found in PATH")
}
cmd := exec.Command("go", "mod", "tidy")
cmd.Dir = projectDir
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("%s", msg)
}
return nil
}
// runGoGetGest runs "go get github.com/caiolandgraf/gest/v2@latest" inside
// projectDir, adding gest to the project's go.mod.
func runGoGetGest(projectDir string) error {
cmd := exec.Command("go", "get", gestModule)
cmd.Dir = projectDir
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("%s", msg)
}
return nil
}
// runGoInstallGestCLI runs "go install github.com/caiolandgraf/gest/v2/cmd/gest@latest"
// to make the gest CLI available globally on the user's PATH.
func runGoInstallGestCLI() error {
cmd := exec.Command("go", "install", gestCLIModule)
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("%s", msg)
}
return nil
}
// ──────────────────────────────────────────────
// UI helpers
// ──────────────────────────────────────────────
func printSetupHeader(projectName, modulePath string) {
sep := " " + colorDim + strings.Repeat("─", 54) + colorReset
logo := "\n" +
logoG1 + ` █▀▀ █▀█ █▀█ █░█ █▀▀ ` + colorReset + "\n" +
logoG3 + ` █▄█ █▀▄ █▄█ ▀▄▀ ██▄ ` + colorReset + "\n"
fmt.Println(logo)
fmt.Printf(
" %sProject%s %s\n",
colorBold+colorGray, colorReset,
bold(projectName),
)
fmt.Printf(
" %sModule%s %s\n",
colorBold+colorGray, colorReset,
colorCyan+modulePath+colorReset,
)
fmt.Printf(
" %sTemplate%s %s\n",
colorBold+colorGray, colorReset,
colorDim+setupTemplateRepo+colorReset,
)
fmt.Println()
fmt.Println(sep)
fmt.Println()
}
func printSetupSuccess(projectName string) {
sep := " " + colorDim + strings.Repeat("─", 54) + colorReset
fmt.Println()
fmt.Println(sep)
fmt.Println()
fmt.Println(done("Project created in " + bold("./"+projectName)))
fmt.Println()
fmt.Println(nextSteps())
fmt.Printf(
" %s1.%s %s\n",
colorGray,
colorReset,
colorGreen+"cd "+projectName+colorReset,
)
fmt.Printf(
" %s2.%s %s\n",
colorGray,
colorReset,
colorGreen+"cp .env.example .env"+colorReset,
)
fmt.Printf(
" %s3.%s %s\n",
colorGray,
colorReset,
colorGreen+"grove up"+colorReset,
)
fmt.Printf(
" %s4.%s %s %s\n",
colorGray,
colorReset,
colorGreen+"grove make:test <Name>"+colorReset,
colorDim+"scaffold your first test"+colorReset,
)
fmt.Println()
}
// ──────────────────────────────────────────────
// Formatting helpers
// ──────────────────────────────────────────────
func fmtBytes(n int64) string {
switch {
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/float64(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%.0f KB", float64(n)/float64(1<<10))
default:
return fmt.Sprintf("%d B", n)
}
}
func fmtDuration(d time.Duration) string {
if d < time.Second {
return fmt.Sprintf("%dms", d.Milliseconds())
}
return fmt.Sprintf("%.1fs", d.Seconds())
}