github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/pkg/cmd/main.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"log"
     7  	"os"
     8  	"os/signal"
     9  
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  type Option func(*cobra.Command)
    14  
    15  func WithArgs(args ...string) Option { return func(c *cobra.Command) { c.SetArgs(args) } }
    16  func WithStdout(w io.Writer) Option  { return func(c *cobra.Command) { c.SetOut(w) } }
    17  func WithStderr(w io.Writer) Option  { return func(c *cobra.Command) { c.SetErr(w) } }
    18  
    19  func Execute(version string, opt ...Option) error {
    20  	ctx, cancel := context.WithCancel(context.Background())
    21  	c := make(chan os.Signal, 1)
    22  	signal.Notify(c, os.Interrupt)
    23  	go func() {
    24  		<-c // Close gracefully if CTRL+C is pressed once.
    25  		cancel()
    26  		<-c // Exit if CTRL+C is pressed twice.
    27  		os.Exit(1)
    28  	}()
    29  
    30  	cmd := rootCmd(version)
    31  
    32  	for _, o := range opt {
    33  		o(cmd)
    34  	}
    35  
    36  	return cmd.ExecuteContext(ctx)
    37  }
    38  
    39  func rootCmd(version string) *cobra.Command {
    40  	var silent bool
    41  
    42  	cmd := &cobra.Command{
    43  		Use:  "kubri",
    44  		Long: "Sign and release software for common package managers and software update frameworks.",
    45  		PersistentPreRun: func(cmd *cobra.Command, _ []string) {
    46  			log.SetFlags(0)
    47  			if silent {
    48  				log.SetOutput(io.Discard)
    49  			} else {
    50  				log.SetOutput(cmd.OutOrStdout())
    51  			}
    52  		},
    53  	}
    54  
    55  	cmd.PersistentFlags().BoolVarP(&silent, "silent", "s", false, "only log fatal errors")
    56  
    57  	cmd.AddCommand(buildCmd(), keysCmd(), jsonschemaCmd(), versionCmd(version))
    58  
    59  	return cmd
    60  }