func NewOttoGrouper() *OttoGrouper { return &OttoGrouper{ OutputChannel: make(DocumentChannel), Otto: otto.New(), groupValues: make(map[string]ExpressionStatsMap), groupDocs: make(map[string]Document)} }
func main() { flag.Parse() var script []byte var err error filename := flag.Arg(0) if filename == "" || filename == "-" { script, err = ioutil.ReadAll(os.Stdin) if err != nil { fmt.Printf("Can't read stdin: %v\n", err) os.Exit(64) } } else { script, err = ioutil.ReadFile(filename) if err != nil { fmt.Printf("Can't open file \"%v\": %v\n", filename, err) os.Exit(64) } } if !*underscoreFlag { underscore.Disable() } Otto := otto.New() _, err = Otto.Run(string(script)) if err != nil { fmt.Println(err) os.Exit(64) } }
func initJs(t *testing.T) *otto.Otto { var otto = otto.New() soyutilsFile, err := os.Open("lib/soyutils.js") if err != nil { panic(err) } // remove any non-otto compatible regular expressions var soyutilsBuf bytes.Buffer var scanner = bufio.NewScanner(soyutilsFile) var i = 1 for scanner.Scan() { switch i { case 2565, 2579, 2586: // skip these regexes // soy.esc.$$FILTER_FOR_FILTER_CSS_VALUE_ // soy.esc.$$FILTER_FOR_FILTER_HTML_ATTRIBUTES_ // soy.esc.$$FILTER_FOR_FILTER_HTML_ELEMENT_NAME_ default: soyutilsBuf.Write(scanner.Bytes()) soyutilsBuf.Write([]byte("\n")) } i++ } // load the soyutils library _, err = otto.Run(soyutilsBuf.String()) if err != nil { t.Errorf("soyutils error: %v", err) panic(err) } return otto }
func Calculate(response http.ResponseWriter, request *http.Request, params martini.Params) { bodyBytes, err := ioutil.ReadAll(request.Body) if err != nil { return } var toCalc Calculation err = json.Unmarshal(bodyBytes, &toCalc) if err != nil { http.Error(response, "Failed to Parse JSON", http.StatusInternalServerError) return } if toCalc.Calculation == "" { return } runner := otto.New() result, err := runner.Run(toCalc.Calculation) if err != nil { http.Error(response, err.Error(), http.StatusInternalServerError) return } toCalc.Result, _ = result.ToFloat() responseBytes, err := json.Marshal(toCalc) if err != nil { http.Error(response, "Failed to Encode JSON", http.StatusInternalServerError) return } fmt.Fprint(response, string(responseBytes)) return }
func NewScripting() (s *Scripting, err error) { s = &Scripting{ vm: otto.New(), listeners: map[string][]otto.Value{}, } return }
// NewJavascriptBuilder compiles the supplied javascript and creates a Javascriptbulder func NewJavascriptBuilder(config Config, file, src string) (*JavascriptBuilder, error) { js := &JavascriptBuilder{ file: file, vm: otto.New(), path: filepath.Dir(file), config: config, nodes: make(map[string]Node), pipelines: make([]*transporter.Pipeline, 0), } var ( script *otto.Script err error ) if src != "" { script, err = js.vm.Compile("", src) } else { script, err = js.vm.Compile(file, nil) } if err != nil { return js, err } js.script = script js.vm.Set("Source", js.source) return js, nil }
func NewChannelMapper(funcSource string) (*ChannelMapper, error) { mapper := &ChannelMapper{} mapper.js = otto.New() // Implementation of the 'sync()' callback: mapper.js.Set("sync", func(call otto.FunctionCall) otto.Value { for _, arg := range call.ArgumentList { if arg.IsString() { mapper.channels = append(mapper.channels, arg.String()) } else if arg.Class() == "Array" { array := ottoArrayToStrings(arg.Object()) if array != nil { mapper.channels = append(mapper.channels, array...) } } } return otto.UndefinedValue() }) if _, err := mapper.setFunction(funcSource); err != nil { return nil, err } mapper.requests = make(chan channelMapperRequest) go mapper.serve() return mapper, nil }
func TestFetchWithHandlerParallel(t *testing.T) { m := http.NewServeMux() m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) }) vm := otto.New() l := loop.New(vm) if err := DefineWithHandler(vm, l, m); err != nil { panic(err) } ch := make(chan bool, 1) if err := vm.Set("__capture", func(c otto.FunctionCall) otto.Value { defer func() { ch <- true }() return otto.UndefinedValue() }); err != nil { panic(err) } must(l.EvalAndRun(`Promise.all([1,2,3,4,5].map(function(i) { return fetch('/' + i); })).then(__capture)`)) <-ch }
func TestOttoFromGoArray(t *testing.T) { o := otto.New() _, err := OttoFromGoArray(o, nil) if err == nil { t.Errorf("expected err for nil array to OttoFromGoArray") } }
// NewAnnotator returns an Annotator with the sources, seeded with some javascript. // If ends is true, it will annotate the 1 base ends of the interval as well as the // interval itself. If strict is true, when overlapping variants, they must share // the ref allele and at least 1 alt allele. func NewAnnotator(sources []*Source, js string, ends bool, strict bool) *Annotator { for _, s := range sources { if e := checkSource(s); e != nil { log.Fatal(e) } } a := Annotator{ Sources: sources, Strict: strict, Ends: ends, } for _, src := range a.Sources { src.Vm = otto.New() // create a new vm for each source and lock in the source if strings.HasPrefix(src.Op, "js:") { var err error src.Js, err = src.Vm.Compile(src.Op, src.Op[3:]) if err != nil { log.Fatalf("error parsing op: %s for file %s", src.Op, src.File) } } if js != "" { _, err := src.Vm.Run(js) if err != nil { log.Fatalf("error parsing customjs:%s", err) } } } return &a }
func main() { flag.Parse() if !*flag_underscore { underscore.Disable() } err := func() error { src, err := readSource(flag.Arg(0)) if err != nil { return err } vm := otto.New() g_vm = vm vm.Set("setRoute", setRoute) vm.Set("startServer", startServer) vm.Set("writeMessage", writeMessage) _, err = vm.Run(src) return err }() if err != nil { switch err := err.(type) { case *otto.Error: fmt.Print(err.String()) default: fmt.Println(err) } os.Exit(64) } }
func createVM() *otto.Otto { vm := otto.New() logObj, _ := vm.Object(`$log = {}`) logObj.Set("info", _log_info) fileObj, _ := vm.Object(`$file = {}`) fileObj.Set("exists", _file_exists) fileObj.Set("write", _file_write) fileObj.Set("copy", _file_copy) fileObj.Set("size", _file_size) fileObj.Set("move", _file_move) fileObj.Set("mkdir", _file_mkdir) fileObj.Set("delete", _file_delete) fileObj.Set("readString", _file_readString) requestObj, _ := vm.Object(`$request = {}`) requestObj.Set("download", _request_download) requestObj.Set("get", _request_get) systemObj, _ := vm.Object(`$system = {}`) systemObj.Set("executeAndRead", _system_executeAndRead) systemObj.Set("execute", _system_execute) systemObj.Set("detach", _system_detach) systemObj.Set("currentUser", _system_currentUser) systemObj.Set("kill", _system_kill) return vm }
func main() { vm := otto.New() s, _ := simplejson.NewJson([]byte(` {"name":"[{\"name\":\"全部\",\"value\":\"all\"},{\"value\":372,\"name\":\"家居个护\"},{\"value\":437,\"name\":\"美容彩妆\"},{\"value\":438,\"name\":\"母婴\"},{\"value\":440,\"name\":\"数码家电\"},{\"value\":636,\"name\":\"【多余类目\"},{\"value\":836,\"name\":\"环球美食\"},{\"value\":837,\"name\":\"营养保健\"},{\"value\":1025,\"name\":\"箱包配饰\"},{\"value\":7578,\"name\":\"运动户外\"},{\"value\":8115,\"name\":\"生鲜\"},{\"value\":9691,\"name\":\"服装鞋靴\"}]"} `)) //fmt.Println(s.Get("name").MustMap()) vm.Set("def", s.Get("name").MustString()) vm.Set("getArray", func(call otto.FunctionCall) otto.Value { result, _ := vm.ToValue(getArray(call.Argument(0).String(), call.Argument(1).String())) return result }) vm.Set("getMap", func(call otto.FunctionCall) otto.Value { result, _ := vm.ToValue(getMap(call.Argument(0).String(), call.Argument(1).String())) return result }) _, e := vm.Run(` //var x = []; //x=x.concat(eval(def)) // console.log(x[0].name) //console.log(x.push(1)) //var x = {category_level:1}; //var x = JSON.parse(getData('http://localhost:8080/ds/50',JSON.stringify({name:1,age:19}))); //console.log(x.data) //console.log(x.code) console.log(getArray('http://www.jeasyui.com/demo/main/treegrid_data1.json')[0].id) `) if e != nil { fmt.Println(e) } }
func TestNewReader_ReadAll(t *testing.T) { runtime := otto.New() reader := strings.NewReader("Hello ottox!") assert.NoError(t, NewReader(runtime, "read", reader)) // make sure ottox.read method was added assert.True(t, Exist(runtime, "read")) // read some bytes if r, err := runtime.Call(`read`, nil, -1); assert.NoError(t, err) { if res, err := r.Object().Get("data"); assert.NoError(t, err) { if bytes, err := res.ToString(); assert.NoError(t, err) { assert.Equal(t, bytes, "Hello ottox!", "data") } } if res, err := r.Object().Get("eof"); assert.NoError(t, err) { if eofBool, err := res.ToBoolean(); assert.NoError(t, err) { assert.True(t, eofBool, "eof") } } } }
func HTTPMiddlewarePreRequest(endpoint *kasi_conf.EndpointSetting, r *http.Request) *MiddlewareResponse { for i := 0; i < len(endpoint.Middleware); i++ { jsFile, err := ioutil.ReadFile(endpoint.Middleware[i]) if err != nil { log.Error("javascript file, `%v`, not found", i) continue } vm := otto.New() vm.Run(jsFile) request := *r requestJS, _ := vm.ToValue(&request) response := MiddlewareResponse{StatusCode: 0, Header: map[string]string{}, Body: ""} responseJS, _ := vm.ToValue(&response) returnedResponse, err := vm.Call("process_request", nil, requestJS, responseJS) if err != nil { log.Error("failed to call, %v", err) continue } if !returnedResponse.IsDefined() { continue } exportedResponseReady, err := returnedResponse.Export() if err == nil { return exportedResponseReady.(*MiddlewareResponse) } break } return nil }
func main() { flag.Parse() if !*flag_underscore { underscore.Disable() } err := func() error { src, err := readSource(flag.Arg(0)) if err != nil { return err } vm := otto.New() _, err = vm.Run(src) return err }() if err != nil { switch err := err.(type) { case *otto.Error: fmt.Print(err.String()) default: fmt.Println(err) } os.Exit(64) } }
func TestNewWriter(t *testing.T) { runtime := otto.New() var buf bytes.Buffer assert.NoError(t, NewWriter(runtime, "write", &buf)) // make sure ottox.read method was added assert.True(t, Exist(runtime, "write")) if r, err := runtime.Call(`write`, nil, "abcde"); assert.NoError(t, err) { if res, err := r.Object().Get("len"); assert.NoError(t, err) { if lenInt, err := res.ToInteger(); assert.NoError(t, err) { assert.Equal(t, 5, lenInt, "len") assert.Equal(t, "abcde", buf.String()) } } } if r, err := runtime.Call(`write`, nil, "fghij"); assert.NoError(t, err) { if res, err := r.Object().Get("len"); assert.NoError(t, err) { if lenInt, err := res.ToInteger(); assert.NoError(t, err) { assert.Equal(t, 5, lenInt, "len") assert.Equal(t, "abcdefghij", buf.String()) } } } }
func initJavascript() { js = otto.New() f := facts.FindFacts() // TODO: log error factsAsJson, err := f.ToJson() if err == nil { js.Object(`facts = ` + string(factsAsJson)) } // Create javascript functions js.Set("directory", directory) js.Set("symlink", symlink) js.Set("template", template) js.Set("apt", apt) js.Set("yum", yum) js.Set("command", command) js.Set("user", user) js.Set("pg_user", pgUser) js.Set("pg_database", pgDatabase) js.Set("mysql_user", mysqlUser) js.Set("mysql_database", mysqlDatabase) js.Set("sleep", sleep) js.Set("upstart", upstart) js.Set("file", file) js.Set("include", include) }
func Worker(lines, out chan *string, script, preload string, wg *sync.WaitGroup) { defer wg.Done() vm := otto.New() if preload != "" { _, err := vm.Run(preload) if err != nil { log.Fatal(err) } } compiled, err := vm.Compile("", script) if err != nil { log.Fatal(err) } for line := range lines { vm.Set("input", *line) _, err := vm.Run(compiled) if err != nil { log.Fatal(err) } result, err := vm.Get("output") if result == otto.NullValue() { continue } if err != nil { log.Fatal(err) } r := result.String() out <- &r } }
func TestFetchWithHandler(t *testing.T) { m := http.NewServeMux() m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // these spaces are here so we can disambiguate between this and the // re-encoded data the javascript below spits out w.Write([]byte("[ 1 , 2 , 3 ]")) }) vm := otto.New() l := loop.New(vm) if err := DefineWithHandler(vm, l, m); err != nil { panic(err) } ch := make(chan bool, 1) if err := vm.Set("__capture", func(s string) { defer func() { ch <- true }() if s != `[1,2,3]` { panic(fmt.Errorf("expected data to be json, and for that json to be parsed")) } }); err != nil { panic(err) } must(l.EvalAndRun(`fetch('/').then(function(r) { return r.json(); }).then(function(d) { return setTimeout(__capture, 4, JSON.stringify(d)); })`)) <-ch }
// Start running the JavaScript engine. func (w *JavaScript) Run() { if cmd, ok := <-w.Cmd; ok { // initial setup engine := otto.New() // define a callback for sending messages to Out engine.Set("emitOut", func(call otto.FunctionCall) otto.Value { out, err := call.Argument(0).Export() flow.Check(err) w.Out.Send(out) return otto.UndefinedValue() }) // process the command input if _, err := engine.Run(cmd.(string)); err != nil { glog.Fatal(err) } // only start the processing loop if the "onIn" handler exists value, err := engine.Get("onIn") if err == nil && value.IsFunction() { for in := range w.In { engine.Call("onIn", nil, in) } } } }
func TestFetchCallback(t *testing.T) { m := http.NewServeMux() m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) }) s := httptest.NewServer(m) defer s.Close() vm := otto.New() l := loop.New(vm) if err := Define(vm, l); err != nil { panic(err) } ch := make(chan bool, 1) if err := vm.Set("__capture", func(s string) { defer func() { ch <- true }() if !strings.Contains(s, "hello") { panic(fmt.Errorf("expected to find `hello' in response")) } }); err != nil { panic(err) } must(l.EvalAndRun(`fetch('` + s.URL + `').then(function(r) { return r.text(); }).then(__capture)`)) <-ch }
func newReducer() *otto.Otto { o := otto.New() must(o.Set("_sum", javascriptReduceSum)) must(o.Set("_count", javascriptReduceCount)) must(o.Set("_stats", javascriptReduceStats)) return o }
func newRenderer(files []string) *renderer { r := &renderer{otto.New()} r.runFile("assets/global.js") r.runFile("assets/react.js") r.runFiles(files) return r }
func RunScript(file string) (conquest *Conquest, err error) { defer func() { if r := recover(); r != nil { switch r.(type) { case error: err = r.(error) case string: err = errors.New(r.(string)) } } }() vm := otto.New() conjs := JSConquest{ vm: vm, conquest: NewConquest(), } if err = vm.Set("conquest", conjs); err != nil { return } script, err := vm.Compile(file, nil) if err != nil { return } _, err = vm.Run(script) if err != nil { return } conquest = conjs.conquest return }
// New is the constructor for a new engine. func New(root, conditions string) (*Engine, error) { hostname, err := os.Hostname() if err != nil { return nil, err } engine := &Engine{Root: root, Hostname: hostname} if _, err := os.Stat(path.Join(engine.Root, "logic")); err == nil { logic, err := ioutil.ReadDir(path.Join(engine.Root, "logic")) if err != nil { return nil, err } engine.Logic = logic } if _, err := os.Stat(path.Join(engine.Root, "stacks")); err == nil { stacks, err := ioutil.ReadDir(path.Join(engine.Root, "stacks")) if err != nil { return nil, err } engine.Stacks = stacks } engine.DryRun = true engine.PythonPath = "python" engine.PipPath = "pip" engine.jsVM = otto.New() engine.SetConditions(conditions) return engine, nil }
func (*JSUtil) RunJS(e *irc.Event) { var halt = errors.New("Stahp") defer func() { if caught := recover(); caught != nil { if caught == halt { e.Connection.Privmsgf(e.Arguments[0], "!! WTF STAHP %s !!", e.Nick) return } } }() q := strings.TrimSpace(strings.Replace(e.Arguments[1], "!js ", "", -1)) vm := otto.New() vm.Interrupt = make(chan func(), 1) // The buffer prevents blocking go func() { time.Sleep(10 * time.Second) // Stop after two seconds vm.Interrupt <- func() { panic(halt) } }() script, ser := vm.Compile("", q) if ser == nil { outjs, er := vm.Run(script) if er == nil { e.Connection.Privmsgf(e.Arguments[0], "[%s]: %s", e.Nick, outjs) } else { e.Connection.Privmsgf(e.Arguments[0], "Error in JS %s: %s", e.Nick, er) } } else { e.Connection.Privmsgf(e.Arguments[0], "Compile error %s: %s", e.Nick, ser) } }
func newVM() *otto.Otto { vm := otto.New() // os object os, _ := vm.Object(`os = {}`) os.Set("getwd", os_getwd) os.Set("mkdir", os_mkdir) os.Set("remove", os_remove) os.Set("rename", os_rename) os.Set("stat", os_stat) os.Set("system", os_system) os.Set("whence", os_whence) vm.Run(fmt.Sprintf(`os.FileInfo = function(name, size, mode, mtime) { this.name = name; this.size = size; this.mode = mode; this.mtime = mtime; }; os.FileInfo.prototype.isDir = function() { return (this.mode & %v) !== 0; }; os.FileInfo.prototype.isRegular = function() { return (this.mode & %v) === 0; }; os.FileInfo.prototype.perm = function() { return this.mode & %v; }; `, int64(1<<31), int64(0xff<<24), 0777)) return vm }
func NewJSRuntime() (*JsVm, error) { vm := otto.New() jsvm := NewJsVm(vm) RegisterModules(jsvm) path := defaultPath fileC, err := ioutil.ReadFile(path) if err != nil { return nil, err } /* fileHash := md5.Sum(fileC) if len(lastMd5) == 0 || lastMd5 != fileHash { lastMd5 = fileHash fmt.Println("compiling") compiled, err = vm.Compile(path, nil) if err != nil { return nil, err } } _, err = vm.Run(compiled) */ _, err = jsvm.Run(string(fileC)) if err == nil { UsedRuntimes += 1 fmt.Println("used runtimes " + strconv.Itoa(UsedRuntimes)) runtime.SetFinalizer(vm, finalizer) } return jsvm, err }
func NewOttoCartesianProductJoiner() *OttoCartesianProductJoiner { return &OttoCartesianProductJoiner{ OutputChannel: make(DocumentChannel), leftDocs: make([]Document, 0), rightDocs: make([]Document, 0), Otto: otto.New()} }