github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/chat/commands/base.go (about) 1 package commands 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 "github.com/keybase/client/go/chat/globals" 9 "github.com/keybase/client/go/chat/utils" 10 "github.com/keybase/client/go/libkb" 11 "github.com/keybase/client/go/protocol/chat1" 12 "github.com/keybase/client/go/protocol/gregor1" 13 ) 14 15 type baseCommand struct { 16 globals.Contextified 17 utils.DebugLabeler 18 name string 19 aliases []string 20 usage string 21 description string 22 hasHelpText bool 23 } 24 25 func newBaseCommand(g *globals.Context, name, usage, desc string, hasHelpText bool, aliases ...string) *baseCommand { 26 return &baseCommand{ 27 Contextified: globals.NewContextified(g), 28 DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), fmt.Sprintf("Commands.%s", name), false), 29 name: name, 30 usage: usage, 31 aliases: aliases, 32 description: desc, 33 hasHelpText: hasHelpText, 34 } 35 } 36 37 func (b *baseCommand) tokenize(text string, minArgs int) (toks []string, err error) { 38 toks = strings.Split(strings.TrimRight(text, " "), " ") 39 if len(toks) < minArgs { 40 return toks, ErrInvalidArguments 41 } 42 return toks, nil 43 } 44 45 func (b *baseCommand) commandAndMessage(text string) (cmd string, msg string, err error) { 46 toks, err := b.tokenize(text, 1) 47 if err != nil { 48 return "", "", err 49 } 50 if len(toks) == 1 { 51 return toks[0], "", nil 52 } 53 return toks[0], strings.Join(toks[1:], " "), nil 54 } 55 56 func (b *baseCommand) getChatUI() libkb.ChatUI { 57 ui, err := b.G().UIRouter.GetChatUI() 58 if err != nil || ui == nil { 59 b.Debug(context.Background(), "getChatUI: no chat UI found: err: %s", err) 60 return utils.NullChatUI{} 61 } 62 return ui 63 } 64 65 func (b *baseCommand) Match(ctx context.Context, text string) bool { 66 if !strings.HasPrefix(text, "/") { 67 return false 68 } 69 cands := b.aliases 70 cands = append(cands, b.name) 71 for _, c := range cands { 72 if strings.HasPrefix(text, fmt.Sprintf("/%s", c)) { 73 return true 74 } 75 } 76 return false 77 } 78 79 func (b *baseCommand) Name() string { 80 return b.name 81 } 82 83 func (b *baseCommand) Usage() string { 84 return b.usage 85 } 86 87 func (b *baseCommand) Description() string { 88 return b.description 89 } 90 91 func (b *baseCommand) HasHelpText() bool { 92 return b.hasHelpText 93 } 94 95 func (b *baseCommand) Preview(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID, 96 tlfName, text string) { 97 } 98 99 func (b *baseCommand) Export() chat1.ConversationCommand { 100 return chat1.ConversationCommand{ 101 Name: b.Name(), 102 Usage: b.Usage(), 103 Description: b.Description(), 104 HasHelpText: b.HasHelpText(), 105 } 106 }