Skip to content

Commit

Permalink
🧱 find workdir any case
Browse files Browse the repository at this point in the history
  • Loading branch information
warjiang committed Jun 15, 2023
1 parent 9abd3f5 commit f0e62ae
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions util/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package util

import (
"os"
"path"
"path/filepath"
"runtime"
"strings"
)

func GetCurrentAbsPath() string {
// 最终方案-全兼容
dir := getCurrentAbPathByExecutable()
tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
// 如果是临时目录或者是goland运行的目录,那么就用caller的方式获取
if strings.Contains(dir, tmpDir) || strings.Contains(dir, "GoLand") {
return getCurrentAbPathByCaller()
}
return dir
}

func GetWorkdir() string {
currentAbsPath := GetCurrentAbsPath()
workDir := filepath.Join(currentAbsPath, "..")
return workDir
}

// 获取当前执行文件绝对路径
func getCurrentAbPathByExecutable() string {
exePath, err := os.Executable()
if err != nil {
panic(err)
}
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)
}
return abPath
}

0 comments on commit f0e62ae

Please sign in to comment.