go-mod-clean/redoGoMod.go

88 lines
2.4 KiB
Go

package main
// recreates the go.mod and go.sum files
import (
"errors"
"os"
"go.wit.com/lib/protobuf/gitpb"
"go.wit.com/log"
)
// remove every go.mod and go.sum
// testing to see where this stuff is coming from
func eraseGoMod(repo *gitpb.Repo) {
// unset the go development ENV var to generate release files
if err := repo.StrictRun([]string{"rm", "-f", "go.mod", "go.sum"}); err != nil {
log.Warn(repo.GoPath, "rm go.mod go.sum failed", err)
}
}
// sets the required golang version in go.mod
func setGoVersion(repo *gitpb.Repo, version string) error {
// most things should build with golang after 1.21
if err := repo.StrictRun([]string{"go", "mod", "edit", "-go=" + version}); err != nil {
log.Warn(repo.GoPath, "go mod edit failed", err)
return err
}
return nil
}
// wrapper around 'go mod init' and 'go mod tidy'
func redoGoMod(repo *gitpb.Repo) error {
// unset the go development ENV var to generate release files
os.Unsetenv("GO111MODULE")
if err := repo.StrictRun([]string{"rm", "-f", "go.mod", "go.sum"}); err != nil {
log.Warn("rm go.mod go.sum failed", err)
return err
}
if err := repo.StrictRun([]string{"go", "mod", "init", repo.GoPath}); err != nil {
log.Warn("go mod init failed", err)
return err
}
if err := repo.StrictRun([]string{"go", "mod", "tidy", "-go=1.21"}); err != nil {
log.Warn("go mod tidy failed", err)
return err
}
// most things should build with golang after 1.21 // todo: allow this to be set somewhere
if err := setGoVersion(repo, "1.21"); err != nil {
log.Warn(repo.GoPath, "go mod edit failed", err)
return err
}
repo.GoDeps = nil
repo.GoPrimitive = false
// if there is not a go.sum file, it better be a primitive golang project
if !repo.Exists("go.sum") {
// todo. fix this logic
ok, err := repo.IsPrimitive()
if err != nil {
// this means this repo does not depend on any other package
log.Info("PRIMATIVE repo error:", repo.GoPath, "err =", err)
return err
}
if ok {
// this means the repo is primitive so there is no go.sum
repo.GoPrimitive = true
repo.GoDeps = new(gitpb.GoDeps)
return nil
}
}
if !repo.Exists("go.sum") {
// this should never happen
data, _ := repo.ReadFile("go.mod")
log.Info(string(data))
return errors.New("missing go.sum file on non-primitive go.mod")
}
repo.GoDeps = new(gitpb.GoDeps)
// return the attempt to parse go.sum
_, err := repo.ParseGoSum()
return err
}