command.go 930 字节
Newer Older
D
Derek Parker 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
package command

import (
	"fmt"
	"os"
)

type cmdfunc func() error

type Commands struct {
	cmds map[string]cmdfunc
}

func DebugCommands() *Commands {
	cmds := map[string]cmdfunc{
		"exit": exitFunc,
	}

	return &Commands{cmds}
}

D
Derek Parker 已提交
22 23 24 25
func (c *Commands) Register(cmdstr string, cf cmdfunc) {
	c.cmds[cmdstr] = cf
}

26 27 28
// Find will look up the command function for the given command input.
// If it cannot find the command it will defualt to noCmdAvailable().
// If the command is an empty string it will replay the last command.
D
Derek Parker 已提交
29 30 31
func (c *Commands) Find(cmdstr string) cmdfunc {
	cmd, ok := c.cmds[cmdstr]
	if !ok {
32 33 34 35
		if cmdstr == "" {
			return nullCommand
		}

D
Derek Parker 已提交
36 37 38
		return noCmdAvailable
	}

39 40 41
	// Allow <enter> to replay last command
	c.cmds[""] = cmd

D
Derek Parker 已提交
42 43 44 45 46 47 48 49 50 51 52
	return cmd
}

func noCmdAvailable() error {
	return fmt.Errorf("command not available")
}

func exitFunc() error {
	os.Exit(0)
	return nil
}
53 54 55 56

func nullCommand() error {
	return nil
}