package bonfire import ( "io" "os" "github.com/spf13/cobra" ) // NewRoot builds the shared cobra root used by the summer tool and app binaries. // It accepts command values rather than a party registry to avoid an import cycle. func NewRoot(name string, commands []Command, out io.Writer) *cobra.Command { if out == nil { out = os.Stdout } root := &cobra.Command{ Use: name, SilenceUsage: true, SilenceErrors: true, CompletionOptions: cobra.CompletionOptions{ DisableDefaultCmd: true, }, } root.SetOut(out) root.SetErr(out) for _, command := range commands { root.AddCommand(wrap(command, out)) } return root } func wrap(c Command, out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: c.Name, Short: c.Description, Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { if c.Run == nil { return nil } writer := out if cmd != nil { if w := cmd.OutOrStdout(); w != nil { writer = w } } return c.Run(cmd.Context(), cobraInput{cmd: cmd, spec: c, args: args}, writerOutput{w: writer}) }, } for _, flag := range c.Flags { if flag.Shorthand != "" { cmd.Flags().StringP(flag.Name, flag.Shorthand, flag.Default, flag.Description) continue } cmd.Flags().String(flag.Name, flag.Default, flag.Description) } return cmd }