go-quasar-partial-ssr/backend/pkg/ts-rpc/TSFiles.go

79 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tsrpc
import (
"bytes"
"fmt"
"os"
"os/exec"
)
type TSFiles map[string]string
func (t *TSFiles) Add(name string, source string) {
if t == nil || *t == nil {
*t = make(map[string]string)
}
if (*t)[name] == "" {
(*t)[name] = source
} else {
(*t)[name] += source
}
}
func (t *TSFiles) Get(name string) (string, bool) {
if t == nil || *t == nil {
return "", false
}
s, ok := (*t)[name]
return s, ok
}
func (t *TSFiles) Save() error {
if t == nil || *t == nil {
return fmt.Errorf("TS Files not initialized")
}
var path string
if value, exists := os.LookupEnv("FRONTEND_API_PATH"); exists {
path = value
} else {
return fmt.Errorf("FRONTEND_API_PATH environment variable not set")
}
for name, source := range *t {
formatted, err := formatJS(source)
if err != nil {
return fmt.Errorf("format JS: %w", err)
}
err = os.WriteFile(fmt.Sprintf("%s/%s", path, name), []byte(formatted), 0644)
if err != nil {
return fmt.Errorf("write local generated typescript: %w", err)
}
}
return nil
}
func formatJS(src string) (string, error) {
// Se hai prettier globale:
cmd := exec.Command("prettier", "--parser", "typescript", "--use-tabs", "false", "--tab-width", "2")
// Se hai prettier solo come devDependency:
// cmd := exec.Command("npx", "prettier", "--parser", "typescript")
cmd.Stdin = bytes.NewBufferString(src)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
// Stampa anche lo stderr di Prettier, così vedi lerrore reale
return "", fmt.Errorf("prettier error: %v\nstderr: %s", err, stderr.String())
}
return out.String(), nil
}