forgepb/goSrcFind.go

92 lines
2.5 KiB
Go

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 (f *Forge) findGoSrc() (string, error) {
pwd, err := os.Getwd()
startpwd, _ := os.Getwd()
if err == nil {
log.Info("forge.findGoSrc() trying digup", pwd, err)
// Check for go.work in the current directory and then move up until root
if pwd, err := digup(pwd); err == nil {
log.Info("forge.findGoSrc() using go.work file in directory", pwd)
f.goWork = true
// found an existing go.work file
// os.Chdir(pwd)
return pwd, nil
} else {
log.Info("forge.digup() err", pwd, err)
}
} else {
log.Info("forge.findGoSrc() os.Getwd()", pwd, err)
}
// there are no go.work files, resume the ~/go/src behavior from prior to golang 1.22
pwd, err = useGoSrc()
log.Info("forge.findGoSrc() 2 using ~/go/src directory", pwd, "start was", startpwd)
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 (f *Forge) goWorkExists() bool {
var err error
workFilePath := filepath.Join(f.GetGoSrc(), "go.work")
if _, err = os.Stat(workFilePath); err == nil {
log.Info("f.goWorkExists() found", workFilePath)
return true
} else if !os.IsNotExist(err) {
log.Info("f.goWorkExists() missing", workFilePath)
return false
}
// probably false, but some other error
log.Info("f.goWorkExists() os.Stat() error", err, workFilePath)
return false
}
func digup(path string) (string, error) {
for {
workFilePath := filepath.Join(path, "go.work")
log.Info("digup trying", workFilePath)
if _, err := os.Stat(workFilePath); err == nil {
log.Info("digup found", path)
return path, nil // Found the go.work file
} else if !os.IsNotExist(err) {
log.Info("forgepb.digup() failed", workFilePath, 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")
}