- 运行目录定位、路径存在性、带进度回调下载、Zip 打包/解压(兼容 GBK 中文文件名) - 附单元测试、examples/filex 例程与包 README
78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
// Package filex 文件与目录工具:工作目录/运行目录定位、路径存在性判断、
|
|
// 带进度回调的文件下载、Zip 打包与解压(兼容 GBK 中文文件名)。
|
|
package filex
|
|
|
|
import (
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
)
|
|
|
|
// 获取工作目录
|
|
func GetWorkDir() string {
|
|
str, _ := os.Getwd()
|
|
return str
|
|
}
|
|
|
|
// trimmedPath 规范化路径并去掉末尾分隔符
|
|
func trimmedPath(file string) string {
|
|
idx := strings.LastIndexByte(file, '/')
|
|
if idx == -1 {
|
|
return file
|
|
}
|
|
// Find the penultimate separator.
|
|
idx = strings.LastIndexByte(file[:idx], '/')
|
|
if idx == -1 {
|
|
return file
|
|
}
|
|
return file[:idx+1]
|
|
}
|
|
|
|
// 最终方案-全兼容
|
|
func GetRunDir() string {
|
|
dir := getCurrentAbPathByExecutable()
|
|
if strings.Contains(dir, getTmpDir()) {
|
|
dir = GetWorkDir()
|
|
}
|
|
// 结尾不是分隔符时补上(原写法用 || 恒为 true,行为等价但触发 vet 告警)
|
|
if dir[len(dir)-1:] != "/" && dir[len(dir)-1:] != "\\" {
|
|
dir += string(filepath.Separator)
|
|
}
|
|
return dir
|
|
}
|
|
|
|
// 获取系统临时目录,兼容go run
|
|
func getTmpDir() string {
|
|
dir := os.Getenv("TEMP")
|
|
if dir == "" {
|
|
dir = os.Getenv("TMP")
|
|
}
|
|
res, _ := filepath.EvalSymlinks(dir)
|
|
// 取父目录
|
|
dir = filepath.Dir(res)
|
|
return dir
|
|
}
|
|
|
|
// 获取当前执行文件绝对路径 (go build)
|
|
func getCurrentAbPathByExecutable() string {
|
|
exePath, err := os.Executable()
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
|
|
return res
|
|
}
|
|
|
|
// 获取当前执行文件绝对路径(go run)
|
|
func GetCurrentAbPathByCaller() string {
|
|
var abPath string
|
|
_, filename, _, ok := runtime.Caller(0)
|
|
if ok {
|
|
abPath = path.Dir(filename)
|
|
}
|
|
abPath = trimmedPath(filename)
|
|
return abPath
|
|
}
|