Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ builds:
- linux
- windows
- darwin
ldflags:
- -s -w
- -X github.com/loops-so/cli/cmd.version={{.Version}}
- -X github.com/loops-so/cli/cmd.commit={{.ShortCommit}}

archives:
- formats: [tar.gz]
Expand Down
36 changes: 36 additions & 0 deletions cmd/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cmd

import (
"fmt"
"io"

"github.com/spf13/cobra"
)

var (
version = "dev"
commit = "none"
)

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version information",
RunE: func(cmd *cobra.Command, args []string) error {
return runVersion(cmd.OutOrStdout())
},
}

func runVersion(w io.Writer) error {
if isJSONOutput() {
return printJSON(w, struct {
Version string `json:"version"`
Commit string `json:"commit"`
}{version, commit})
}
fmt.Fprintf(w, "loops %s (commit: %s)\n", version, commit)
return nil
}

func init() {
rootCmd.AddCommand(versionCmd)
}
41 changes: 41 additions & 0 deletions cmd/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package cmd

import (
"bytes"
"encoding/json"
"strings"
"testing"
)

func TestRunVersion_Text(t *testing.T) {
outputFormat = "text"
var buf bytes.Buffer
if err := runVersion(&buf); err != nil {
t.Fatal(err)
}
got := buf.String()
if !strings.HasPrefix(got, "loops ") {
t.Errorf("unexpected output: %q", got)
}
}

func TestRunVersion_JSON(t *testing.T) {
outputFormat = "json"
t.Cleanup(func() { outputFormat = "text" })

var buf bytes.Buffer
if err := runVersion(&buf); err != nil {
t.Fatal(err)
}

var got struct {
Version string `json:"version"`
Commit string `json:"commit"`
}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if got.Version == "" {
t.Error("version field is empty")
}
}