|
1 | 1 | package project_root_directory |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + how_run "github.com/golang-infrastructure/go-how-run" |
4 | 5 | "os" |
5 | 6 | "path/filepath" |
6 | 7 | ) |
7 | 8 |
|
8 | | -func Get() string { |
9 | | - return "" |
10 | | -} |
11 | | - |
12 | | -type RunType int |
13 | | - |
14 | | -const ( |
15 | | - RunTypeUintTest RunType = iota |
16 | | - RunTypeRelease |
17 | | -) |
18 | | - |
19 | | -func judgeCurrentRunType() { |
20 | | - |
| 9 | +// GetRootDirectory 获取当前项目的根路径在哪里 |
| 10 | +func GetRootDirectory() (string, error) { |
| 11 | + runType, err := how_run.GetRunType() |
| 12 | + if err != nil { |
| 13 | + return "", err |
| 14 | + } |
| 15 | + switch runType { |
| 16 | + // RunTypeSourceUnknown 咱也不知道咋运行的 |
| 17 | + case how_run.RunTypeUnknown: |
| 18 | + return "", ErrProjectRootDirectoryUnknown |
| 19 | + // RunTypeSourceCode 是从源代码中运行的 |
| 20 | + case how_run.RunTypeSourceCode: |
| 21 | + return GetSourceCodeRootDirectory() |
| 22 | + // RunTypeReleaseBinary 发布的二进制文件运行 |
| 23 | + case how_run.RunTypeReleaseBinary: |
| 24 | + return GetExecutableRootDirectory() |
| 25 | + default: |
| 26 | + return "", ErrProjectRootDirectoryUnknown |
| 27 | + } |
21 | 28 | } |
22 | 29 |
|
23 | | -// 获取可执行文件的路径 |
24 | | -func getExecutable() string { |
25 | | - ex, err := os.Executable() |
| 30 | +func GetSourceCodeRootDirectory() (string, error) { |
| 31 | + searchDirectory, err := os.Getwd() |
26 | 32 | if err != nil { |
27 | | - return "" |
| 33 | + return "", err |
28 | 34 | } |
29 | | - exPath := filepath.Dir(ex) |
30 | | - realPath, err := filepath.EvalSymlinks(exPath) |
31 | | - if err != nil { |
32 | | - return "" |
| 35 | + // 从当前路径往上找,第一个拥有go.mod文件的目录认为是项目的根路径 |
| 36 | + for searchDirectory != "" { |
| 37 | + goModPath := filepath.Join(searchDirectory, "go.mod") |
| 38 | + stat, err := os.Stat(goModPath) |
| 39 | + if err == nil && stat != nil && !stat.IsDir() { |
| 40 | + return searchDirectory, nil |
| 41 | + } |
| 42 | + searchDirectory = filepath.Dir(searchDirectory) |
33 | 43 | } |
34 | | - return realPath |
35 | | - //return filepath.Dir(realPath) |
| 44 | + return "", ErrProjectRootDirectoryUnknown |
36 | 45 | } |
37 | 46 |
|
38 | | -// 源代码测试 |
39 | | - |
40 | | -// 源代码Example |
41 | | - |
42 | | -// 源代码基准测试 |
43 | | - |
44 | | -// 源代码main方法运行 |
45 | | - |
46 | | -// 编译后的执行 |
| 47 | +// GetExecutableRootDirectory 获取可执行文件的root路径 |
| 48 | +func GetExecutableRootDirectory() (string, error) { |
| 49 | + // 对于可执行文件而言,其所在的路径就是项目的根目录 |
| 50 | + return os.Getwd() |
| 51 | +} |
0 commit comments