|
1 | 1 | package util |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "log" |
4 | 5 | "os" |
5 | 6 | "path" |
6 | 7 | "path/filepath" |
7 | 8 | "runtime" |
8 | 9 | "strings" |
9 | 10 | ) |
10 | 11 |
|
11 | | -func GetCurrentAbsPath() string { |
12 | | - // 最终方案-全兼容 |
13 | | - dir := getCurrentAbPathByExecutable() |
| 12 | +func GetCurrentAbsPath() (string, bool) { |
| 13 | + // Work in dev and prod runtime |
| 14 | + isDebug := false |
| 15 | + absDir := getCurrentAbsPathByExecutable() |
14 | 16 | tmpDir, _ := filepath.EvalSymlinks(os.TempDir()) |
15 | | - // 如果是临时目录或者是goland运行的目录,那么就用caller的方式获取 |
16 | | - if strings.Contains(dir, tmpDir) || strings.Contains(dir, "GoLand") { |
17 | | - return getCurrentAbPathByCaller() |
| 17 | + // If it is a temporary directory or the directory contains 'GoLand' keyword, |
| 18 | + // then retrieve it using the `caller` method. |
| 19 | + if strings.Contains(absDir, tmpDir) || strings.Contains(absDir, "GoLand") { |
| 20 | + isDebug = true |
| 21 | + return getCurrentAbsPathByCaller(), isDebug |
18 | 22 | } |
19 | | - return dir |
| 23 | + return absDir, isDebug |
20 | 24 | } |
21 | 25 |
|
22 | 26 | func GetWorkdir() string { |
23 | | - currentAbsPath := GetCurrentAbsPath() |
24 | | - workDir := filepath.Join(currentAbsPath, "..") |
| 27 | + workDir, isDebug := GetCurrentAbsPath() |
| 28 | + if isDebug { |
| 29 | + workDir = filepath.Join(workDir, "..") |
| 30 | + } |
25 | 31 | return workDir |
26 | 32 | } |
27 | 33 |
|
28 | | -// 获取当前执行文件绝对路径 |
29 | | -func getCurrentAbPathByExecutable() string { |
| 34 | +// getCurrentAbsPathByExecutable Retrieve the absolute path to the currently executing file. |
| 35 | +func getCurrentAbsPathByExecutable() string { |
30 | 36 | exePath, err := os.Executable() |
| 37 | + log.Printf("executable path: %s", exePath) |
31 | 38 | if err != nil { |
32 | 39 | panic(err) |
33 | 40 | } |
34 | | - res, _ := filepath.EvalSymlinks(filepath.Dir(exePath)) |
35 | | - return res |
| 41 | + res, _ := filepath.EvalSymlinks(exePath) |
| 42 | + return path.Dir(res) |
36 | 43 | } |
37 | 44 |
|
38 | | -// 获取当前执行文件绝对路径(go run) |
39 | | -func getCurrentAbPathByCaller() string { |
| 45 | +// getCurrentAbsPathByCaller Retrieve the absolute path to the currently executing file.(by `go run`) |
| 46 | +func getCurrentAbsPathByCaller() string { |
40 | 47 | var abPath string |
41 | 48 | _, filename, _, ok := runtime.Caller(0) |
42 | 49 | if ok { |
|
0 commit comments