move code to kvm package

This commit is contained in:
Siyuan Miao 2025-05-20 15:06:27 +02:00
parent 12dbe6fcf0
commit 9bde820321
4 changed files with 70 additions and 15 deletions

View File

@ -22,6 +22,9 @@ linters:
- linters:
- errcheck
path: _test.go
- linters:
- forbidigo
path: cmd/main.go
paths:
- third_party$
- builtin$

View File

@ -3,28 +3,23 @@ package main
import (
"flag"
"fmt"
"os"
"github.com/jetkvm/kvm"
"github.com/prometheus/common/version"
)
func printVersion() {
version.Version = kvm.GetBuiltAppVersion()
app_version := version.Print("JetKVM Application")
fmt.Println(app_version)
nativeVersion, err := kvm.GetNativeVersion()
if err == nil {
fmt.Println("\nJetKVM Native, version", nativeVersion)
}
}
func main() {
versionPtr := flag.Bool("version", false, "print version and exit")
versionJsonPtr := flag.Bool("version-json", false, "print version as json and exit")
flag.Parse()
if *versionPtr {
printVersion()
if *versionPtr || *versionJsonPtr {
versionData, err := kvm.GetVersionData(*versionJsonPtr)
if err != nil {
fmt.Printf("failed to get version data: %v\n", err)
os.Exit(1)
}
fmt.Println(string(versionData))
return
}

View File

@ -8,6 +8,7 @@ import (
"io"
"net"
"os"
"strings"
"sync"
"time"
@ -295,7 +296,7 @@ func GetNativeVersion() (string, error) {
if err != nil {
return "", err
}
return string(version), nil
return strings.TrimSpace(string(version)), nil
}
func ensureBinaryUpdated(destPath string) error {

56
version.go Normal file
View File

@ -0,0 +1,56 @@
package kvm
import (
"bytes"
"encoding/json"
"html/template"
"runtime"
"github.com/prometheus/common/version"
)
var versionInfoTmpl = `
JetKVM Application, version {{.version}} (branch: {{.branch}}, revision: {{.revision}})
build date: {{.buildDate}}
go version: {{.goVersion}}
platform: {{.platform}}
{{if .nativeVersion}}
JetKVM Native, version {{.nativeVersion}}
{{end}}
`
func GetVersionData(isJson bool) ([]byte, error) {
version.Version = GetBuiltAppVersion()
m := map[string]string{
"version": version.Version,
"revision": version.GetRevision(),
"branch": version.Branch,
"buildDate": version.BuildDate,
"goVersion": version.GoVersion,
"platform": runtime.GOOS + "/" + runtime.GOARCH,
}
nativeVersion, err := GetNativeVersion()
if err == nil {
m["nativeVersion"] = nativeVersion
}
if isJson {
jsonData, err := json.Marshal(m)
if err != nil {
return nil, err
}
return jsonData, nil
}
t := template.Must(template.New("version").Parse(versionInfoTmpl))
var buf bytes.Buffer
if err := t.ExecuteTemplate(&buf, "version", m); err != nil {
return nil, err
}
return buf.Bytes(), nil
}