Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: output version to stdout instead of command out #43

Merged
merged 1 commit into from
Feb 9, 2024
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
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
}
}
}
Loading