Repository navigation
Expand file tree
/
Copy pathcommand.go
More file actions
64 lines (58 loc) · 1.72 KB
/
Copy pathcommand.go
File metadata and controls
64 lines (58 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package gosh
import (
"fmt"
"reflect"
"runtime"
"strings"
"unicode"
)
// Call associates code with a name, so that can be invoked from script or CLI
type Call struct {
Name string
Func reflect.Value
Exported bool
Tool ToolSpec
}
// Calls reference all code that can be invoked from script or CLI
var Calls map[string]Call = make(map[string]Call)
// Register associates a Go function with its name, so that it can be
// invoked via scripts or the command line.
func Register(funcs ...interface{}) interface{} {
for _, f := range funcs {
rv := reflect.ValueOf(f)
if rv.Kind() != reflect.Func {
panic(fmt.Sprintf("Cannot create go call from '%+v'", f))
}
longName := runtime.FuncForPC(rv.Pointer()).Name()
shortName := longName[strings.LastIndex(longName, ".")+1:]
Cmd(shortName, f)
}
return nil
}
// Cmd associates a Go function with a name, so that it can be invoked
// via scripts or the command line.
func Cmd(name string, call interface{}) interface{} {
return registerCall(name, call)
}
func registerCall(name string, call interface{}, options ...ToolOption) interface{} {
if name == "" {
panic("Cannot create call with empty name")
}
rv := reflect.ValueOf(call)
if rv.Kind() != reflect.Func {
panic(fmt.Sprintf("Cannot create go call from '%s'", name))
}
key := strings.ToLower(name)
if _, found := Calls[key]; found {
panic(fmt.Sprintf("Cannot create more than one call named '%s'", name))
}
exported := unicode.IsUpper([]rune(name)[0])
tool := minimalToolSpec(name, exported)
for _, option := range options {
option(&tool)
}
ensureLegacyInputParam(&tool, rv.Type())
inferParamTypes(&tool, rv.Type())
Calls[key] = Call{Name: name, Func: rv, Exported: exported, Tool: tool}
return nil
}