github.com/starshine-sys/bcr@v0.21.0/alias.go (about) 1 package bcr 2 3 import ( 4 "errors" 5 "fmt" 6 "strings" 7 8 "github.com/diamondburned/arikawa/v3/bot/extras/shellwords" 9 ) 10 11 // Errors related to creating aliases 12 var ( 13 ErrNoPath = errors.New("alias: no path supplied") 14 ErrNilCommand = errors.New("alias: command was nil") 15 ) 16 17 // ArgTransformer is used in Alias, passing in the context's RawArgs, which are then split again. 18 type ArgTransformer func(string) string 19 20 // Alias creates an alias to the command `path`, and transforms the arguments according to argTransform. 21 // argTransform is called with the context's RawArgs. 22 func (r *Router) Alias(name string, aliases, path []string, argTransform ArgTransformer) (*Command, error) { 23 if len(path) == 0 { 24 return nil, errors.New("no path supplied") 25 } 26 27 c, ok := r.cmds[path[0]] 28 if !ok { 29 return nil, ErrNilCommand 30 } 31 if len(path) > 1 { 32 for _, step := range path[1:] { 33 c, ok = c.subCmds[step] 34 if !ok { 35 return nil, ErrNilCommand 36 } 37 } 38 } 39 40 cmd := Command{ 41 Name: name, 42 Aliases: aliases, 43 44 Summary: fmt.Sprintf("Alias to `%v`:\n%v", strings.Join(path, " "), c.Summary), 45 Description: c.Description, 46 Usage: c.Usage, 47 48 Args: c.Args, 49 Flags: c.Flags, 50 51 Blacklistable: c.Blacklistable, 52 CustomPermissions: c.CustomPermissions, 53 Permissions: c.Permissions, 54 55 subCmds: c.subCmds, 56 57 GuildOnly: c.GuildOnly, 58 OwnerOnly: c.OwnerOnly, 59 Cooldown: c.Cooldown, 60 61 Command: func(ctx *Context) (err error) { 62 if argTransform != nil { 63 ctx.RawArgs = argTransform(ctx.RawArgs) 64 65 ctx.Args, err = shellwords.Parse(ctx.RawArgs) 66 if err != nil { 67 ctx.Args = strings.Split(ctx.RawArgs, " ") 68 } 69 } 70 71 return c.Command(ctx) 72 }, 73 } 74 75 return &cmd, nil 76 } 77 78 // AliasMust is a wrapper around Alias that panics if err is non-nil 79 func (r *Router) AliasMust(name string, aliases, path []string, argTransform ArgTransformer) *Command { 80 a, err := r.Alias(name, aliases, path, argTransform) 81 if err != nil { 82 panic(err) 83 } 84 return a 85 } 86 87 // DefaultArgTransformer adds a prefix or suffix (or both!) to the current args 88 func DefaultArgTransformer(prefix, suffix string) ArgTransformer { 89 t := strings.TrimSpace(fmt.Sprintf("%v $args %v", prefix, suffix)) 90 91 return func(args string) string { 92 return strings.Replace(t, "$args", args, -1) 93 } 94 }