Skip to content

Commit

Permalink
feat(cmd): Add version flag
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Mar 7, 2024
1 parent b5120f9 commit f652bfb
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 9 deletions.
21 changes: 16 additions & 5 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import (
"github.com/spf13/pflag"
)

func New() *cobra.Command {
func New(version, commit string) *cobra.Command {
cmd := &cobra.Command{
Use: "pwgen",
Short: "Generate passwords",
Use: "pwgen",
Short: "Generate passwords",
Version: buildVersion(version, commit),

DisableAutoGenTag: true,
}
Expand All @@ -27,11 +28,21 @@ func New() *cobra.Command {
)

// default cmd if no cmd is given
cmd.InitDefaultVersionFlag()
subCmd, _, err := cmd.Find(os.Args[1:])
if err == nil && subCmd.Use == cmd.Use && cmd.Flags().Parse(os.Args[1:]) != pflag.ErrHelp {
args := append([]string{template.Use}, os.Args[1:]...)
cmd.SetArgs(args)
if versionFlag, err := cmd.Flags().GetBool("version"); err == nil && !versionFlag {
args := append([]string{template.Use}, os.Args[1:]...)
cmd.SetArgs(args)
}
}

return cmd
}

func buildVersion(version, commit string) string {
if commit != "" {
version += " (" + commit + ")"
}
return version
}
2 changes: 1 addition & 1 deletion internal/generate/completions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func main() {
panic(err)
}

rootCmd := cmd.New()
rootCmd := cmd.New("", "")
name := rootCmd.Name()
var buf bytes.Buffer
rootCmd.SetOut(&buf)
Expand Down
2 changes: 1 addition & 1 deletion internal/generate/docs/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func main() {
log.Fatal(fmt.Errorf("failed to mkdir: %w", err))
}

rootCmd := cmd.New()
rootCmd := cmd.New("", "")

err = doc.GenMarkdownTree(rootCmd, output)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/generate/manpages/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func main() {
panic(err)
}

rootCmd := cmd.New()
rootCmd := cmd.New("", "")
rootName := rootCmd.Name()

date, err := time.Parse(time.RFC3339, dateParam)
Expand Down
7 changes: 6 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ import (
"github.com/gabe565/pwgen-go/cmd"
)

var (
version = "beta"
commit = ""
)

func main() {
rootCmd := cmd.New()
rootCmd := cmd.New(version, commit)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
Expand Down

0 comments on commit f652bfb

Please sign in to comment.