cmd, console: split off the console into a reusable package
This commit is contained in:
22
internal/jsre/bignumber_js.go
Normal file
22
internal/jsre/bignumber_js.go
Normal file
File diff suppressed because one or more lines are too long
74
internal/jsre/completion.go
Normal file
74
internal/jsre/completion.go
Normal file
@ -0,0 +1,74 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package jsre
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/robertkrimen/otto"
|
||||
)
|
||||
|
||||
// CompleteKeywords returns potential continuations for the given line. Since line is
|
||||
// evaluated, callers need to make sure that evaluating line does not have side effects.
|
||||
func (jsre *JSRE) CompleteKeywords(line string) []string {
|
||||
var results []string
|
||||
jsre.Do(func(vm *otto.Otto) {
|
||||
results = getCompletions(vm, line)
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
func getCompletions(vm *otto.Otto, line string) (results []string) {
|
||||
parts := strings.Split(line, ".")
|
||||
objRef := "this"
|
||||
prefix := line
|
||||
if len(parts) > 1 {
|
||||
objRef = strings.Join(parts[0:len(parts)-1], ".")
|
||||
prefix = parts[len(parts)-1]
|
||||
}
|
||||
|
||||
obj, _ := vm.Object(objRef)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
iterOwnAndConstructorKeys(vm, obj, func(k string) {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
if objRef == "this" {
|
||||
results = append(results, k)
|
||||
} else {
|
||||
results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Append opening parenthesis (for functions) or dot (for objects)
|
||||
// if the line itself is the only completion.
|
||||
if len(results) == 1 && results[0] == line {
|
||||
obj, _ := vm.Object(line)
|
||||
if obj != nil {
|
||||
if obj.Class() == "Function" {
|
||||
results[0] += "("
|
||||
} else {
|
||||
results[0] += "."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(results)
|
||||
return results
|
||||
}
|
88
internal/jsre/completion_test.go
Normal file
88
internal/jsre/completion_test.go
Normal file
@ -0,0 +1,88 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package jsre
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCompleteKeywords(t *testing.T) {
|
||||
re := New("", os.Stdout)
|
||||
re.Run(`
|
||||
function theClass() {
|
||||
this.foo = 3;
|
||||
this.gazonk = {xyz: 4};
|
||||
}
|
||||
theClass.prototype.someMethod = function () {};
|
||||
var x = new theClass();
|
||||
var y = new theClass();
|
||||
y.someMethod = function override() {};
|
||||
`)
|
||||
|
||||
var tests = []struct {
|
||||
input string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
input: "x",
|
||||
want: []string{"x."},
|
||||
},
|
||||
{
|
||||
input: "x.someMethod",
|
||||
want: []string{"x.someMethod("},
|
||||
},
|
||||
{
|
||||
input: "x.",
|
||||
want: []string{
|
||||
"x.constructor",
|
||||
"x.foo",
|
||||
"x.gazonk",
|
||||
"x.someMethod",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "y.",
|
||||
want: []string{
|
||||
"y.constructor",
|
||||
"y.foo",
|
||||
"y.gazonk",
|
||||
"y.someMethod",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "x.gazonk.",
|
||||
want: []string{
|
||||
"x.gazonk.constructor",
|
||||
"x.gazonk.hasOwnProperty",
|
||||
"x.gazonk.isPrototypeOf",
|
||||
"x.gazonk.propertyIsEnumerable",
|
||||
"x.gazonk.toLocaleString",
|
||||
"x.gazonk.toString",
|
||||
"x.gazonk.valueOf",
|
||||
"x.gazonk.xyz",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
cs := re.CompleteKeywords(test.input)
|
||||
if !reflect.DeepEqual(cs, test.want) {
|
||||
t.Errorf("wrong completions for %q\ngot %v\nwant %v", test.input, cs, test.want)
|
||||
}
|
||||
}
|
||||
}
|
15964
internal/jsre/ethereum_js.go
Normal file
15964
internal/jsre/ethereum_js.go
Normal file
File diff suppressed because it is too large
Load Diff
327
internal/jsre/jsre.go
Normal file
327
internal/jsre/jsre.go
Normal file
@ -0,0 +1,327 @@
|
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package jsre provides execution environment for JavaScript.
|
||||
package jsre
|
||||
|
||||
import (
|
||||
crand "crypto/rand"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/robertkrimen/otto"
|
||||
)
|
||||
|
||||
/*
|
||||
JSRE is a generic JS runtime environment embedding the otto JS interpreter.
|
||||
It provides some helper functions to
|
||||
- load code from files
|
||||
- run code snippets
|
||||
- require libraries
|
||||
- bind native go objects
|
||||
*/
|
||||
type JSRE struct {
|
||||
assetPath string
|
||||
output io.Writer
|
||||
evalQueue chan *evalReq
|
||||
stopEventLoop chan bool
|
||||
loopWg sync.WaitGroup
|
||||
}
|
||||
|
||||
// jsTimer is a single timer instance with a callback function
|
||||
type jsTimer struct {
|
||||
timer *time.Timer
|
||||
duration time.Duration
|
||||
interval bool
|
||||
call otto.FunctionCall
|
||||
}
|
||||
|
||||
// evalReq is a serialized vm execution request processed by runEventLoop.
|
||||
type evalReq struct {
|
||||
fn func(vm *otto.Otto)
|
||||
done chan bool
|
||||
}
|
||||
|
||||
// runtime must be stopped with Stop() after use and cannot be used after stopping
|
||||
func New(assetPath string, output io.Writer) *JSRE {
|
||||
re := &JSRE{
|
||||
assetPath: assetPath,
|
||||
output: output,
|
||||
evalQueue: make(chan *evalReq),
|
||||
stopEventLoop: make(chan bool),
|
||||
}
|
||||
re.loopWg.Add(1)
|
||||
go re.runEventLoop()
|
||||
re.Set("loadScript", re.loadScript)
|
||||
re.Set("inspect", prettyPrintJS)
|
||||
return re
|
||||
}
|
||||
|
||||
// randomSource returns a pseudo random value generator.
|
||||
func randomSource() *rand.Rand {
|
||||
bytes := make([]byte, 8)
|
||||
seed := time.Now().UnixNano()
|
||||
if _, err := crand.Read(bytes); err == nil {
|
||||
seed = int64(binary.LittleEndian.Uint64(bytes))
|
||||
}
|
||||
|
||||
src := rand.NewSource(seed)
|
||||
return rand.New(src)
|
||||
}
|
||||
|
||||
// This function runs the main event loop from a goroutine that is started
|
||||
// when JSRE is created. Use Stop() before exiting to properly stop it.
|
||||
// The event loop processes vm access requests from the evalQueue in a
|
||||
// serialized way and calls timer callback functions at the appropriate time.
|
||||
|
||||
// Exported functions always access the vm through the event queue. You can
|
||||
// call the functions of the otto vm directly to circumvent the queue. These
|
||||
// functions should be used if and only if running a routine that was already
|
||||
// called from JS through an RPC call.
|
||||
func (self *JSRE) runEventLoop() {
|
||||
vm := otto.New()
|
||||
r := randomSource()
|
||||
vm.SetRandomSource(r.Float64)
|
||||
|
||||
registry := map[*jsTimer]*jsTimer{}
|
||||
ready := make(chan *jsTimer)
|
||||
|
||||
newTimer := func(call otto.FunctionCall, interval bool) (*jsTimer, otto.Value) {
|
||||
delay, _ := call.Argument(1).ToInteger()
|
||||
if 0 >= delay {
|
||||
delay = 1
|
||||
}
|
||||
timer := &jsTimer{
|
||||
duration: time.Duration(delay) * time.Millisecond,
|
||||
call: call,
|
||||
interval: interval,
|
||||
}
|
||||
registry[timer] = timer
|
||||
|
||||
timer.timer = time.AfterFunc(timer.duration, func() {
|
||||
ready <- timer
|
||||
})
|
||||
|
||||
value, err := call.Otto.ToValue(timer)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return timer, value
|
||||
}
|
||||
|
||||
setTimeout := func(call otto.FunctionCall) otto.Value {
|
||||
_, value := newTimer(call, false)
|
||||
return value
|
||||
}
|
||||
|
||||
setInterval := func(call otto.FunctionCall) otto.Value {
|
||||
_, value := newTimer(call, true)
|
||||
return value
|
||||
}
|
||||
|
||||
clearTimeout := func(call otto.FunctionCall) otto.Value {
|
||||
timer, _ := call.Argument(0).Export()
|
||||
if timer, ok := timer.(*jsTimer); ok {
|
||||
timer.timer.Stop()
|
||||
delete(registry, timer)
|
||||
}
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
vm.Set("_setTimeout", setTimeout)
|
||||
vm.Set("_setInterval", setInterval)
|
||||
vm.Run(`var setTimeout = function(args) {
|
||||
if (arguments.length < 1) {
|
||||
throw TypeError("Failed to execute 'setTimeout': 1 argument required, but only 0 present.");
|
||||
}
|
||||
return _setTimeout.apply(this, arguments);
|
||||
}`)
|
||||
vm.Run(`var setInterval = function(args) {
|
||||
if (arguments.length < 1) {
|
||||
throw TypeError("Failed to execute 'setInterval': 1 argument required, but only 0 present.");
|
||||
}
|
||||
return _setInterval.apply(this, arguments);
|
||||
}`)
|
||||
vm.Set("clearTimeout", clearTimeout)
|
||||
vm.Set("clearInterval", clearTimeout)
|
||||
|
||||
var waitForCallbacks bool
|
||||
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case timer := <-ready:
|
||||
// execute callback, remove/reschedule the timer
|
||||
var arguments []interface{}
|
||||
if len(timer.call.ArgumentList) > 2 {
|
||||
tmp := timer.call.ArgumentList[2:]
|
||||
arguments = make([]interface{}, 2+len(tmp))
|
||||
for i, value := range tmp {
|
||||
arguments[i+2] = value
|
||||
}
|
||||
} else {
|
||||
arguments = make([]interface{}, 1)
|
||||
}
|
||||
arguments[0] = timer.call.ArgumentList[0]
|
||||
_, err := vm.Call(`Function.call.call`, nil, arguments...)
|
||||
if err != nil {
|
||||
fmt.Println("js error:", err, arguments)
|
||||
}
|
||||
|
||||
_, inreg := registry[timer] // when clearInterval is called from within the callback don't reset it
|
||||
if timer.interval && inreg {
|
||||
timer.timer.Reset(timer.duration)
|
||||
} else {
|
||||
delete(registry, timer)
|
||||
if waitForCallbacks && (len(registry) == 0) {
|
||||
break loop
|
||||
}
|
||||
}
|
||||
case req := <-self.evalQueue:
|
||||
// run the code, send the result back
|
||||
req.fn(vm)
|
||||
close(req.done)
|
||||
if waitForCallbacks && (len(registry) == 0) {
|
||||
break loop
|
||||
}
|
||||
case waitForCallbacks = <-self.stopEventLoop:
|
||||
if !waitForCallbacks || (len(registry) == 0) {
|
||||
break loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, timer := range registry {
|
||||
timer.timer.Stop()
|
||||
delete(registry, timer)
|
||||
}
|
||||
|
||||
self.loopWg.Done()
|
||||
}
|
||||
|
||||
// Do executes the given function on the JS event loop.
|
||||
func (self *JSRE) Do(fn func(*otto.Otto)) {
|
||||
done := make(chan bool)
|
||||
req := &evalReq{fn, done}
|
||||
self.evalQueue <- req
|
||||
<-done
|
||||
}
|
||||
|
||||
// stops the event loop before exit, optionally waits for all timers to expire
|
||||
func (self *JSRE) Stop(waitForCallbacks bool) {
|
||||
self.stopEventLoop <- waitForCallbacks
|
||||
self.loopWg.Wait()
|
||||
}
|
||||
|
||||
// Exec(file) loads and runs the contents of a file
|
||||
// if a relative path is given, the jsre's assetPath is used
|
||||
func (self *JSRE) Exec(file string) error {
|
||||
code, err := ioutil.ReadFile(common.AbsolutePath(self.assetPath, file))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var script *otto.Script
|
||||
self.Do(func(vm *otto.Otto) {
|
||||
script, err = vm.Compile(file, code)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = vm.Run(script)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Bind assigns value v to a variable in the JS environment
|
||||
// This method is deprecated, use Set.
|
||||
func (self *JSRE) Bind(name string, v interface{}) error {
|
||||
return self.Set(name, v)
|
||||
}
|
||||
|
||||
// Run runs a piece of JS code.
|
||||
func (self *JSRE) Run(code string) (v otto.Value, err error) {
|
||||
self.Do(func(vm *otto.Otto) { v, err = vm.Run(code) })
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Get returns the value of a variable in the JS environment.
|
||||
func (self *JSRE) Get(ns string) (v otto.Value, err error) {
|
||||
self.Do(func(vm *otto.Otto) { v, err = vm.Get(ns) })
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Set assigns value v to a variable in the JS environment.
|
||||
func (self *JSRE) Set(ns string, v interface{}) (err error) {
|
||||
self.Do(func(vm *otto.Otto) { err = vm.Set(ns, v) })
|
||||
return err
|
||||
}
|
||||
|
||||
// loadScript executes a JS script from inside the currently executing JS code.
|
||||
func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value {
|
||||
file, err := call.Argument(0).ToString()
|
||||
if err != nil {
|
||||
// TODO: throw exception
|
||||
return otto.FalseValue()
|
||||
}
|
||||
file = common.AbsolutePath(self.assetPath, file)
|
||||
source, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
// TODO: throw exception
|
||||
return otto.FalseValue()
|
||||
}
|
||||
if _, err := compileAndRun(call.Otto, file, source); err != nil {
|
||||
// TODO: throw exception
|
||||
fmt.Println("err:", err)
|
||||
return otto.FalseValue()
|
||||
}
|
||||
// TODO: return evaluation result
|
||||
return otto.TrueValue()
|
||||
}
|
||||
|
||||
// Evaluate executes code and pretty prints the result to the specified output
|
||||
// stream.
|
||||
func (self *JSRE) Evaluate(code string, w io.Writer) error {
|
||||
var fail error
|
||||
|
||||
self.Do(func(vm *otto.Otto) {
|
||||
val, err := vm.Run(code)
|
||||
if err != nil {
|
||||
fail = err
|
||||
} else {
|
||||
prettyPrint(vm, val, w)
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
})
|
||||
return fail
|
||||
}
|
||||
|
||||
// Compile compiles and then runs a piece of JS code.
|
||||
func (self *JSRE) Compile(filename string, src interface{}) (err error) {
|
||||
self.Do(func(vm *otto.Otto) { _, err = compileAndRun(vm, filename, src) })
|
||||
return err
|
||||
}
|
||||
|
||||
func compileAndRun(vm *otto.Otto, filename string, src interface{}) (otto.Value, error) {
|
||||
script, err := vm.Compile(filename, src)
|
||||
if err != nil {
|
||||
return otto.Value{}, err
|
||||
}
|
||||
return vm.Run(script)
|
||||
}
|
137
internal/jsre/jsre_test.go
Normal file
137
internal/jsre/jsre_test.go
Normal file
@ -0,0 +1,137 @@
|
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package jsre
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/robertkrimen/otto"
|
||||
)
|
||||
|
||||
type testNativeObjectBinding struct{}
|
||||
|
||||
type msg struct {
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value {
|
||||
m, err := call.Argument(0).ToString()
|
||||
if err != nil {
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
v, _ := call.Otto.ToValue(&msg{m})
|
||||
return v
|
||||
}
|
||||
|
||||
func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) {
|
||||
dir, err := ioutil.TempDir("", "jsre-test")
|
||||
if err != nil {
|
||||
t.Fatal("cannot create temporary directory:", err)
|
||||
}
|
||||
if testjs != "" {
|
||||
if err := ioutil.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil {
|
||||
t.Fatal("cannot create test.js:", err)
|
||||
}
|
||||
}
|
||||
return New(dir, os.Stdout), dir
|
||||
}
|
||||
|
||||
func TestExec(t *testing.T) {
|
||||
jsre, dir := newWithTestJS(t, `msg = "testMsg"`)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
err := jsre.Exec("test.js")
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
val, err := jsre.Run("msg")
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
if !val.IsString() {
|
||||
t.Errorf("expected string value, got %v", val)
|
||||
}
|
||||
exp := "testMsg"
|
||||
got, _ := val.ToString()
|
||||
if exp != got {
|
||||
t.Errorf("expected '%v', got '%v'", exp, got)
|
||||
}
|
||||
jsre.Stop(false)
|
||||
}
|
||||
|
||||
func TestNatto(t *testing.T) {
|
||||
jsre, dir := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
err := jsre.Exec("test.js")
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
val, err := jsre.Run("msg")
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
if !val.IsString() {
|
||||
t.Errorf("expected string value, got %v", val)
|
||||
}
|
||||
exp := "testMsg"
|
||||
got, _ := val.ToString()
|
||||
if exp != got {
|
||||
t.Errorf("expected '%v', got '%v'", exp, got)
|
||||
}
|
||||
jsre.Stop(false)
|
||||
}
|
||||
|
||||
func TestBind(t *testing.T) {
|
||||
jsre := New("", os.Stdout)
|
||||
defer jsre.Stop(false)
|
||||
|
||||
jsre.Bind("no", &testNativeObjectBinding{})
|
||||
|
||||
_, err := jsre.Run(`no.TestMethod("testMsg")`)
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadScript(t *testing.T) {
|
||||
jsre, dir := newWithTestJS(t, `msg = "testMsg"`)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
_, err := jsre.Run(`loadScript("test.js")`)
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
val, err := jsre.Run("msg")
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
if !val.IsString() {
|
||||
t.Errorf("expected string value, got %v", val)
|
||||
}
|
||||
exp := "testMsg"
|
||||
got, _ := val.ToString()
|
||||
if exp != got {
|
||||
t.Errorf("expected '%v', got '%v'", exp, got)
|
||||
}
|
||||
jsre.Stop(false)
|
||||
}
|
262
internal/jsre/pretty.go
Normal file
262
internal/jsre/pretty.go
Normal file
@ -0,0 +1,262 @@
|
||||
// Copyright 2015 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package jsre
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/robertkrimen/otto"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPrettyPrintLevel = 3
|
||||
indentString = " "
|
||||
)
|
||||
|
||||
var (
|
||||
FunctionColor = color.New(color.FgMagenta).SprintfFunc()
|
||||
SpecialColor = color.New(color.Bold).SprintfFunc()
|
||||
NumberColor = color.New(color.FgRed).SprintfFunc()
|
||||
StringColor = color.New(color.FgGreen).SprintfFunc()
|
||||
)
|
||||
|
||||
// these fields are hidden when printing objects.
|
||||
var boringKeys = map[string]bool{
|
||||
"valueOf": true,
|
||||
"toString": true,
|
||||
"toLocaleString": true,
|
||||
"hasOwnProperty": true,
|
||||
"isPrototypeOf": true,
|
||||
"propertyIsEnumerable": true,
|
||||
"constructor": true,
|
||||
}
|
||||
|
||||
// prettyPrint writes value to standard output.
|
||||
func prettyPrint(vm *otto.Otto, value otto.Value, w io.Writer) {
|
||||
ppctx{vm: vm, w: w}.printValue(value, 0, false)
|
||||
}
|
||||
|
||||
func prettyPrintJS(call otto.FunctionCall, w io.Writer) otto.Value {
|
||||
for _, v := range call.ArgumentList {
|
||||
prettyPrint(call.Otto, v, w)
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
type ppctx struct {
|
||||
vm *otto.Otto
|
||||
w io.Writer
|
||||
}
|
||||
|
||||
func (ctx ppctx) indent(level int) string {
|
||||
return strings.Repeat(indentString, level)
|
||||
}
|
||||
|
||||
func (ctx ppctx) printValue(v otto.Value, level int, inArray bool) {
|
||||
switch {
|
||||
case v.IsObject():
|
||||
ctx.printObject(v.Object(), level, inArray)
|
||||
case v.IsNull():
|
||||
fmt.Fprint(ctx.w, SpecialColor("null"))
|
||||
case v.IsUndefined():
|
||||
fmt.Fprint(ctx.w, SpecialColor("undefined"))
|
||||
case v.IsString():
|
||||
s, _ := v.ToString()
|
||||
fmt.Fprint(ctx.w, StringColor("%q", s))
|
||||
case v.IsBoolean():
|
||||
b, _ := v.ToBoolean()
|
||||
fmt.Fprint(ctx.w, SpecialColor("%t", b))
|
||||
case v.IsNaN():
|
||||
fmt.Fprint(ctx.w, NumberColor("NaN"))
|
||||
case v.IsNumber():
|
||||
s, _ := v.ToString()
|
||||
fmt.Fprint(ctx.w, NumberColor("%s", s))
|
||||
default:
|
||||
fmt.Fprint(ctx.w, "<unprintable>")
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
|
||||
switch obj.Class() {
|
||||
case "Array":
|
||||
lv, _ := obj.Get("length")
|
||||
len, _ := lv.ToInteger()
|
||||
if len == 0 {
|
||||
fmt.Fprintf(ctx.w, "[]")
|
||||
return
|
||||
}
|
||||
if level > maxPrettyPrintLevel {
|
||||
fmt.Fprint(ctx.w, "[...]")
|
||||
return
|
||||
}
|
||||
fmt.Fprint(ctx.w, "[")
|
||||
for i := int64(0); i < len; i++ {
|
||||
el, err := obj.Get(strconv.FormatInt(i, 10))
|
||||
if err == nil {
|
||||
ctx.printValue(el, level+1, true)
|
||||
}
|
||||
if i < len-1 {
|
||||
fmt.Fprintf(ctx.w, ", ")
|
||||
}
|
||||
}
|
||||
fmt.Fprint(ctx.w, "]")
|
||||
|
||||
case "Object":
|
||||
// Print values from bignumber.js as regular numbers.
|
||||
if ctx.isBigNumber(obj) {
|
||||
fmt.Fprint(ctx.w, NumberColor("%s", toString(obj)))
|
||||
return
|
||||
}
|
||||
// Otherwise, print all fields indented, but stop if we're too deep.
|
||||
keys := ctx.fields(obj)
|
||||
if len(keys) == 0 {
|
||||
fmt.Fprint(ctx.w, "{}")
|
||||
return
|
||||
}
|
||||
if level > maxPrettyPrintLevel {
|
||||
fmt.Fprint(ctx.w, "{...}")
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(ctx.w, "{")
|
||||
for i, k := range keys {
|
||||
v, _ := obj.Get(k)
|
||||
fmt.Fprintf(ctx.w, "%s%s: ", ctx.indent(level+1), k)
|
||||
ctx.printValue(v, level+1, false)
|
||||
if i < len(keys)-1 {
|
||||
fmt.Fprintf(ctx.w, ",")
|
||||
}
|
||||
fmt.Fprintln(ctx.w)
|
||||
}
|
||||
if inArray {
|
||||
level--
|
||||
}
|
||||
fmt.Fprintf(ctx.w, "%s}", ctx.indent(level))
|
||||
|
||||
case "Function":
|
||||
// Use toString() to display the argument list if possible.
|
||||
if robj, err := obj.Call("toString"); err != nil {
|
||||
fmt.Fprint(ctx.w, FunctionColor("function()"))
|
||||
} else {
|
||||
desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
|
||||
desc = strings.Replace(desc, " (", "(", 1)
|
||||
fmt.Fprint(ctx.w, FunctionColor("%s", desc))
|
||||
}
|
||||
|
||||
case "RegExp":
|
||||
fmt.Fprint(ctx.w, StringColor("%s", toString(obj)))
|
||||
|
||||
default:
|
||||
if v, _ := obj.Get("toString"); v.IsFunction() && level <= maxPrettyPrintLevel {
|
||||
s, _ := obj.Call("toString")
|
||||
fmt.Fprintf(ctx.w, "<%s %s>", obj.Class(), s.String())
|
||||
} else {
|
||||
fmt.Fprintf(ctx.w, "<%s>", obj.Class())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx ppctx) fields(obj *otto.Object) []string {
|
||||
var (
|
||||
vals, methods []string
|
||||
seen = make(map[string]bool)
|
||||
)
|
||||
add := func(k string) {
|
||||
if seen[k] || boringKeys[k] || strings.HasPrefix(k, "_") {
|
||||
return
|
||||
}
|
||||
seen[k] = true
|
||||
if v, _ := obj.Get(k); v.IsFunction() {
|
||||
methods = append(methods, k)
|
||||
} else {
|
||||
vals = append(vals, k)
|
||||
}
|
||||
}
|
||||
iterOwnAndConstructorKeys(ctx.vm, obj, add)
|
||||
sort.Strings(vals)
|
||||
sort.Strings(methods)
|
||||
return append(vals, methods...)
|
||||
}
|
||||
|
||||
func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
|
||||
seen := make(map[string]bool)
|
||||
iterOwnKeys(vm, obj, func(prop string) {
|
||||
seen[prop] = true
|
||||
f(prop)
|
||||
})
|
||||
if cp := constructorPrototype(obj); cp != nil {
|
||||
iterOwnKeys(vm, cp, func(prop string) {
|
||||
if !seen[prop] {
|
||||
f(prop)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
|
||||
Object, _ := vm.Object("Object")
|
||||
rv, _ := Object.Call("getOwnPropertyNames", obj.Value())
|
||||
gv, _ := rv.Export()
|
||||
switch gv := gv.(type) {
|
||||
case []interface{}:
|
||||
for _, v := range gv {
|
||||
f(v.(string))
|
||||
}
|
||||
case []string:
|
||||
for _, v := range gv {
|
||||
f(v)
|
||||
}
|
||||
default:
|
||||
panic(fmt.Errorf("Object.getOwnPropertyNames returned unexpected type %T", gv))
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx ppctx) isBigNumber(v *otto.Object) bool {
|
||||
// Handle numbers with custom constructor.
|
||||
if v, _ := v.Get("constructor"); v.Object() != nil {
|
||||
if strings.HasPrefix(toString(v.Object()), "function BigNumber") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// Handle default constructor.
|
||||
BigNumber, _ := ctx.vm.Object("BigNumber.prototype")
|
||||
if BigNumber == nil {
|
||||
return false
|
||||
}
|
||||
bv, _ := BigNumber.Call("isPrototypeOf", v)
|
||||
b, _ := bv.ToBoolean()
|
||||
return b
|
||||
}
|
||||
|
||||
func toString(obj *otto.Object) string {
|
||||
s, _ := obj.Call("toString")
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func constructorPrototype(obj *otto.Object) *otto.Object {
|
||||
if v, _ := obj.Get("constructor"); v.Object() != nil {
|
||||
if v, _ = v.Object().Get("prototype"); v.Object() != nil {
|
||||
return v.Object()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user