// Package spec provides spec file generation for use with carapace-bin
package spec import ( ) // Spec generates the spec file. func ( *cobra.Command) string { := &bytes.Buffer{} := yaml.NewEncoder() .SetIndent(2) _ = .Encode(commandLine()) return "# yaml-language-server: $schema=https://carapace.sh/schemas/command.json\n" + .String() } func commandLine( *cobra.Command) command.Command { := command.Command{ Name: .Use, Description: .Short, Aliases: .Aliases, Group: .GroupID, Hidden: .Hidden, Flags: make(command.FlagSet), PersistentFlags: make(command.FlagSet), Commands: make([]command.Command, 0), } if .Long != "" { .Documentation.Command = .Long } .ExclusiveFlags = exclusiveFlags() .LocalFlags().VisitAll(func( *pflag.Flag) { if .PersistentFlags().Lookup(.Name) != nil { return } .Flags[flagDefinition(, .Flags())] = toFlag() }) .PersistentFlags().VisitAll(func( *pflag.Flag) { .PersistentFlags[flagDefinition(, .Flags())] = toFlag() }) for , := range .Commands() { if .Name() != "_carapace" && .Deprecated == "" { .Commands = append(.Commands, ()) } } return } func flagDefinition( *pflag.Flag, *pflag.FlagSet) string { := pflagfork.Flag{Flag: } := pflagfork.FlagSet{FlagSet: }.Prefix() return .Definition() } func toFlag( *pflag.Flag) command.Flag { := pflagfork.Flag{Flag: } := .GetMode() var , string switch { case pflagfork.ShorthandOnly: = .Shorthand case pflagfork.NameAsShorthand: = .Shorthand = .Name default: if .Shorthand != "" { = .Shorthand } = .Name } var string if !isZeroDefault() { = .DefValue } return command.Flag{ Longhand: , Shorthand: , Description: .Usage, NameAsShorthand: == pflagfork.NameAsShorthand, Repeatable: .IsRepeatable(), Optarg: .IsOptarg() && .TakesValue(), Value: .TakesValue(), Hidden: .Hidden, Required: .Required(), Nargs: .Nargs(), Default: , } } func isZeroDefault( *pflag.Flag) bool { switch .Value.Type() { case "bool", "count": return .DefValue == "false" || .DefValue == "0" case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float32", "float64": return .DefValue == "0" case "string": return .DefValue == "" case "stringSlice", "intSlice", "int32Slice", "int64Slice", "uintSlice", "float32Slice", "float64Slice", "boolSlice", "durationSlice", "stringArray", "ipSlice", "ipNetSlice", "stringToInt", "stringToInt64", "stringToString": return .DefValue == "[]" case "duration": return .DefValue == "0s" case "ip", "ipNet", "ipMask": return .DefValue == "<nil>" default: return .DefValue == "" } } func exclusiveFlags( *cobra.Command) [][]string { := make(map[string]bool) var [][]string := func( *pflag.Flag) { for , := range .Annotations["cobra_annotation_mutually_exclusive"] { := strings.Fields() sort.Strings() := strings.Join(, "\x00") if ![] { [] = true = append(, ) } } } .LocalFlags().VisitAll() .PersistentFlags().VisitAll() return }