forgepb/goSrcFind.go

87 lines
2.3 KiB
Go
Raw Permalink Normal View History

2024-11-24 06:20:30 -06:00
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/log"
)
// look for a go.work file
// otherwise use ~/go/src
2024-12-01 22:23:02 -06:00
func (f *Forge) findGoSrc() (string, error) {
2024-11-24 06:20:30 -06:00
pwd, err := os.Getwd()
// startpwd, _ := os.Getwd()
2024-11-24 06:20:30 -06:00
if err == nil {
// Check for go.work in the current directory and then move up until root
if pwd, err := digup(pwd); err == nil {
2024-12-01 22:23:02 -06:00
f.goWork = true
2024-11-24 06:20:30 -06:00
// found an existing go.work file
2024-11-30 12:45:07 -06:00
// os.Chdir(pwd)
2024-11-24 06:20:30 -06:00
return pwd, nil
2024-12-07 16:50:04 -06:00
} else {
// if there is an error looking for the go.work file
// default to using ~/go/src
// log.Info("forge.digup() err", pwd, err)
2024-11-24 06:20:30 -06:00
}
2024-12-07 16:50:04 -06:00
} else {
// this shouldn't really happen. maybe your working directory got deleted
log.Info("forge.findGoSrc() os.Getwd() was probably deleted", pwd, err)
2024-11-24 06:20:30 -06:00
}
// there are no go.work files, resume the ~/go/src behavior from prior to golang 1.22
pwd, err = useGoSrc()
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")
err = os.MkdirAll(pwd, os.ModePerm)
return pwd, err
2024-11-24 06:20:30 -06:00
}
2024-12-10 01:48:29 -06:00
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)
2024-12-10 01:48:29 -06:00
return true
} else if !os.IsNotExist(err) {
// log.Info("f.goWorkExists() missing", workFilePath)
2024-12-10 01:48:29 -06:00
return false
}
// probably false, but some other error
// log.Info("f.goWorkExists() os.Stat() error", err, workFilePath)
2024-12-10 01:48:29 -06:00
return false
}
2024-11-24 06:20:30 -06:00
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")
}