Skip to content

Commit

Permalink
fix: Enable to display current command's version (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shu Kutsuzawa authored Mar 11, 2020
1 parent 8c9aacf commit 7082817
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ builds:
- amd64
env:
- CGO_ENABLED=0
ldflags:
- "-X github.com/screwdriver-cd/sd-local/cmd.version={{ .Version }}"

archives:
- format: binary
Expand Down
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func Execute() error {
rootCmd.AddCommand(
newBuildCmd(),
config.NewConfigCmd(),
newVersionCmd(),
)
return rootCmd.Execute()
}
23 changes: 23 additions & 0 deletions cmd/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

var (
// version is embedded when building this command using ldflags.
// if nothing is embedded, version is "dev"
version = "dev"
)

func newVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Display command's version.",
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintln(cmd.OutOrStdout(), version)
},
}
}
46 changes: 46 additions & 0 deletions cmd/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package cmd

import (
"bytes"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestVersionCmd(t *testing.T) {
cases := []struct {
name string
version string
expect string
}{
{
name: "0.0.1 is embedded as version",
version: "0.0.1",
expect: "0.0.1",
},
{
name: "0.1.0 is embedded as version",
version: "0.1.0",
expect: "0.1.0",
},
{
name: "version is not embedded",
expect: "dev",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
tv := version
if c.version != "" {
version = c.version
}
defer func() { version = tv }()
cmd := newVersionCmd()
buf := bytes.NewBuffer(nil)
cmd.SetOut(buf)
cmd.Execute()
assert.Equal(t, fmt.Sprintf("%s\n", c.expect), buf.String())
})
}
}

0 comments on commit 7082817

Please sign in to comment.