Skip to content

Commit 51b75ae

Browse files
committed
Support version output
1 parent 2517e24 commit 51b75ae

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

internal/cli/root.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,22 @@ package cli
33
import (
44
"diffscope-package-manager/internal/cli/commands"
55
"diffscope-package-manager/internal/config"
6+
"encoding/json"
7+
"fmt"
68

79
"github.com/spf13/cobra"
810
"github.com/spf13/viper"
911
)
1012

13+
var (
14+
version = "0.0.0+dev"
15+
)
16+
17+
type versionJsonOutput struct {
18+
Name string `json:"name"`
19+
Version string `json:"version"`
20+
}
21+
1122
var (
1223
rootCmd = &cobra.Command{
1324
Use: "dspm",
@@ -17,6 +28,32 @@ var (
1728
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
1829
return initConfig(cmd)
1930
},
31+
RunE: func(cmd *cobra.Command, arg []string) error {
32+
showVersion, err := cmd.Flags().GetBool("version")
33+
if err != nil {
34+
return err
35+
}
36+
if showVersion {
37+
if loadedConfig.JSON {
38+
output := versionJsonOutput{
39+
Name: cmd.Use,
40+
Version: version,
41+
}
42+
jsonBytes, err := json.Marshal(output)
43+
if err != nil {
44+
return err
45+
}
46+
fmt.Fprintln(cmd.OutOrStdout(), string(jsonBytes))
47+
} else {
48+
fmt.Fprintf(cmd.OutOrStdout(), "%s version %s\n", cmd.Use, version)
49+
}
50+
return nil
51+
}
52+
return cmd.Help()
53+
},
54+
CompletionOptions: cobra.CompletionOptions{
55+
DisableDefaultCmd: true,
56+
},
2057
}
2158

2259
loadedConfig config.Config
@@ -35,6 +72,7 @@ func Config() config.Config {
3572
func init() {
3673
rootCmd.PersistentFlags().Bool("json", false, "output JSON")
3774
rootCmd.PersistentFlags().String("packages-dir", "", "packages installation directory")
75+
rootCmd.Flags().BoolP("version", "v", false, "version for "+rootCmd.Use)
3876

3977
rootCmd.AddCommand(
4078
commands.NewInstallCmd(),

0 commit comments

Comments
 (0)