dnscontrol/pkg/js/js.go
Ed Bardsley 06ee4d6fb1 Verbose debug logging via the ConsolePrinter and printer package. (#404)
This:
 * adds a global -v flag for verbosity
 * refactors the "printer" package to have a DefaultPrinter and package
   functions that call it, similar to net/http's DefaultServeMux
 * adds printer tests
 * moves current users of Debugf to Printf
 * moves most users of the "log" package to use "printer"
 * demotes noticably noisy log messages to "Debugf", like "IGNORE"-
   and "NO_PURGE"-related messages
2018-10-08 16:10:44 -04:00

88 lines
2.1 KiB
Go

package js
import (
"encoding/json"
"io/ioutil"
"github.com/StackExchange/dnscontrol/models"
"github.com/StackExchange/dnscontrol/pkg/printer"
"github.com/StackExchange/dnscontrol/pkg/transform"
"github.com/robertkrimen/otto"
// load underscore js into vm by default
_ "github.com/robertkrimen/otto/underscore" // required by otto
)
// ExecuteJavascript accepts a javascript string and runs it, returning the resulting dnsConfig.
func ExecuteJavascript(script string, devMode bool) (*models.DNSConfig, error) {
vm := otto.New()
vm.Set("require", require)
vm.Set("REV", reverse)
helperJs := GetHelpers(devMode)
// run helper script to prime vm and initialize variables
if _, err := vm.Run(helperJs); err != nil {
return nil, err
}
// run user script
if _, err := vm.Run(script); err != nil {
return nil, err
}
// export conf as string and unmarshal
value, err := vm.Run(`JSON.stringify(conf)`)
if err != nil {
return nil, err
}
str, err := value.ToString()
if err != nil {
return nil, err
}
conf := &models.DNSConfig{}
if err = json.Unmarshal([]byte(str), conf); err != nil {
return nil, err
}
return conf, nil
}
// GetHelpers returns the filename of helpers.js, or the esc'ed version.
func GetHelpers(devMode bool) string {
return _escFSMustString(devMode, "/helpers.js")
}
func require(call otto.FunctionCall) otto.Value {
if len(call.ArgumentList) != 1 {
throw(call.Otto, "require takes exactly one argument")
}
file := call.Argument(0).String()
printer.Debugf("requiring: %s\n", file)
data, err := ioutil.ReadFile(file)
if err != nil {
throw(call.Otto, err.Error())
}
_, err = call.Otto.Run(string(data))
if err != nil {
throw(call.Otto, err.Error())
}
return otto.TrueValue()
}
func throw(vm *otto.Otto, str string) {
panic(vm.MakeCustomError("Error", str))
}
func reverse(call otto.FunctionCall) otto.Value {
if len(call.ArgumentList) != 1 {
throw(call.Otto, "REV takes exactly one argument")
}
dom := call.Argument(0).String()
rev, err := transform.ReverseDomainName(dom)
if err != nil {
throw(call.Otto, err.Error())
}
v, _ := otto.ToValue(rev)
return v
}