Public Access
270 lines
6.5 KiB
Go
270 lines
6.5 KiB
Go
package cmd
|
|
|
|
import (
|
|
"bufio"
|
|
"crypto/rand"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"math/big"
|
|
"os"
|
|
"os/exec"
|
|
"path"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"text/template"
|
|
|
|
"git.fernandovideira.com/FernandoJVideira/draft/assets"
|
|
"github.com/manifoldco/promptui"
|
|
)
|
|
|
|
const (
|
|
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+"
|
|
)
|
|
|
|
func randomString(length int) string {
|
|
s, r := make([]rune, length), []rune(chars)
|
|
|
|
for i := range s {
|
|
p, _ := rand.Int(rand.Reader, big.NewInt(int64(len(r))))
|
|
x, y := p.Uint64(), uint64(len(r))
|
|
s[i] = r[x%y]
|
|
}
|
|
return string(s)
|
|
}
|
|
|
|
func genFile(tplPath, tplName, outputPath string, data any) error {
|
|
tplContent, err := assets.EmbedFS.ReadFile(tplPath)
|
|
if err != nil {
|
|
return fmt.Errorf("error reading %s template: %w", tplPath, err)
|
|
}
|
|
|
|
tpl, err := template.New(tplName).Parse(string(tplContent))
|
|
if err != nil {
|
|
return fmt.Errorf("error parsing %s template: %w", tplPath, err)
|
|
}
|
|
|
|
if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
|
|
return fmt.Errorf("error ensuring directory for %s: %w", outputPath, err)
|
|
}
|
|
|
|
outFile, err := os.Create(outputPath)
|
|
if err != nil {
|
|
return fmt.Errorf("error creating %s: %w", outputPath, err)
|
|
}
|
|
defer outFile.Close()
|
|
|
|
return tpl.Execute(outFile, data)
|
|
}
|
|
|
|
func getModuleName() (string, error) {
|
|
dir, err := os.Getwd()
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to get working directory: %w", err)
|
|
}
|
|
|
|
for {
|
|
goModPath := filepath.Join(dir, "go.mod")
|
|
file, err := os.Open(goModPath)
|
|
if err == nil {
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
line := strings.TrimSpace(scanner.Text())
|
|
if str, ok := strings.CutPrefix(line, "module "); ok {
|
|
return strings.TrimSpace(str), nil
|
|
}
|
|
}
|
|
if err := scanner.Err(); err != nil {
|
|
return "", fmt.Errorf("failed to read %s: %w", goModPath, err)
|
|
}
|
|
return "", fmt.Errorf("module directive not found in %s", goModPath)
|
|
}
|
|
|
|
if !errors.Is(err, os.ErrNotExist) {
|
|
return "", fmt.Errorf("failed to open %s: %w", goModPath, err)
|
|
}
|
|
|
|
parent := filepath.Dir(dir)
|
|
if parent == dir {
|
|
return "", fmt.Errorf("go.mod not found starting from %s", dir)
|
|
}
|
|
dir = parent
|
|
}
|
|
}
|
|
|
|
func runCommand(dir, name string, args ...string) error {
|
|
cmd := exec.Command(name, args...)
|
|
cmd.Dir = dir
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
|
|
return cmd.Run()
|
|
}
|
|
|
|
func commandExists(name string) bool {
|
|
_, err := exec.LookPath(name)
|
|
return err == nil
|
|
}
|
|
|
|
func requirePnpmAndNpx() error {
|
|
if !commandExists("pnpm") {
|
|
return fmt.Errorf("pnpm is required but not found on PATH")
|
|
}
|
|
if !commandExists("npx") {
|
|
return fmt.Errorf("npx is required but not found on PATH")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func promptClientFramework() (isVue bool, resultLabel string, err error) {
|
|
prompt := promptui.Select{
|
|
Label: "Select Client Framework",
|
|
Items: []string{"Nuxt", "Vue"},
|
|
}
|
|
_, result, err := prompt.Run()
|
|
if err != nil {
|
|
return false, "", err
|
|
}
|
|
return result == "Vue", result, nil
|
|
}
|
|
|
|
func pnpmVersion() (string, error) {
|
|
out, err := exec.Command("pnpm", "--version").Output()
|
|
if err != nil {
|
|
return "", fmt.Errorf("error getting pnpm version: %w", err)
|
|
}
|
|
return strings.TrimSpace(string(out)), nil
|
|
}
|
|
|
|
func toPascalCase(s string) string {
|
|
parts := regexp.MustCompile(`[^a-zA-Z0-9]+`).Split(s, -1)
|
|
var b strings.Builder
|
|
for _, p := range parts {
|
|
if p == "" {
|
|
continue
|
|
}
|
|
b.WriteString(strings.ToUpper(p[:1]))
|
|
b.WriteString(p[1:])
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func promptProjectName() (moduleName, projectDir, serviceName string, err error) {
|
|
prompt := promptui.Prompt{Label: "Project Name"}
|
|
rawInput, err := prompt.Run()
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
moduleName = strings.TrimSpace(rawInput)
|
|
projectDir = path.Base(strings.TrimSuffix(moduleName, "/"))
|
|
serviceName = toPascalCase(projectDir)
|
|
return moduleName, projectDir, serviceName, nil
|
|
}
|
|
|
|
func promptAPIType() (useGRPC bool, resultLabel string, err error) {
|
|
prompt := promptui.Select{
|
|
Label: "Select API Type",
|
|
Items: []string{"HTTP (REST)", "gRPC"},
|
|
}
|
|
_, result, err := prompt.Run()
|
|
if err != nil {
|
|
return false, "", err
|
|
}
|
|
return strings.Contains(result, "gRPC"), result, nil
|
|
}
|
|
|
|
func copyEmbeddedDir(root, destDir string, replacements map[string]string) error {
|
|
return fs.WalkDir(assets.EmbedFS, root, func(path string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if d.IsDir() {
|
|
return nil
|
|
}
|
|
|
|
relPath, _ := filepath.Rel(root, path)
|
|
contentBytes, err := assets.EmbedFS.ReadFile(path)
|
|
if err != nil {
|
|
return fmt.Errorf("error reading embedded file %s: %w", path, err)
|
|
}
|
|
|
|
content := string(contentBytes)
|
|
for old, new := range replacements {
|
|
content = strings.ReplaceAll(content, old, new)
|
|
}
|
|
|
|
targetPath := filepath.Join(destDir, relPath)
|
|
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
|
return fmt.Errorf("error creating directory %s: %w", filepath.Dir(targetPath), err)
|
|
}
|
|
|
|
return os.WriteFile(targetPath, []byte(content), 0644)
|
|
})
|
|
}
|
|
|
|
type scaffoldRecipe struct {
|
|
label string
|
|
destSubdir string
|
|
preScaffold func(projectDir string) error
|
|
postScaffold func(projectDir string) error
|
|
}
|
|
|
|
func runNewProject(recipe scaffoldRecipe) {
|
|
moduleName, projectDir, serviceName, err := promptProjectName()
|
|
if err != nil {
|
|
fmt.Printf("Prompt failed %v\n", err)
|
|
return
|
|
}
|
|
|
|
useGRPC, resultLabel, err := promptAPIType()
|
|
if err != nil {
|
|
fmt.Printf("Prompt failed %v\n", err)
|
|
return
|
|
}
|
|
|
|
if useGRPC && !commandExists("protoc") {
|
|
fmt.Println("❌ protoc is required for gRPC projects but wasn't found on PATH.")
|
|
fmt.Println(" Install it (e.g. `brew install protobuf`) and try again.")
|
|
return
|
|
}
|
|
|
|
fmt.Printf("🚀 Scaffolding %s '%s' as %s...\n", recipe.label, moduleName, resultLabel)
|
|
|
|
if recipe.preScaffold != nil {
|
|
if err := recipe.preScaffold(projectDir); err != nil {
|
|
fmt.Printf("error preparing project: %v", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := scaffoldAPI(projectDir, recipe.destSubdir, moduleName, serviceName, useGRPC); err != nil {
|
|
fmt.Printf("error scaffolding project: %v", err)
|
|
return
|
|
}
|
|
|
|
fmt.Println("📦 Installing tools...")
|
|
if err := installTools(useGRPC); err != nil {
|
|
fmt.Printf("error installing tools: %v", err)
|
|
return
|
|
}
|
|
|
|
fmt.Println("🧹 Tidying up Go modules...")
|
|
destRoot := filepath.Join(projectDir, recipe.destSubdir)
|
|
if err := runCommand(destRoot, "go", "mod", "tidy"); err != nil {
|
|
fmt.Printf("error running 'go mod tidy': %v", err)
|
|
return
|
|
}
|
|
|
|
if recipe.postScaffold != nil {
|
|
if err := recipe.postScaffold(projectDir); err != nil {
|
|
fmt.Printf("error finishing project: %v", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
fmt.Println("✅ Done!")
|
|
}
|