command.go 966 字节
Newer Older
D
Derek Parker 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
package command

import (
	"fmt"
	"os"
)

type cmdfunc func() error

type Commands struct {
	cmds map[string]cmdfunc
}

14
// Returns a Commands struct with default commands defined.
D
Derek Parker 已提交
15 16 17
func DebugCommands() *Commands {
	cmds := map[string]cmdfunc{
		"exit": exitFunc,
18
		"":     nullCommand,
D
Derek Parker 已提交
19 20 21 22 23
	}

	return &Commands{cmds}
}

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

28 29 30
// 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 已提交
31 32 33 34 35 36
func (c *Commands) Find(cmdstr string) cmdfunc {
	cmd, ok := c.cmds[cmdstr]
	if !ok {
		return noCmdAvailable
	}

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

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

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

func exitFunc() error {
	os.Exit(0)
	return nil
}
51 52 53 54

func nullCommand() error {
	return nil
}