package carapace
import (
"os"
"github.com/carapace-sh/carapace/internal/shell"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type Carapace struct {
cmd *cobra .Command
}
func Gen (cmd *cobra .Command ) *Carapace {
addCompletionCommand (cmd )
storage .bridge (cmd )
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 {
for name , action := range actions {
e .flag [name ] = action
}
}
}
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 ) {
return shell .Snippet (c .cmd , name )
}
func IsCallback () bool {
return len (os .Args ) > 1 && os .Args [1 ] == "_carapace"
}
func Test (t interface { Error (args ...interface {}) }) {
for _ , e := range storage .check () {
t .Error (e )
}
}
The pages are generated with Golds v0.8.2 . (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 .