command.go 1.2 KB
Newer Older
D
Derek Parker 已提交
1 2
// Package command implements functions for responding to user
// input and dispatching to appropriate backend commands.
D
Derek Parker 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15
package command

import (
	"fmt"
	"os"
)

type cmdfunc func() error

type Commands struct {
	cmds map[string]cmdfunc
}

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

	return &Commands{cmds}
}

D
Derek Parker 已提交
26 27
// Register custom commands. Expects cf to be a func of type cmdfunc,
// returning only an error.
D
Derek Parker 已提交
28 29 30 31
func (c *Commands) Register(cmdstr string, cf cmdfunc) {
	c.cmds[cmdstr] = cf
}

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

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

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

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

func exitFunc() error {
	os.Exit(0)
	return nil
}
55 56 57 58

func nullCommand() error {
	return nil
}