Skip to content

Commit

Permalink
refactor: move external command checks into commands lib (#198)
Browse files Browse the repository at this point in the history
* refactor: move environment-based command restrictions to be stored with the command itself
  • Loading branch information
aschmahmann authored Aug 4, 2020
1 parent 0cd468a commit df39339
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
34 changes: 34 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,39 @@ type Command struct {
// simple typo in a sub command will invoke the parent command and may
// end up returning a cryptic error to the user.
Subcommands map[string]*Command

// NoRemote denotes that a command cannot be executed in a remote environment
NoRemote bool

// NoLocal denotes that a command cannot be executed in a local environment
NoLocal bool

// Extra contains a set of other command-specific parameters
Extra *Extra
}

// Extra is a set of tag information for a command
type Extra struct {
m map[interface{}]interface{}
}

func (e *Extra) SetValue(key, value interface{}) *Extra {
if e == nil {
e = &Extra{}
}
if e.m == nil {
e.m = make(map[interface{}]interface{})
}
e.m[key] = value
return e
}

func (e *Extra) GetValue(key interface{}) (interface{}, bool) {
if e == nil || e.m == nil {
return nil, false
}
val, found := e.m[key]
return val, found
}

var (
Expand Down Expand Up @@ -141,6 +174,7 @@ func (c *Command) call(req *Request, re ResponseEmitter, env Environment) error
}

// Resolve returns the subcommands at the given path
// The returned set of subcommands starts with this command and therefore is always at least size 1
func (c *Command) Resolve(pth []string) ([]*Command, error) {
cmds := make([]*Command, len(pth)+1)
cmds[0] = c
Expand Down
13 changes: 12 additions & 1 deletion http/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,19 @@ func parseRequest(r *http.Request, root *cmds.Command) (*cmds.Request, error) {
getPath = pth[:len(pth)-1]
)

cmd, err := root.Get(getPath)
cmdPath, err := root.Resolve(getPath)
if err != nil {
// 404 if there is no command at that path
return nil, ErrNotFound
}

for _, c := range cmdPath {
if c.NoRemote {
return nil, ErrNotFound
}
}

cmd := cmdPath[len(cmdPath)-1]
sub := cmd.Subcommands[pth[len(pth)-1]]

if sub == nil {
Expand All @@ -49,6 +56,10 @@ func parseRequest(r *http.Request, root *cmds.Command) (*cmds.Request, error) {
cmd = sub
}

if cmd.NoRemote {
return nil, ErrNotFound
}

opts, stringArgs2 := parseOptions(r)
optDefs, err := root.GetOptions(pth)
if err != nil {
Expand Down

0 comments on commit df39339

Please sign in to comment.