package carapace
import (
"fmt"
"maps"
"os"
"slices"
"strings"
"github.com/carapace-sh/carapace/internal/shell"
"github.com/carapace-sh/carapace/internal/shell/multi"
"github.com/carapace-sh/carapace/pkg/uid"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type Carapace struct {
cmd *cobra .Command
}
type Option func (*entry )
func WithSubcommands (cmds ...*cobra .Command ) Option {
return func (e *entry ) {
e .subcommands = cmds
exe := uid .Executable ()
names := make ([]string , 0 , len (cmds )+1 )
names = append (names , exe )
for _ , cmd := range cmds {
names = append (names , cmd .Name ())
}
e .subcommandNames = names
if e .defaultName == "" {
e .defaultName = exe
}
}
}
func WithDefault (name string ) Option {
return func (e *entry ) {
e .defaultName = name
}
}
func WithSnippetFuncs (funcs map [string ]string ) Option {
return func (e *entry ) {
if e .snippetFuncs == nil {
e .snippetFuncs = make (map [string ][]string )
}
for sh , code := range funcs {
e .snippetFuncs [sh ] = append (e .snippetFuncs [sh ], code )
}
}
}
func Gen (cmd *cobra .Command , opts ...Option ) *Carapace {
addCompletionCommand (cmd )
storage .bridge (cmd )
e := storage .get (cmd )
for _ , opt := range opts {
opt (e )
}
return &Carapace {
cmd : cmd ,
}
}
func (c Carapace ) PreRun (f func (cmd *cobra .Command , args []string )) {
if entry := storage .get (c .cmd ); entry .prerun != nil {
_f := entry .prerun
entry .prerun = func (cmd *cobra .Command , args []string ) {
_f (cmd , args )
f (cmd , args )
}
} else {
entry .prerun = f
}
}
func (c Carapace ) PreInvoke (f func (cmd *cobra .Command , flag *pflag .Flag , action Action ) Action ) {
if entry := storage .get (c .cmd ); entry .preinvoke != nil {
_f := entry .preinvoke
entry .preinvoke = func (cmd *cobra .Command , flag *pflag .Flag , action Action ) Action {
return f (cmd , flag , _f (cmd , flag , action ))
}
} else {
entry .preinvoke = f
}
}
func (c Carapace ) PositionalCompletion (action ...Action ) {
storage .get (c .cmd ).positional = action
}
func (c Carapace ) PositionalAnyCompletion (action Action ) {
storage .get (c .cmd ).positionalAny = &action
}
func (c Carapace ) DashCompletion (action ...Action ) {
storage .get (c .cmd ).dash = action
}
func (c Carapace ) DashAnyCompletion (action Action ) {
storage .get (c .cmd ).dashAny = &action
}
func (c Carapace ) FlagCompletion (actions ActionMap ) {
e := storage .get (c .cmd )
e .flagMutex .Lock ()
defer e .flagMutex .Unlock ()
if e .flag == nil {
e .flag = actions
} else {
maps .Copy (e .flag , actions )
}
}
const annotation_standalone = "carapace_standalone"
func (c Carapace ) Standalone () {
c .cmd .CompletionOptions = cobra .CompletionOptions {
DisableDefaultCmd : true ,
}
if c .cmd .Annotations == nil {
c .cmd .Annotations = make (map [string ]string )
}
c .cmd .Annotations [annotation_standalone ] = "true"
c .PreRun (func (cmd *cobra .Command , args []string ) {
if f := cmd .Flag ("help" ); f == nil {
cmd .Flags ().Bool ("help" , false , "" )
cmd .Flag ("help" ).Hidden = true
} else if f .Annotations != nil {
if _ , ok := f .Annotations [cobra .FlagSetByCobraAnnotation ]; ok {
cmd .Flag ("help" ).Hidden = true
}
}
})
c .cmd .SetHelpCommand (&cobra .Command {Use : "_carapace_help" , Hidden : true , Deprecated : "fake help command to prevent default" })
}
func (c Carapace ) Snippet (name string ) (string , error ) {
entry := storage .get (c .cmd )
if len (entry .subcommands ) > 0 {
return multi .Snippet (name , entry .subcommandNames , entry .defaultName , entry .snippetFuncs )
}
s , err := shell .Snippet (c .cmd , name )
if err != nil {
return s , err
}
if entry .snippetFuncs != nil {
if extra , ok := entry .snippetFuncs [name ]; ok && len (extra ) > 0 {
s = strings .Join (extra , "\n" ) + "\n" + s
}
}
return s , nil
}
func (c Carapace ) Execute () error {
if entry := storage .get (c .cmd ); len (entry .subcommands ) > 0 {
c .rewriteArgs (entry )
}
return c .cmd .Execute ()
}
func IsCallback () bool {
return len (os .Args ) > 1 && os .Args [1 ] == "_carapace"
}
func (c Carapace ) rewriteArgs (e *entry ) {
exe := uid .Executable ()
isCompleterSubcommand := func (name string ) bool {
return slices .Contains (e .subcommandNames , name )
}
isRootSubcommand := func (name string ) bool {
for _ , cmd := range c .cmd .Commands () {
if cmd .Name () == name {
return true
}
}
return false
}
if len (os .Args ) > 1 && os .Args [1 ] == "_carapace" {
if len (os .Args ) < 4 {
shell := ""
if len (os .Args ) > 2 {
shell = os .Args [2 ]
}
fmt .Println (multi .SnippetOrEmpty (shell , e .subcommandNames , e .defaultName , e .snippetFuncs ))
os .Exit (0 )
}
if len (os .Args ) > 4 && isCompleterSubcommand (os .Args [4 ]) && os .Args [4 ] != exe {
os .Args = append (
[]string {os .Args [0 ], os .Args [4 ], "_carapace" , os .Args [2 ], os .Args [3 ]},
os .Args [5 :]...,
)
} else {
os .Args = append (
[]string {os .Args [0 ], exe , "_carapace" },
os .Args [2 :]...,
)
}
}
if len (os .Args ) > 2 && os .Args [1 ] == exe && os .Args [2 ] == "_carapace" {
if len (os .Args ) < 4 {
return
}
if os .Args [3 ] == "export" {
if len (os .Args ) > 6 && isRootSubcommand (os .Args [6 ]) {
os .Args = append (
[]string {os .Args [0 ], os .Args [6 ], "_carapace" , os .Args [3 ], os .Args [4 ], os .Args [5 ]},
os .Args [7 :]...,
)
} else {
os .Args = append ([]string {os .Args [0 ]}, os .Args [2 :]...)
}
} else {
if len (os .Args ) < 5 {
fmt .Println (multi .SingleSnippetOrEmpty (os .Args [3 ], exe , e .subcommandNames , e .defaultName , e .snippetFuncs ))
os .Exit (0 )
}
if isRootSubcommand (os .Args [4 ]) {
os .Args = append (
[]string {os .Args [0 ], os .Args [4 ], "_carapace" , os .Args [3 ]},
os .Args [5 :]...,
)
} else {
os .Args = append ([]string {os .Args [0 ]}, os .Args [2 :]...)
}
}
}
if len (os .Args ) > 2 && isCompleterSubcommand (os .Args [1 ]) && os .Args [2 ] == "_carapace" {
if len (os .Args ) < 5 {
shell := ""
if len (os .Args ) > 3 {
shell = os .Args [3 ]
}
fmt .Println (multi .SingleSnippetOrEmpty (shell , os .Args [1 ], e .subcommandNames , e .defaultName , e .snippetFuncs ))
os .Exit (0 )
}
}
}
func Test (t interface { Error (args ...any ) }) {
for _ , e := range storage .check () {
t .Error (e )
}
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .