summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJeff Carr <[email protected]>2024-11-24 06:20:30 -0600
committerJeff Carr <[email protected]>2024-11-24 06:20:30 -0600
commit84d04f28c962722adec33ca9fc230a74fe3081f5 (patch)
treef5d71215dce0022fd85828e6f43a43bc596dd490
parent7025f6b7e5d5014649d09e35cfcfc770d748aef7 (diff)
common code to determin go/srcv0.0.5
-rw-r--r--goSrc.go66
1 files changed, 66 insertions, 0 deletions
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")
+}