gotygen/cmd/root.go

105 lines
2.4 KiB
Go

package cmd
import (
"bytes"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"githouse.ru/macrox/gotygen/pkg/strcase"
"githouse.ru/macrox/gotygen/pkg/filler"
"githouse.ru/macrox/gotygen/pkg/utils"
"githouse.ru/macrox/gotygen/internal/config"
"githouse.ru/macrox/gotygen/pkg/document"
"github.com/spf13/cobra"
"golang.org/x/exp/slog"
)
var rootCmd = &cobra.Command{
Use: "gotygen",
Short: "Generate Go type definitions from JSON",
Run: func(cmd *cobra.Command, args []string) {
conf, workDir, err := config.Read()
if len(workDir) > 1 {
fmt.Println("Work dir:", workDir)
}
if err != nil {
slog.Error("failed read config", err)
os.Exit(1)
}
if len(conf.Packages) < 1 {
slog.Warn("empty packages in config")
os.Exit(1)
}
for _, p := range conf.Packages {
doc := document.NewDocument(p.Name,
fmt.Sprintf("Generated with gotygen v%s // %s", version, time.Now().Format(time.RFC3339)),
)
for _, i := range p.Inputs {
if len(i.Name) < 1 {
i.Name = strcase.ToCamel(utils.TrimmedFilenameFromPath(i.Path))
if len(i.Name) < 1 {
slog.Warn("input config constrain empty name")
continue
}
}
data, err := os.ReadFile(i.Path)
if err != nil {
slog.Error("failed to read input file", err)
os.Exit(1)
}
f := filler.NewJsonFiller(data, i.Name, p.Acronyms...)
if len(p.Replacements) > 0 {
f.UseReplacements(p.Replacements)
}
if len(i.Replacements) > 0 {
f.UseReplacements(i.Replacements)
}
if len(i.Acronyms) > 0 {
f.UseCaps(i.Acronyms)
}
if err = f.Fill(doc); err != nil {
slog.Error("failed fill document", err)
}
}
buffer := new(bytes.Buffer)
if _, err = buffer.WriteString(doc.String()); err != nil {
slog.Error("failed to write document to buffer", err)
os.Exit(1)
}
if p.Output == "" {
_, _ = io.Copy(os.Stdout, buffer)
} else {
_ = os.MkdirAll(filepath.Dir(p.Output), os.ModePerm)
if strings.HasSuffix(p.Output, "/") {
err = os.WriteFile(fmt.Sprint(p.Output, p.Name, ".go"), buffer.Bytes(), os.ModePerm)
} else {
err = os.WriteFile(p.Output, buffer.Bytes(), os.ModePerm)
}
}
if err != nil {
slog.Error("failed to write output file", err)
os.Exit(1)
}
buffer.Reset()
}
},
}
func init() {
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
log.Fatalln(err)
}
}