Skip to content

Commit

Permalink
feat: Add a --version flag to keep-sorted. (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffFaer authored Dec 16, 2024
1 parent cfd64db commit 65bfea4
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"fmt"
"os"
"path"
"runtime/debug"
"time"

"github.com/google/keep-sorted/cmd"
Expand All @@ -34,6 +35,7 @@ func main() {
logLevel := flag.CountP("verbose", "v", "Log more verbosely")
colorMode := flag.String("color", "auto", "Whether to color debug output. One of \"always\", \"never\", or \"auto\"")
omitTimestamps := flag.Bool("omit-timestamps", false, "Do not emit timestamps in console logging. Useful for tests")
version := flag.Bool("version", false, "Report the keep-sorted version.")
if err := flag.CommandLine.MarkHidden("omit-timestamps"); err != nil {
panic(err)
}
Expand All @@ -48,6 +50,11 @@ func main() {

flag.Parse()

if *version {
fmt.Fprintln(os.Stdout, readVersion())
return
}

out := os.Stderr
var shouldColor bool
switch *colorMode {
Expand All @@ -72,3 +79,43 @@ func main() {
os.Exit(1)
}
}

func readVersion() string {
bi, ok := debug.ReadBuildInfo()
if !ok {
return "unknown"
}

const revisionKey = "vcs.revision"
const timeKey = "vcs.time"
const dirtyKey = "vcs.modified"
settings := make(map[string]string)
for _, s := range bi.Settings {
settings[s.Key] = s.Value
}

var s string
if v := bi.Main.Version; v != "" && v != "(devel)" {
s = v
} else if r := settings[revisionKey]; r != "" {
s = r
if len(s) > 7 {
s = s[:7]
}
}

if s == "" {
return "unknown"
}

if settings[dirtyKey] == "true" {
s += "-dev"
}
if t := settings[timeKey]; t != "" {
if ts, err := time.Parse(time.RFC3339, t); err == nil {
t = ts.In(time.Local).Format(time.RFC3339)
}
s += fmt.Sprintf(" (%s)", t)
}
return s
}

0 comments on commit 65bfea4

Please sign in to comment.