-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.go
More file actions
41 lines (31 loc) · 781 Bytes
/
module.go
File metadata and controls
41 lines (31 loc) · 781 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package program
import (
"errors"
"fmt"
"io/fs"
"os"
"path"
"runtime"
)
func ModuleDirectoryPath() (string, error) {
const refFilePath = "go.mod"
// Skip one call frame, i.e. the one associated with this very function,
// since we want to locate the module of the calling function.
_, filePath, _, _ := runtime.Caller(1)
dirPath := path.Dir(filePath)
for dirPath != "/" {
dirPath = path.Join(dirPath, "..")
filePath := path.Join(dirPath, refFilePath)
_, err := os.Stat(filePath)
if errors.Is(err, fs.ErrNotExist) {
continue
} else if err != nil {
return "", fmt.Errorf("cannot stat %q: %v", filePath, err)
}
break
}
if dirPath == "/" {
return "", fmt.Errorf("%q not found in parent directories", refFilePath)
}
return dirPath, nil
}