Skip to content

Commit b467546

Browse files
committed
added function to find parent directory with go.mod.
1 parent 774e987 commit b467546

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

ditto.go

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,12 @@ func getCacheFilePath(req *http.Request) string {
9797
endpointPlusMethod := fmt.Sprintf("%s:%s", method, url)
9898
hash.Write([]byte(endpointPlusMethod))
9999
hashedEndpoint := fmt.Sprintf("%x", hash.Sum(nil))
100-
return filepath.Join(".ditto", hashedEndpoint)
100+
101+
goModDir, err := findGoModDir()
102+
if err != nil {
103+
panic(err)
104+
}
105+
return filepath.Join(goModDir, ".ditto", hashedEndpoint)
101106
}
102107

103108
func retrieve(req *http.Request) ([]byte, error) {
@@ -113,3 +118,27 @@ func cache(req *http.Request, data []byte) error {
113118
os.MkdirAll(filepath.Dir(cacheFilePath), os.ModePerm)
114119
return os.WriteFile(cacheFilePath, data, 0644)
115120
}
121+
122+
func findGoModDir() (string, error) {
123+
path, err := os.Getwd()
124+
if err != nil {
125+
return "", err
126+
}
127+
128+
home, err := os.UserHomeDir()
129+
if err != nil {
130+
return "", err
131+
}
132+
133+
for {
134+
if path == home || path == "//" {
135+
return "", nil
136+
}
137+
138+
if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil {
139+
return path, nil
140+
}
141+
142+
path = filepath.Dir(path)
143+
}
144+
}

ditto_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,9 @@ func TestCachingTransport_RoundTrip(t *testing.T) {
5151

5252
// TODO: Add more assertions as needed
5353
}
54+
func TestFindGoModDir(t *testing.T) {
55+
_, err := findGoModDir()
56+
if err != nil {
57+
t.Fatal(err)
58+
}
59+
}

0 commit comments

Comments
 (0)