feat: 优化项目创建命令,增加模板渲染支持

This commit is contained in:
Rogee
2025-09-10 14:17:11 +08:00
parent 1fac55115d
commit a714d4a3a9

View File

@@ -1,6 +1,7 @@
package cmd
import (
"bytes"
"fmt"
"io/fs"
"os"
@@ -9,11 +10,11 @@ import (
"strings"
"text/template"
"go.ipao.vip/atomctl/templates"
"go.ipao.vip/atomctl/pkg/utils/gomod"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"go.ipao.vip/atomctl/pkg/utils/gomod"
"go.ipao.vip/atomctl/templates"
)
// 验证包名是否合法:支持域名、路径分隔符和常见字符
@@ -115,25 +116,42 @@ func commandNewProjectE(cmd *cobra.Command, args []string) error {
return err
}
// 渲染判定:优先(.tpl/.raw) > 行内指令 > 模板分隔符
isTpl := false
if strings.HasSuffix(path, ".tpl") {
isTpl = true
targetPath = strings.TrimSuffix(targetPath, ".tpl")
} else if strings.HasSuffix(path, ".raw") {
isTpl = false
targetPath = strings.TrimSuffix(targetPath, ".raw")
} else if bytes.Contains(content, []byte("atomctl:mode=tpl")) {
isTpl = true
} else if bytes.Contains(content, []byte("atomctl:mode=raw")) {
isTpl = false
} else if bytes.Contains(content, []byte("{{")) && bytes.Contains(content, []byte("}}")) {
isTpl = true
}
if inPlace && strings.HasSuffix(path, string(os.PathSeparator)+"go.mod.tpl") {
if _, err := os.Stat(filepath.Join(rootDir, "go.mod")); err == nil {
log.Infof("跳过已有文件: %s", filepath.Join(rootDir, "go.mod"))
return nil
}
tmpl, err := template.New(filepath.Base(path)).Parse(string(content))
if err != nil {
return err
}
targetPath = strings.TrimSuffix(targetPath, ".tpl")
if !force {
if _, err := os.Stat(targetPath); err == nil {
log.Warnf("文件已存在,跳过: %s", targetPath)
return nil
}
}
log.Infof("创建文件: %s", targetPath)
if isTpl {
tmpl, err := template.New(filepath.Base(path)).Parse(string(content))
if err != nil {
return err
}
log.Infof("[渲染] 文件: %s", targetPath)
f, err := os.Create(targetPath)
if err != nil {
return errors.Wrapf(err, "创建文件失败 %s", targetPath)
@@ -142,17 +160,7 @@ func commandNewProjectE(cmd *cobra.Command, args []string) error {
return tmpl.Execute(f, projectInfo)
}
if strings.HasSuffix(path, ".raw") {
targetPath = strings.TrimSuffix(targetPath, ".raw")
}
if !force {
if _, err := os.Stat(targetPath); err == nil {
log.Warnf("文件已存在,跳过: %s", targetPath)
return nil
}
}
log.Infof("创建文件: %s", targetPath)
log.Infof("[复制] 文件: %s", targetPath)
return os.WriteFile(targetPath, content, 0o644)
}); err != nil {
return err