From e9ea8fa536f00a6c8caa56d874fbb045af185e22 Mon Sep 17 00:00:00 2001 From: tx7do Date: Fri, 27 Oct 2023 16:58:06 +0800 Subject: [PATCH] feat: io utils --- io/path.go | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 io/path.go diff --git a/io/path.go b/io/path.go new file mode 100644 index 0000000..e8c5a4c --- /dev/null +++ b/io/path.go @@ -0,0 +1,82 @@ +package common + +import ( + "os" + "path/filepath" +) + +func GetWorkingDirPath() string { + dir, err := os.Getwd() + if err != nil { + panic(err) + } + return dir +} + +func GetExePath() string { + ex, err := os.Executable() + if err != nil { + panic(err) + } + exePath := filepath.Dir(ex) + return exePath +} + +func GetAbsPath() string { + dir, err := filepath.Abs(filepath.Dir(os.Args[0])) + if err != nil { + panic(err) + } + return dir +} + +// PathExist 路径是否存在 +func PathExist(path string) bool { + _, err := os.Stat(path) + if err == nil { + return true + } + if os.IsNotExist(err) { + return false + } + return false +} + +// GetFileList 获取文件夹下面的所有文件的列表 +func GetFileList(root string) []string { + var files []string + + if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + if info.IsDir() { + return nil + } + + files = append(files, path) + return nil + }); err != nil { + return nil + } + + return files +} + +// GetFolderNameList 获取当前文件夹下面的所有文件夹名的列表 +func GetFolderNameList(root string) []string { + var names []string + fs, _ := os.ReadDir(root) + for _, file := range fs { + if file.IsDir() { + names = append(names, file.Name()) + } + } + return names +} + +// ReadFile 读取文件 +func ReadFile(path string) []byte { + content, err := os.ReadFile(path) + if err != nil { + return nil + } + return content +}