Adding simple require functionality to js (#58)

* Adding simple require functionality to js

* comment
This commit is contained in:
Craig Peterson 2017-03-27 16:01:12 -06:00 committed by GitHub
parent b0333f3244
commit efb8e9bbf4
5 changed files with 45 additions and 1 deletions

View file

@ -2,6 +2,8 @@ package js
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/StackExchange/dnscontrol/models"
@ -14,6 +16,8 @@ import (
func ExecuteJavascript(script string, devMode bool) (*models.DNSConfig, error) {
vm := otto.New()
vm.Set("require", require)
helperJs := GetHelpers(devMode)
// run helper script to prime vm and initialize variables
if _, err := vm.Run(helperJs); err != nil {
@ -44,3 +48,17 @@ func ExecuteJavascript(script string, devMode bool) (*models.DNSConfig, error) {
func GetHelpers(devMode bool) string {
return _escFSMustString(devMode, "/helpers.js")
}
func require(call otto.FunctionCall) otto.Value {
file := call.Argument(0).String()
fmt.Printf("requiring: %s\n", file)
data, err := ioutil.ReadFile(file)
if err != nil {
panic(err)
}
_, err = call.Otto.Run(string(data))
if err != nil {
panic(err)
}
return otto.TrueValue()
}

View file

@ -6,6 +6,7 @@ import (
"os"
"path/filepath"
"testing"
"unicode"
"github.com/StackExchange/dnscontrol/models"
)
@ -25,7 +26,8 @@ func TestParsedFiles(t *testing.T) {
t.Fatal(err)
}
for _, f := range files {
if filepath.Ext(f.Name()) != ".js" {
//run all js files that start with a number. Skip others.
if filepath.Ext(f.Name()) != ".js" || !unicode.IsNumber(rune(f.Name()[0])) {
continue
}
t.Log(f.Name(), "------")

View file

@ -0,0 +1,2 @@
require("js/parse_tests/import.js")

View file

@ -0,0 +1,19 @@
{
"registrars": [],
"dns_providers": [],
"domains": [
{
"name": "foo.com",
"registrar": "none",
"dnsProviders": {},
"records": [
{
"type": "A",
"name": "@",
"target": "1.2.3.4"
}
],
"keepunknown": false
}
]
}

3
js/parse_tests/import.js Normal file
View file

@ -0,0 +1,3 @@
D("foo.com","none",
A("@","1.2.3.4")
);