package cmd import ( "bufio" "crypto/rand" "errors" "fmt" "os" "os/exec" "path/filepath" "strings" "text/template" "git.fernandovideira.com/FernandoJVideira/draft/assets" ) const ( chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+" ) func randomString(length int) string { s, r := make([]rune, length), []rune(chars) for i := range s { p, _ := rand.Prime(rand.Reader, 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() }