core/utils/file.go

64 lines
1.3 KiB
Go
Raw Normal View History

2025-02-07 13:01:38 +08:00
package utils
import (
"errors"
"io"
"os"
2025-02-18 23:42:23 +08:00
"path/filepath"
2025-02-07 13:01:38 +08:00
)
2025-02-18 23:42:23 +08:00
// 将字符串写入文件
2025-02-07 13:01:38 +08:00
func StringToFile(path, content string) error {
startF, err := os.Create(path)
if err != nil {
return errors.New("os.Create create file " + path + " error:" + err.Error())
}
defer startF.Close()
_, err = io.WriteString(startF, content)
if err != nil {
return errors.New("io.WriteString to " + path + " error:" + err.Error())
}
return nil
}
2025-02-18 23:42:23 +08:00
// 递归遍历文件夹
// rootDir: 文件夹根目录
// s: 存储文件名的切片
// filter: 过滤条件:".git", ".idea", ".vscode", ".gitignore", ".gitea", ".github", ".golangci.yml", "*.pyc"
func FileTree(rootDir string, s []string, filter []string) ([]string, error) {
rd, err := os.ReadDir(rootDir)
if err != nil {
return s, err
}
for _, fi := range rd {
// 检查文件名是否匹配任何一个过滤模式
matched := false
for _, item := range filter {
exists, err := filepath.Match(item, fi.Name())
if err != nil {
continue
}
if exists {
matched = true
break
}
}
if matched {
continue
}
if fi.IsDir() {
fullDir := rootDir + "/" + fi.Name()
s, err = FileTree(fullDir, s, filter)
if err != nil {
return s, err
}
} else {
fullName := rootDir + "/" + fi.Name()
s = append(s, fullName)
}
}
return s, nil
}