Skip to content

Commit

Permalink
added function to find parent directory with go.mod.
Browse files Browse the repository at this point in the history
  • Loading branch information
TimothyStiles committed Jan 12, 2024
1 parent 774e987 commit b467546
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
31 changes: 30 additions & 1 deletion ditto.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@ func getCacheFilePath(req *http.Request) string {
endpointPlusMethod := fmt.Sprintf("%s:%s", method, url)
hash.Write([]byte(endpointPlusMethod))
hashedEndpoint := fmt.Sprintf("%x", hash.Sum(nil))
return filepath.Join(".ditto", hashedEndpoint)

goModDir, err := findGoModDir()
if err != nil {
panic(err)
}
return filepath.Join(goModDir, ".ditto", hashedEndpoint)
}

func retrieve(req *http.Request) ([]byte, error) {
Expand All @@ -113,3 +118,27 @@ func cache(req *http.Request, data []byte) error {
os.MkdirAll(filepath.Dir(cacheFilePath), os.ModePerm)
return os.WriteFile(cacheFilePath, data, 0644)
}

func findGoModDir() (string, error) {
path, err := os.Getwd()
if err != nil {
return "", err
}

home, err := os.UserHomeDir()
if err != nil {
return "", err
}

for {
if path == home || path == "//" {
return "", nil
}

if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil {
return path, nil
}

path = filepath.Dir(path)
}
}
6 changes: 6 additions & 0 deletions ditto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,9 @@ func TestCachingTransport_RoundTrip(t *testing.T) {

// TODO: Add more assertions as needed
}
func TestFindGoModDir(t *testing.T) {
_, err := findGoModDir()
if err != nil {
t.Fatal(err)
}
}

0 comments on commit b467546

Please sign in to comment.