Added Project base path retrieval

main
oabrivard 2 years ago
parent 671c3d2b17
commit f2ddc28884

@ -1,6 +1,7 @@
package file package file
import ( import (
"os"
"path/filepath" "path/filepath"
"runtime" "runtime"
) )
@ -11,3 +12,20 @@ var (
// Root folder of this project // Root folder of this project
ProjectRoot = filepath.Join(filepath.Dir(b), "..") ProjectRoot = filepath.Join(filepath.Dir(b), "..")
) )
// GetBasePath returns the root folder of the project
func GetBasePath() string {
dir, err := os.Getwd()
if err != nil {
panic(err)
}
for _, err := os.ReadFile(filepath.Join(dir, "go.mod")); err != nil && len(dir) > 1; {
println(dir)
dir = filepath.Dir(dir)
_, err = os.ReadFile(filepath.Join(dir, "go.mod"))
}
if len(dir) < 2 {
panic("No go.mod found")
}
return dir
}

@ -10,3 +10,10 @@ func TestProjectRoot(t *testing.T) {
t.Errorf("ProjectRoot is not correct: %s", ProjectRoot) t.Errorf("ProjectRoot is not correct: %s", ProjectRoot)
} }
} }
func TestGetBasePath(t *testing.T) {
basePath := GetBasePath()
if !strings.Contains(basePath, "abrolgo") {
t.Errorf("GetBasePath is not correct: %s", basePath)
}
}

Loading…
Cancel
Save