robertkrimen / otto

A JavaScript interpreter in Go (golang)
http://godoc.org/github.com/robertkrimen/otto
MIT License
8.01k stars 584 forks source link

otto/repl: pretty print expression results #338

Open robfig opened 5 years ago

robfig commented 5 years ago

First, thank you for the wonderful project! It's been really helpful.

I recently started using the repl module for a project I was hoping to implement in Go rather than Node.js, and I quickly ran into a stakeholder concern of lacking the helpful REPL feature of pretty-printing the results of expressions.

For example, using repl.Run, referencing a JS object results in this being printed

[object Object]

instead of something helpful like the Node.js repl prints:

> entities
EntityDB {
  db:
   Datastore {
     inMemoryOnly: true,
     autoload: false,
     timestampData: false,
     filename: null,
     compareStrings: undefined,
 ....

Looking into the code, I don't see any way to customize the printed output, so I was wondering if you would be open to a pull request?

Here is the relevant code:

# otto/repl/repl.go

            v, err := vm.Eval(s) // <--
            if err != nil {
                if oerr, ok := err.(*otto.Error); ok {
                    io.Copy(rl.Stdout(), strings.NewReader(oerr.String()))
                } else {
                    io.Copy(rl.Stdout(), strings.NewReader(err.Error()))
                }
            } else {
                rl.Stdout().Write([]byte(v.String() + "\n"))
            }

One way to permit this use case is to add an optional Eval func to the repl.Options struct that replaces the line above, if set.

How does that sound?

Thank you, Rob

stevenh commented 1 year ago

Would definitely like to see this.