Skip to content

Commit f0e62ae

Browse files
committed
🧱 find workdir any case
1 parent 9abd3f5 commit f0e62ae

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

util/path.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package util
2+
3+
import (
4+
"os"
5+
"path"
6+
"path/filepath"
7+
"runtime"
8+
"strings"
9+
)
10+
11+
func GetCurrentAbsPath() string {
12+
// 最终方案-全兼容
13+
dir := getCurrentAbPathByExecutable()
14+
tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
15+
// 如果是临时目录或者是goland运行的目录,那么就用caller的方式获取
16+
if strings.Contains(dir, tmpDir) || strings.Contains(dir, "GoLand") {
17+
return getCurrentAbPathByCaller()
18+
}
19+
return dir
20+
}
21+
22+
func GetWorkdir() string {
23+
currentAbsPath := GetCurrentAbsPath()
24+
workDir := filepath.Join(currentAbsPath, "..")
25+
return workDir
26+
}
27+
28+
// 获取当前执行文件绝对路径
29+
func getCurrentAbPathByExecutable() string {
30+
exePath, err := os.Executable()
31+
if err != nil {
32+
panic(err)
33+
}
34+
res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
35+
return res
36+
}
37+
38+
// 获取当前执行文件绝对路径(go run)
39+
func getCurrentAbPathByCaller() string {
40+
var abPath string
41+
_, filename, _, ok := runtime.Caller(0)
42+
if ok {
43+
abPath = path.Dir(filename)
44+
}
45+
return abPath
46+
}

0 commit comments

Comments
 (0)