spruce/internal/cmd/version.go
Dan Anglin 90638f5569
fix: customised usage messages
Add functionality to display the default help message when running
spruce without any arguments or when the help flag is used.

Customise the help message for the subcommands.

Additional changes:

- Refactor: move the Runner interface to the internal cmd package
- Fix: Add a summary for each of the subcommands.
- Refactor: Use string builder to replace string literals.
- Perf: Use a switch statement to only create the subcommand that the
  user calls.
2023-08-13 17:45:33 +01:00

46 lines
1 KiB
Go

package cmd
import (
"flag"
"fmt"
"strings"
)
type VersionCommand struct {
*flag.FlagSet
summary string
fullVersion bool
binaryVersion string
buildTime string
goVersion string
gitCommit string
}
func NewVersionCommand(binaryVersion, buildTime, goVersion, gitCommit string) *VersionCommand {
vc := VersionCommand{
FlagSet: flag.NewFlagSet("version", flag.ExitOnError),
binaryVersion: binaryVersion,
buildTime: buildTime,
goVersion: goVersion,
gitCommit: gitCommit,
summary: "Print the application's build information.",
}
vc.BoolVar(&vc.fullVersion, "full", false, "prints the full build information")
vc.Usage = usageFunc(vc.Name(), vc.summary, vc.FlagSet)
return &vc
}
func (v *VersionCommand) Run() error {
var b strings.Builder
if v.fullVersion {
fmt.Fprintf(&b, "Spruce\n Version: %s\n Git commit: %s\n Go version: %s\n Build date: %s\n", v.binaryVersion, v.gitCommit, v.goVersion, v.buildTime)
} else {
fmt.Fprintln(&b, v.binaryVersion)
}
fmt.Print(b.String())
return nil
}