From 84d04f28c962722adec33ca9fc230a74fe3081f5 Mon Sep 17 00:00:00 2001 From: Jeff Carr Date: Sun, 24 Nov 2024 06:20:30 -0600 Subject: [PATCH] common code to determin go/src --- goSrc.go | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 goSrc.go diff --git a/goSrc.go b/goSrc.go new file mode 100644 index 0000000..b4ee277 --- /dev/null +++ b/goSrc.go @@ -0,0 +1,66 @@ +package forgepb + +// returns whatever your golang source dir is +// If there is a go.work file in your parent, that directory will be returned +// otherwise, return ~/go/src + +import ( + "fmt" + "os" + "path/filepath" + + "go.wit.com/lib/gui/shell" + "go.wit.com/log" +) + +// look for a go.work file +// otherwise use ~/go/src +func FindGoSrc() (string, error) { + pwd, err := os.Getwd() + if err == nil { + // Check for go.work in the current directory and then move up until root + if pwd, err := digup(pwd); err == nil { + log.Info("using go.work file in directory", pwd) + // found an existing go.work file + os.Chdir(pwd) + return pwd, nil + } + } + + // there are no go.work files, resume the ~/go/src behavior from prior to golang 1.22 + pwd, err = useGoSrc() + log.Info("using ~/go/src directory", pwd) + return pwd, err +} + +// this is the 'old way" and works fine for me. I use it because I like the ~/go/src directory +// because I know exactly what is in it: GO stuff & nothing else +func useGoSrc() (string, error) { + homeDir, err := os.UserHomeDir() + if err != nil { + return "", err + } + pwd := filepath.Join(homeDir, "go/src") + shell.Mkdir(pwd) + os.Chdir(pwd) + return pwd, nil +} + +func digup(path string) (string, error) { + for { + workFilePath := filepath.Join(path, "go.work") + if _, err := os.Stat(workFilePath); err == nil { + return path, nil // Found the go.work file + } else if !os.IsNotExist(err) { + return "", err // An error other than not existing + } + + parentPath := filepath.Dir(path) + if parentPath == path { + break // Reached the filesystem root + } + path = parentPath + } + + return "", fmt.Errorf("no go.work file found") +}