diff --git a/cmd/root.go b/cmd/root.go index 15c1faa..f99b4dc 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "os" "github.com/spf13/cobra" @@ -31,8 +30,5 @@ func Execute() { } func init() { - rootCmd.SetVersionTemplate(fmt.Sprintf( - "tmpo version %s\ncommit: %s\nbuilt: %s\n", - Version, Commit, Date, - )) + rootCmd.SetVersionTemplate(GetVersionOutput()) } diff --git a/cmd/version.go b/cmd/version.go new file mode 100644 index 0000000..8777c12 --- /dev/null +++ b/cmd/version.go @@ -0,0 +1,57 @@ +package cmd + +import ( + "fmt" + "regexp" + "strings" + "time" + + "github.com/spf13/cobra" +) + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Show version information", + Long: "Display the current version information including date and release URL.", + Hidden: true, + Run: func(cmd *cobra.Command, args []string) { + fmt.Print(GetVersionOutput()) + }, +} + +// GetVersionOutput returns the formatted version string used by both +// the version subcommand and the -v/--version flags +func GetVersionOutput() string { + return fmt.Sprintf("\ntmpo version %s %s\n%s\n\n", Version, GetFormattedDate(Date), GetChangelogUrl(Version)) +} + +// GetFormattedDate parses inputDate as an RFC3339 timestamp and returns the date +// formatted as "YYYY-MM-DD" wrapped in parentheses (for example "(2006-01-02)"). +// If inputDate is empty or cannot be parsed as RFC3339, it returns an empty string. +func GetFormattedDate(inputDate string) string { + if inputDate == "" { + return "" + } + + date, err := time.Parse(time.RFC3339, inputDate) + if err != nil { + return "" + } + + return fmt.Sprintf("(%s)", date.Format("2006-01-02")) +} + +func GetChangelogUrl(version string) string { + path := "https://github.com/DylanDevelops/tmpo" + + r := regexp.MustCompile(`^v?\d+\.\d+\.\d+(-[\w.]+)?$`) + if !r.MatchString(version) { + return fmt.Sprintf("%s/releases/latest", path) + } + + return fmt.Sprintf("%s/releases/tag/v%s", path, strings.TrimPrefix(version, "v")) +} + +func init() { + rootCmd.AddCommand(versionCmd) +}