Skip to content

Commit

Permalink
fix: output version to stdout instead of command out (#43)
Browse files Browse the repository at this point in the history
Signed-off-by: Keith Zantow <[email protected]>
  • Loading branch information
kzantow authored Feb 9, 2024
1 parent 06cf78f commit cb94e40
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func VersionCommand(id Identification, additions ...versionAddition) *cobra.Comm

value, err := versionInfo(info, format, additions...)
if err == nil {
cmd.Print(value)
fmt.Print(value)
}
return err
},
Expand Down
62 changes: 62 additions & 0 deletions version_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,39 @@
package clio

import (
"bytes"
"io"
"os"
"sync"
"testing"

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

func Test_versionOutputToStdout(t *testing.T) {
c := VersionCommand(Identification{
Name: "test",
Version: "version",
})

stdout := &bytes.Buffer{}
restoreStdout := capture(&os.Stdout, stdout, 1024)
defer restoreStdout()

stderr := &bytes.Buffer{}
restoreStderr := capture(&os.Stderr, stderr, 1024)
defer restoreStderr()

_ = c.RunE(c, nil)

// close and flush the buffers, wait until complete
restoreStdout()
restoreStderr()

require.NotEmpty(t, stdout.String())
require.Empty(t, stderr.String())
}

func Test_versionInfoText(t *testing.T) {
expected := `Application: the-name
Version: the-version
Expand Down Expand Up @@ -67,3 +95,37 @@ func Test_versionInfoJSON(t *testing.T) {
require.NoError(t, err)
require.JSONEq(t, expected, got)
}

func capture(target **os.File, writer io.Writer, bufSize int) (close func()) {
original := *target

r, w, _ := os.Pipe()

wg := sync.WaitGroup{}
wg.Add(1)

go func() {
defer wg.Done()
buf := make([]byte, bufSize)
for {
n, err := r.Read(buf)
if n > 0 {
_, _ = writer.Write(buf[0:n])
}
if err != nil {
break
}
}
}()

*target = w

return func() {
if original != nil {
_ = w.Close()
wg.Wait()
*target = original
original = nil
}
}
}

0 comments on commit cb94e40

Please sign in to comment.