Cobra

package main

import (
    "os"

    "github.com/spf13/cobra"

    "go.szostok.io/version/extension"
)

// NewRoot returns a root cobra.Command for the whole CLI.
func NewRoot() *cobra.Command {
    cmd := &cobra.Command{
        Use:   "example",
        Short: "An example CLI built with github.com/spf13/cobra",
    }

    cmd.AddCommand(
        // you just need to add this, and you are done.
        extension.NewVersionCobraCmd(),
    )

    return cmd
}

func main() {
    if err := NewRoot().Execute(); err != nil {
        os.Exit(1)
    }
}

You can customize almost all aspects:

  • Enable upgrade notice:

    extension.NewVersionCobraCmd(
        // 2. Explicit turn on upgrade notice
        extension.WithUpgradeNotice("mszostok", "codeowners-validator"),
    ),
    

    It prints the notice on standard error channel (stderr). As a result, output processing, such as executing <cli> version -ojson | jq .gitCommit, works properly even if the upgrade notice is displayed.

  • Define pre-hook function:

    extension.WithPreHook(func(ctx context.Context) error {
     // function body
    })
    
  • Define post-hook function:

    It's executed only if version print was successful.

    extension.WithPostHook(func(ctx context.Context) error {
     // function body
    })
    
  • Define custom aliases:

    extension.WithAliasesOptions("v", "vv"),
    
Back to top