Skip to content

Commit

Permalink
feat(doc): readme
Browse files Browse the repository at this point in the history
  • Loading branch information
morehao committed Jul 26, 2024
1 parent 97a4099 commit c3b454d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 42 deletions.
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,23 @@
# gocutter
gocutter: A CLI for rapidly scaffolding Go projects with templates or by cloning existing structures.
# go-cutter
`go-cutter`是一个命令行工具,用于快速使用模板或克隆现有结构来脚手架Go项目。

# 功能特性
- 在模板项目根路径下执行命令可创建新的Go项目
- 自动替换 import 路径
- 自动更新 go.mod 文件中的模块名称
- 自动删除 .git 目录

***注意:一定要在模板项目的根路径下执行命令***
# 安装
```shell
go install github.com/morehao/go-cutter@latest
```
# 使用方法
## 初始化新项目
```shell
cd /appTemplatePath
go-cutter -d /yourAppPath
```
- `-d, --destination`:新项目的目标目录,例如:`/user/myApp`。此参数为必填项。


42 changes: 2 additions & 40 deletions cmd/cutter.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"bufio"
"fmt"
"go/ast"
"go/format"
Expand Down Expand Up @@ -43,14 +42,8 @@ func cutter(newProjectPath string) error {
return fmt.Errorf("create new project directory: %w", err)
}

// 读取.gitignore文件并创建排除列表
excludes, err := readGitignore(filepath.Join(currentDir, ".gitignore"))
if err != nil {
return fmt.Errorf("read .gitignore fail, err: %w", err)
}

// 复制模板项目到新项目目录,并替换import路径
if err := copyAndReplace(currentDir, newProjectPath, templateName, newProjectName, excludes); err != nil {
if err := copyAndReplace(currentDir, newProjectPath, templateName, newProjectName); err != nil {
return fmt.Errorf("copy and replace fail, err: %w", err)
}
if err := removeGitDir(newProjectPath); err != nil {
Expand All @@ -65,44 +58,13 @@ func isGoProject(path string) bool {
return !os.IsNotExist(err)
}

// readGitignore 读取.gitignore文件并返回排除列表
func readGitignore(filename string) ([]string, error) {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return []string{}, nil
}
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()

var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "#") {
lines = append(lines, line)
}
}
return lines, scanner.Err()
}

// copyAndReplace copy指定目录,并替换import路径
func copyAndReplace(srcDir, dstDir, oldName, newName string, excludes []string) error {
func copyAndReplace(srcDir, dstDir, oldName, newName string) error {
err := filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

// 检查是否排除
for _, exclude := range excludes {
if strings.Contains(path, exclude) {
fmt.Println("Excluding:", path)
return nil
}
}

// 创建目标目录
targetPath := strings.Replace(path, srcDir, dstDir, 1)
if info.IsDir() {
Expand Down

0 comments on commit c3b454d

Please sign in to comment.