-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.go
69 lines (62 loc) · 1.62 KB
/
script.go
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
65
66
67
68
69
package contract
import (
"errors"
"github.com/robertkrimen/otto"
"regexp"
)
type Script struct {
code string
scopes []string
descopes []string
}
func NewScript() Script {
return Script{}
}
func (s *Script) SetScopedVariable(variable string) error {
jsvarre, _ := regexp.Compile("^[^a-zA-Z_$]|[^\\w$]")
if jsvarre.MatchString(variable) {
return errors.New("Variable is not a valid javascript name")
}
if contains(s.scopes, variable) {
return errors.New("Variable has already been scoped")
}
if contains(s.descopes, variable) {
return errors.New("Variable has already been descoped")
}
s.scopes = append(s.scopes, variable)
return nil
}
func (s *Script) SetDescopedVariable(variable string) error {
jsvarre, _ := regexp.Compile("^[^a-zA-Z_$]|[^\\w$]")
if jsvarre.MatchString(variable) {
return errors.New("Variable is not a valid javascript name")
}
if contains(s.scopes, variable) {
return errors.New("Variable has already been scoped")
}
if contains(s.descopes, variable) {
return errors.New("Variable has already been descoped")
}
s.descopes = append(s.descopes, variable)
return nil
}
func (s *Script) SetScriptCode(code string) {
s.code = code
}
func (s *Script) Load(vm *otto.Otto) error {
if s.code == "" {
return errors.New("Script contains no code")
}
for _, variable := range s.scopes {
if exists(variable, vm) {
return errors.New("Global Namespace Conflict for object name: " + variable)
}
}
for _, variable := range s.descopes {
if exists(variable, vm) {
return errors.New("Global Namespace Conflict for object name: " + variable)
}
}
_, err := vm.Run(s.code)
return err
}