signald-go/cmd/signaldctl/cmd/version.go

81 lines
2.5 KiB
Go

// Copyright © 2021 Finn Herzfeld <finn@janky.solutions>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"encoding/json"
"log"
"os"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"gitlab.com/signald/signald-go/cmd/signaldctl/common"
"gitlab.com/signald/signald-go/signald/client-protocol/v1"
)
// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "print the current signald and signaldctl version",
Run: func(cmd *cobra.Command, args []string) {
go common.Signald.Listen(nil)
r := v1.VersionRequest{}
signaldVersion, err := r.Submit(common.Signald)
if err != nil {
log.Fatal(err)
}
signaldctlVersion := v1.JsonVersionMessage{
Name: common.Name,
Branch: common.Branch,
Commit: common.Commit,
Version: common.Version,
}
output := []v1.JsonVersionMessage{signaldVersion, signaldctlVersion}
switch common.OutputFormat {
case common.OutputFormatJSON:
err := json.NewEncoder(os.Stdout).Encode(output)
if err != nil {
log.Fatal(err, "error encoding response to stdout")
}
case common.OutputFormatYAML:
err := yaml.NewEncoder(os.Stdout).Encode(output)
if err != nil {
log.Fatal(err, "error encoding response to stdout")
}
case common.OutputFormatCSV, common.OutputFormatTable, common.OutputFormatDefault:
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(table.Row{"Name", "Version", "Branch", "Commit"})
t.AppendRow(table.Row{common.Name, common.Version, common.Branch, common.Commit})
t.AppendRow(table.Row{signaldVersion.Name, signaldVersion.Version, signaldVersion.Branch, signaldVersion.Commit})
if common.OutputFormat == common.OutputFormatCSV {
t.RenderCSV()
} else {
common.StylizeTable(t)
t.Render()
}
default:
log.Fatal("Unsupported output format")
}
},
}
func init() {
RootCmd.AddCommand(versionCmd)
}