diff --git a/cmd/go-cli-github/main.go b/cmd/go-cli-github/main.go index b6b0012..180d9f9 100644 --- a/cmd/go-cli-github/main.go +++ b/cmd/go-cli-github/main.go @@ -12,19 +12,26 @@ import ( // CLI represents the command-line interface. type CLI struct { - Version VersionCmd `kong:"cmd,help='Print version information'"` - Serve ServeCmd `kong:"cmd,default=1,help='(default) Example serve command'"` + Version kong.VersionFlag `kong:"help='Print version information'"` + Serve ServeCmd `kong:"cmd,default=1,help='(default) Example serve command'"` } func main() { ctx, stop := signal.NotifyContext( context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() + verJSON, err := formatVersionJSON() + if err != nil { + panic(err) + } // parse CLI config cli := CLI{} kctx := kong.Parse(&cli, kong.UsageOnError(), kong.BindFor(ctx), + kong.Vars{ + "version": verJSON, + }, ) // execute CLI kctx.FatalIfErrorf(kctx.Run()) diff --git a/cmd/go-cli-github/version.go b/cmd/go-cli-github/version.go index 8b42cc6..aa6a493 100644 --- a/cmd/go-cli-github/version.go +++ b/cmd/go-cli-github/version.go @@ -1,9 +1,7 @@ package main import ( - "context" - "encoding/json" - "fmt" + "encoding/json/v2" "runtime" ) @@ -15,11 +13,8 @@ var ( version string ) -// VersionCmd represents the `version` command. -type VersionCmd struct{} - -// Run the Version command. -func (*VersionCmd) Run(ctx context.Context) error { +// formatVersionJSON formats version information as a JSON string. +func formatVersionJSON() (string, error) { v, err := json.Marshal( struct { ProjectName string @@ -35,8 +30,7 @@ func (*VersionCmd) Run(ctx context.Context) error { runtime.Version(), }) if err != nil { - return err + return "", err } - _, err = fmt.Println(string(v)) - return err + return string(v), nil } diff --git a/go.mod b/go.mod index ff917e7..11b1e09 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/smlx/go-cli-github -go 1.22.2 +go 1.27 require ( github.com/alecthomas/assert/v2 v2.11.0