Skip to content

Commit f13961a

Browse files
committed
feat: added GetExecutableGoModPath helper function
1 parent c228392 commit f13961a

File tree

2 files changed

+59
-21
lines changed

2 files changed

+59
-21
lines changed

filesystem/utils.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package filesystem
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"path/filepath"
7+
)
8+
9+
// GetCurrentDirectory gets the current directory of the executable
10+
//
11+
// Returns:
12+
//
13+
// - string: the current directory path
14+
// - error: error if any occurred while retrieving the directory
15+
func GetCurrentDirectory() (string, error) {
16+
execPath, err := os.Executable()
17+
if err != nil {
18+
return "", err
19+
}
20+
21+
return filepath.Dir(execPath), nil
22+
}
23+
24+
25+
// GetExecutableGoModPath get the path of the go.mod file relative to the executable (searching upwards in the directory tree)
26+
//
27+
// Returns:
28+
//
29+
// - string: The path to the go.mod file
30+
// - error: The error if any
31+
func GetExecutableGoModPath() (string, error) {
32+
ex, err := os.Executable()
33+
if err != nil {
34+
return "", fmt.Errorf("could not get executable path: %w", err)
35+
}
36+
37+
// Start the search from the executable's directory
38+
dir := filepath.Dir(ex)
39+
40+
// Loop up the directory tree to find go.mod
41+
for {
42+
// Construct the potential go.mod path
43+
goModPath := filepath.Join(dir, "go.mod")
44+
45+
// Check if go.mod exists at this location
46+
if _, err := os.Stat(goModPath); err == nil {
47+
return goModPath, nil // Found the file!
48+
}
49+
50+
// Move up one level
51+
parentDir := filepath.Dir(dir)
52+
53+
// Stop if we hit the filesystem root (no more parent directories)
54+
if parentDir == dir {
55+
return "", fmt.Errorf("go.mod not found in any parent directory relative to executable: %s", ex)
56+
}
57+
dir = parentDir
58+
}
59+
}

filesystem/working_directory.go

Lines changed: 0 additions & 21 deletions
This file was deleted.

0 commit comments

Comments
 (0)