替换module名,排除.git目录

This commit is contained in:
许 洋 2024-08-08 11:42:31 +08:00
parent a0e154be11
commit 986bb9e3e1

31
main.go
View File

@ -49,11 +49,10 @@ func main() {
replacements := getReplacements()
if _, ok := replacements["{{PROJECT_NAME}}"]; !ok {
replacements["{{PROJECT_NAME}}"] = projectName
replacements["{{PROJECT_NAME}}"] = filepath.Base(projectName)
}
var err error
if remoteTemplatePath != "" {
err = handleRemoteTemplate(templatePath, branch, projectName, replacements)
} else {
@ -68,6 +67,22 @@ func main() {
fmt.Printf("Project %s created successfully!\n", projectName)
}
func getModuleName(goModPath string) (string, error) {
content, err := os.ReadFile(goModPath)
if err != nil {
return "", err
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "module ") {
return strings.TrimSpace(strings.TrimPrefix(line, "module ")), nil
}
}
return "", fmt.Errorf("module name not found in go.mod")
}
func handleRemoteTemplate(templateRepo, branch, projectName string, replacements map[string]string) (err error) {
// 创建临时目录
tempDir, err := os.MkdirTemp("", "template-*")
@ -115,6 +130,14 @@ func getReplacements() map[string]string {
}
func copyTemplate(src, dist string, replacements map[string]string) (err error) {
// 读取 go.mod 文件中的模块名称
oldModuleName, err := getModuleName(filepath.Join(src, "go.mod"))
if err != nil {
log.Printf("error reading module name: %s", err)
os.Exit(1)
}
replacements[oldModuleName] = replacements["{{PROJECT_NAME}}"]
return filepath.Walk(src, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
@ -129,6 +152,10 @@ func copyTemplate(src, dist string, replacements map[string]string) (err error)
// 获取目标路径
targetPath := filepath.Join(dist, relPath)
if info.IsDir() && filepath.Base(path) == ".git" {
return filepath.SkipDir
}
if info.IsDir() {
// 创建目录
return os.MkdirAll(targetPath, info.Mode())