github.com/go-goxm/goxm@v0.4.4/utils.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "context" 6 "encoding/json" 7 "fmt" 8 "io" 9 "os" 10 "os/exec" 11 "path/filepath" 12 "strconv" 13 "strings" 14 "time" 15 16 "golang.org/x/mod/modfile" 17 ) 18 19 type Info struct { 20 Version string // version string 21 Time time.Time // commit time 22 } 23 24 func logf(format string, args ...any) { 25 if !strings.HasSuffix(format, "\n") { 26 format += "\n" 27 } 28 fmt.Fprintf(os.Stderr, "GOXM: "+format, args...) 29 } 30 31 func getGoInfoFromGit(ctx context.Context, version string) ([]byte, string, error) { 32 33 gitRootPath, err := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel").Output() 34 if err != nil { 35 return nil, "", fmt.Errorf("Current directory is not in a Git repository: %w", err) 36 } 37 38 gitCommitTime, err := exec.CommandContext(ctx, "git", "log", "--max-count=1", "--format=%ct", version).Output() 39 if err != nil { 40 return nil, "", fmt.Errorf("Git revision not found: %s: %w", version, err) 41 } 42 43 gitCommitTimeInt64, err := strconv.ParseInt(string(bytes.TrimSpace(gitCommitTime)), 0, 64) 44 if err != nil { 45 return nil, "", fmt.Errorf("%w", err) 46 } 47 48 gitVersionInfo := Info{ 49 Version: version, 50 Time: time.Unix(gitCommitTimeInt64, 0).UTC(), 51 } 52 53 gitVersionInfoJSON, err := json.MarshalIndent(gitVersionInfo, "", " ") 54 if err != nil { 55 return nil, "", err 56 } 57 58 return gitVersionInfoJSON, string(bytes.TrimSpace(gitRootPath)), nil 59 } 60 61 func getGoModule(ctx context.Context) (string, []byte, string, error) { 62 63 cwd, err := os.Getwd() 64 if err != nil { 65 return "", nil, "", err 66 } 67 68 goModFilePath := filepath.Join(cwd, "go.mod") 69 goModFile, err := os.Open(goModFilePath) 70 if err != nil { 71 return "", nil, "", fmt.Errorf("Current directory does not contain a Go module file (go.mod)") 72 } 73 defer goModFile.Close() 74 75 goModData, err := io.ReadAll(goModFile) 76 if err != nil { 77 return "", nil, "", fmt.Errorf("Go module file (go.mod) could not be read") 78 } 79 80 goMod, err := modfile.ParseLax(goModFilePath, goModData, nil) 81 if err != nil { 82 return "", nil, "", fmt.Errorf("Go module file (go.mod) could not be parsed") 83 } 84 85 goModName := goMod.Module.Mod.Path 86 if goModName == "" { 87 return "", nil, "", fmt.Errorf("Go module name not found") 88 } 89 90 return goModName, goModData, goModFilePath, nil 91 }