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
83 changes: 83 additions & 0 deletions metadata/metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Package metadata provides build-time information for CLI applications.
//
// Services set their build variables via ldflags at build time:
//
// go build -ldflags "\
// -X github.com/dioad/cli/metadata.Version=$(VERSION) \
// -X github.com/dioad/cli/metadata.Commit=$(COMMIT) \
// -X github.com/dioad/cli/metadata.Date=$(DATE)" \
// ./...
//
// Then pass a BuildInfo to NewVersionCommand:
//
// cmd.AddCommand(
// metadata.NewVersionCommand(OrgName, AppName, metadata.BuildInfo{
// Version: metadata.Version,
// Commit: metadata.Commit,
// Date: metadata.Date,
// }),
// )
package metadata

import (
"encoding/json"
"fmt"

"github.com/spf13/cobra"
)

// Version is the application version, set via ldflags at build time.
var Version = "local"

// Commit is the git commit SHA, set via ldflags at build time.
var Commit = "XX"

// Date is the build date, set via ldflags at build time.
var Date = "1970-01-01"

// BuildInfo holds version information populated at build time.
type BuildInfo struct {
Version string
Commit string
Date string
}

// 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 {
var jsonOutput bool

cmd := &cobra.Command{
Use: "version",
Short: "Show version information (use --json for detailed output)",
Long: `Show version information.

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,
RunE: func(cmd *cobra.Command, _ []string) error {
if jsonOutput {
details := map[string]string{
"version": info.Version,
"commit": info.Commit,
"date": info.Date,
}
enc := json.NewEncoder(cmd.OutOrStdout())
enc.SetIndent("", " ")
return enc.Encode(details)
}

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

cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output version information as JSON")

return cmd
}
Comment on lines +78 to +83

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 is wrapped with cli.NewCommand, which at runtime goes through cli.CobraRunE → InitConfig. That means running version will read config/env, configure logging, and may start a Viper WatchConfig goroutine if a config file exists—side effects that are typically unexpected for a simple version-printing command. Consider wiring cmd.RunE directly for this command (or adding a framework hook to run without InitConfig / without watch/logging) so version stays lightweight and has no background watchers.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

72 changes: 72 additions & 0 deletions metadata/metadata_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package metadata_test

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

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

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

func TestNewVersionCommand_PlainText(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{})

err := cmd.Execute()
require.NoError(t, err)

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

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"})

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)

var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetArgs([]string{})

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")
}
Loading