From f2ddc28884bebb5ba08a7df14dc99a77ba43e03c Mon Sep 17 00:00:00 2001 From: oabrivard Date: Fri, 12 Apr 2024 10:12:30 +0200 Subject: [PATCH] Added Project base path retrieval --- file/file.go | 18 ++++++++++++++++++ file/file_test.go | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/file/file.go b/file/file.go index c0263a2..3dbaddb 100644 --- a/file/file.go +++ b/file/file.go @@ -1,6 +1,7 @@ package file import ( + "os" "path/filepath" "runtime" ) @@ -11,3 +12,20 @@ var ( // Root folder of this project 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 +} diff --git a/file/file_test.go b/file/file_test.go index 582d683..bb6d84a 100644 --- a/file/file_test.go +++ b/file/file_test.go @@ -10,3 +10,10 @@ func TestProjectRoot(t *testing.T) { 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) + } +}