common code to determin go/src

This commit is contained in:
Jeff Carr 2024-11-24 06:20:30 -06:00
parent 7025f6b7e5
commit 84d04f28c9
1 changed files with 66 additions and 0 deletions

66
goSrc.go Normal file
View File

@ -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")
}