Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
What's new
10
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Open sidebar
dms3
go-dms3
Commits
dd2a1050
Commit
dd2a1050
authored
Oct 08, 2014
by
Matt Bell
Committed by
Juan Batiz-Benet
Oct 20, 2014
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
commands: Implemented Command
parent
ac62d13e
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
85 additions
and
0 deletions
+85
-0
commands/command.go
commands/command.go
+85
-0
No files found.
commands/command.go
0 → 100644
View file @
dd2a1050
package
commands
import
(
"fmt"
"strings"
"reflect"
)
type
Command
struct
{
Help
string
Options
[]
Option
f
func
(
*
Request
)
(
interface
{},
error
)
subcommands
map
[
string
]
*
Command
}
// Register adds a subcommand
func
(
c
*
Command
)
Register
(
id
string
,
sub
*
Command
)
error
{
if
c
.
subcommands
==
nil
{
c
.
subcommands
=
make
(
map
[
string
]
*
Command
)
}
// TODO: check for duplicate option names
if
_
,
ok
:=
c
.
subcommands
[
id
];
ok
{
return
fmt
.
Errorf
(
"There is already a subcommand registered with id '%s'"
,
id
)
}
c
.
subcommands
[
id
]
=
sub
return
nil
}
// Call invokes the command at the given subcommand path
func
(
c
*
Command
)
Call
(
path
[]
string
,
req
*
Request
)
(
interface
{},
error
)
{
options
:=
make
([]
Option
,
len
(
c
.
Options
))
copy
(
options
,
c
.
Options
)
cmd
:=
c
if
path
!=
nil
{
for
i
,
id
:=
range
path
{
cmd
=
c
.
Sub
(
id
)
if
cmd
==
nil
{
pathS
:=
strings
.
Join
(
path
[
0
:
i
],
"/"
)
return
nil
,
fmt
.
Errorf
(
"Undefined command: '%s'"
,
pathS
)
}
options
=
append
(
options
,
cmd
.
Options
...
)
}
}
optionsMap
:=
make
(
map
[
string
]
Option
)
for
_
,
opt
:=
range
options
{
for
_
,
name
:=
range
opt
.
Names
{
optionsMap
[
name
]
=
opt
}
}
for
k
,
v
:=
range
req
.
options
{
opt
,
ok
:=
optionsMap
[
k
]
if
!
ok
{
return
nil
,
fmt
.
Errorf
(
"Unrecognized command option: '%s'"
,
k
)
}
for
_
,
name
:=
range
opt
.
Names
{
if
_
,
ok
=
req
.
options
[
name
];
name
!=
k
&&
ok
{
return
nil
,
fmt
.
Errorf
(
"Duplicate command options were provided ('%s' and '%s')"
,
k
,
name
)
}
}
kind
:=
reflect
.
TypeOf
(
v
)
.
Kind
()
if
kind
!=
opt
.
Type
{
return
nil
,
fmt
.
Errorf
(
"Option '%s' should be type '%s', but got type '%s'"
,
k
,
opt
.
Type
.
String
(),
kind
.
String
())
}
}
return
cmd
.
f
(
req
)
}
// Sub returns the subcommand with the given id
func
(
c
*
Command
)
Sub
(
id
string
)
*
Command
{
return
c
.
subcommands
[
id
]
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment