anical/internal/debug/debug.go

66 lines
1.6 KiB
Go

package debug
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"strings"
)
func git(dir string, args ...string) (string, error) {
out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).Output()
return strings.TrimSpace(string(out)), err
}
// findRepo checks the current directory, then its immediate subdirectories.
func findRepo() (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
candidates := []string{cwd, filepath.Dir(cwd)}
entries, _ := os.ReadDir(cwd)
for _, e := range entries {
if e.IsDir() {
candidates = append(candidates, filepath.Join(cwd, e.Name()))
}
}
for _, dir := range candidates {
if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil {
return dir, nil
}
}
return "", fmt.Errorf("no git repo in %s, its parent, or its immediate subfolders", cwd)
}
func GetInfo() {
// Build info embedded at compile time
if bi, ok := debug.ReadBuildInfo(); ok {
fmt.Println("Go version:", bi.GoVersion)
fmt.Println("Module: ", bi.Main.Path, bi.Main.Version)
for _, s := range bi.Settings {
switch s.Key {
case "vcs", "vcs.revision", "vcs.time", "vcs.modified",
"GOOS", "GOARCH", "CGO_ENABLED", "-trimpath", "-compiler":
fmt.Printf("%-12s %s\n", s.Key+":", s.Value)
}
}
}
// Git state of the repo found at runtime
repo, err := findRepo()
if err != nil {
fmt.Println("Git:", err)
return
}
root, _ := git(repo, "rev-parse", "--show-toplevel")
commit, err := git(repo, "rev-parse", "HEAD")
if err != nil {
fmt.Println("Git error:", err)
return
}
fmt.Println("Repo root:", root)
fmt.Println("Commit: ", commit)
}