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
47 changes: 22 additions & 25 deletions metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,10 @@
package metadata

import (
"context"
"encoding/json"
"fmt"
"os"

"github.com/spf13/cobra"

"github.com/dioad/cli"
)

// Version is the application version, set via ldflags at build time.
Expand All @@ -46,14 +42,14 @@ type BuildInfo struct {
Date string
}

type versionConfig struct {
JSON bool `mapstructure:"json"`
}

// NewVersionCommand returns a "version" cobra.Command that prints build information.
// orgName and appName are used in the plain-text output line.
//
// Unlike commands built with cli.NewCommand, this command wires RunE directly and
// does not call InitConfig, so it produces no side effects such as reading config
// files, configuring logging, or starting a background WatchConfig goroutine.
func NewVersionCommand(orgName, appName string, info BuildInfo) *cobra.Command {
cfg := &versionConfig{}
var jsonOutput bool

cmd := &cobra.Command{
Use: "version",
Expand All @@ -63,24 +59,25 @@ func NewVersionCommand(orgName, appName string, info BuildInfo) *cobra.Command {
By default, this prints a single human-readable line with the application version.
Use --json to print detailed version information (including version, commit, and date)
as a JSON object.`,
Args: cobra.NoArgs,
}

exec := func(_ context.Context, cfg *versionConfig) error {
if cfg.JSON {
details := map[string]string{
"version": info.Version,
"commit": info.Commit,
"date": info.Date,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
if jsonOutput {
details := map[string]string{
Comment on lines 51 to +65

Copilot AI Mar 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NewVersionCommand’s behavior was reworked (no cli.NewCommand wrapper, new flag wiring, different execution path) but there are no tests covering the default output vs --json output. Adding a small unit test that executes the command with/without --json and asserts on the emitted output would help prevent regressions.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot apply changes based on this feedback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests were already added in db29088: TestNewVersionCommand_PlainText (default output), TestNewVersionCommand_JSON (--json output), and TestNewVersionCommand_NoInitConfig (verifies no context/config required). All three pass.

"version": info.Version,
"commit": info.Commit,
"date": info.Date,
}
enc := json.NewEncoder(cmd.OutOrStdout())
enc.SetIndent("", " ")
return enc.Encode(details)
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(details)
}

fmt.Printf("%s %s %v\n", orgName, appName, info.Version)
return nil
fmt.Fprintf(cmd.OutOrStdout(), "%s %s %s\n", orgName, appName, info.Version)
return nil
},
}

return cli.NewCommand(cmd, exec, cfg)
cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output version information as JSON")

return cmd
}
110 changes: 34 additions & 76 deletions metadata/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,55 +2,17 @@ package metadata_test

import (
"bytes"
"context"
"encoding/json"
"io"
"os"
"strings"
"testing"

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

"github.com/dioad/cli"
"github.com/dioad/cli/metadata"
)

// captureStdout redirects os.Stdout to a pipe, calls f, then returns
// everything written to the pipe as a string.
func captureStdout(t *testing.T, f func()) string {
t.Helper()

r, w, err := os.Pipe()
require.NoError(t, err)

origStdout := os.Stdout
defer func() {
os.Stdout = origStdout
}()
os.Stdout = w

f()
w.Close()

var buf bytes.Buffer
_, err = io.Copy(&buf, r)
require.NoError(t, err)
r.Close()

return buf.String()
}

func newTestContext() context.Context {
return cli.Context(
context.Background(),
cli.SetOrgName("testorg"),
cli.SetAppName("testapp"),
)
}

// TestNewVersionCommand_FlagRegistered verifies that the --json flag is
// registered on the command returned by NewVersionCommand.
func TestNewVersionCommand_FlagRegistered(t *testing.T) {
func TestNewVersionCommand_PlainText(t *testing.T) {
info := metadata.BuildInfo{
Version: "1.2.3",
Commit: "abc1234",
Expand All @@ -59,56 +21,52 @@ func TestNewVersionCommand_FlagRegistered(t *testing.T) {

cmd := metadata.NewVersionCommand("myorg", "myapp", info)

jsonFlag := cmd.Flags().Lookup("json")
require.NotNil(t, jsonFlag, "--json flag must be registered on the version command")
assert.Equal(t, "false", jsonFlag.DefValue, "--json flag default should be false")
}

// TestNewVersionCommand_PlainOutput verifies that the command prints a single
// "orgName appName version" line when --json is not set.
func TestNewVersionCommand_PlainOutput(t *testing.T) {
info := metadata.BuildInfo{
Version: "1.2.3",
Commit: "abc1234",
Date: "2024-01-01",
}

cmd := metadata.NewVersionCommand("myorg", "myapp", info)
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetArgs([]string{})
cmd.SilenceUsage = true

var execErr error
got := captureStdout(t, func() {
execErr = cmd.ExecuteContext(newTestContext())
})
err := cmd.Execute()
require.NoError(t, err)

require.NoError(t, execErr)
assert.Equal(t, "myorg myapp 1.2.3\n", got)
assert.Equal(t, "myorg myapp 1.2.3\n", buf.String())
}

// TestNewVersionCommand_JSONOutput verifies that the command prints valid JSON
// containing version, commit, and date fields when --json is passed.
func TestNewVersionCommand_JSONOutput(t *testing.T) {
func TestNewVersionCommand_JSON(t *testing.T) {
info := metadata.BuildInfo{
Version: "1.2.3",
Commit: "abc1234",
Date: "2024-01-01",
}

cmd := metadata.NewVersionCommand("myorg", "myapp", info)

var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetArgs([]string{"--json"})
cmd.SilenceUsage = true

var execErr error
got := captureStdout(t, func() {
execErr = cmd.ExecuteContext(newTestContext())
})
err := cmd.Execute()
require.NoError(t, err)

var got map[string]string
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
assert.Equal(t, info.Version, got["version"])
assert.Equal(t, info.Commit, got["commit"])
assert.Equal(t, info.Date, got["date"])
}

func TestNewVersionCommand_NoInitConfig(t *testing.T) {
// This test verifies the command executes without requiring org/app context,
// confirming it bypasses CobraRunE / InitConfig entirely.
info := metadata.BuildInfo{Version: "0.1.0", Commit: "XX", Date: "1970-01-01"}

cmd := metadata.NewVersionCommand("org", "app", info)

require.NoError(t, execErr)
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetArgs([]string{})

var result map[string]string
require.NoError(t, json.Unmarshal([]byte(got), &result), "output should be valid JSON")
assert.Equal(t, info.Version, result["version"])
assert.Equal(t, info.Commit, result["commit"])
assert.Equal(t, info.Date, result["date"])
err := cmd.Execute()
require.NoError(t, err, "version command should run without context or config")
assert.True(t, strings.HasPrefix(buf.String(), "org app "),
"output should start with org and app name")
}