store go.mod and go.sum in git. thank you most excellent git devs

This commit is contained in:
Jeff Carr 2024-12-13 12:34:47 -06:00
parent dbbc35dd24
commit 86f06c8419
2 changed files with 8 additions and 66 deletions

View File

@ -7,6 +7,7 @@ needs to be done sometimes.
* go-mod-clean tries to remove uneeded entries from the go.sum file.
* You must run go-mod-clean in ~/go/src for this to work.
* stores go.mod and go.sum with `autogen:go.mod` tags in 'git notes'
# Install go-mod-clean

73
main.go
View File

@ -2,9 +2,7 @@ package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"go.wit.com/dev/alexflint/arg"
@ -43,8 +41,11 @@ func main() {
// skip restore if --force
if !argv.Force {
// try to restore from the git metadata
if restoreFromGit(check) {
okExit("go.mod was restored from the git notes")
if err := check.AutogenRestore(); err != nil {
badExit(err)
}
if err := check.ValidGoSum(); err == nil {
okExit("go.mod and go.sum were restored ok")
}
}
@ -118,76 +119,16 @@ func badExit(err error) {
os.Exit(-1)
}
// todo: do this the right way in git
func saveAsMetadata(repo *gitpb.Repo) error {
cname := check.GetCurrentBranchName()
cmd := []string{"git", "notes", "remove", cname}
if err := check.StrictRun(cmd); err != nil {
return err
}
cmd = []string{"git", "notes", "add", "-m", "// `autogen:go.mod`", cname}
if err := check.StrictRun(cmd); err != nil {
return err
}
if check.GoPrimitive {
cmd = []string{"git", "notes", "append", "-F", "go.mod", cname}
if err := check.StrictRun(cmd); err != nil {
if err := check.AutogenSave([]string{"go.mod"}, cname, true); err != nil {
return err
}
} else {
cmd = []string{"git", "notes", "append", "-F", "go.mod", cname}
if err := check.StrictRun(cmd); err != nil {
return err
}
cmd = []string{"git", "notes", "append", "-m", "// `autogen:go.sum`", cname}
if err := check.StrictRun(cmd); err != nil {
return err
}
cmd = []string{"git", "notes", "append", "-F", "go.sum", cname}
if err := check.StrictRun(cmd); err != nil {
if err := check.AutogenSave([]string{"go.mod", "go.sum"}, cname, true); err != nil {
return err
}
}
return nil
}
func restoreFromGit(repo *gitpb.Repo) bool {
result := repo.Run([]string{"git", "notes", "show"})
if result.Exit != 0 {
return false
}
if result.Error != nil {
return false
}
if len(result.Stdout) == 0 {
return false
}
var newf *os.File
var body string
for _, line := range result.Stdout {
if strings.HasPrefix(line, "// `autogen:") {
if newf != nil {
fmt.Fprintln(newf, strings.TrimSpace(body))
newf.Close()
newf = nil
body = ""
}
fbase := strings.TrimPrefix(line, "// `autogen:")
fbase = strings.TrimSpace(fbase)
fbase = strings.TrimSuffix(fbase, "`")
// if line == // `autogen:` , then the filename is blank
if fbase != "" {
fname := filepath.Join(filepath.Join(check.FullPath, fbase))
newf, _ = os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
}
continue
}
body += line + "\n"
}
if newf != nil {
fmt.Fprintln(newf, strings.TrimSpace(body))
newf.Close()
}
return true
}