pretty.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package jsre
  17. import (
  18. "fmt"
  19. "io"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "github.com/fatih/color"
  24. "github.com/robertkrimen/otto"
  25. )
  26. const (
  27. maxPrettyPrintLevel = 3
  28. indentString = " "
  29. )
  30. var (
  31. FunctionColor = color.New(color.FgMagenta).SprintfFunc()
  32. SpecialColor = color.New(color.Bold).SprintfFunc()
  33. NumberColor = color.New(color.FgRed).SprintfFunc()
  34. StringColor = color.New(color.FgGreen).SprintfFunc()
  35. ErrorColor = color.New(color.FgHiRed).SprintfFunc()
  36. )
  37. // these fields are hidden when printing objects.
  38. var boringKeys = map[string]bool{
  39. "valueOf": true,
  40. "toString": true,
  41. "toLocaleString": true,
  42. "hasOwnProperty": true,
  43. "isPrototypeOf": true,
  44. "propertyIsEnumerable": true,
  45. "constructor": true,
  46. }
  47. // prettyPrint writes value to standard output.
  48. func prettyPrint(vm *otto.Otto, value otto.Value, w io.Writer) {
  49. ppctx{vm: vm, w: w}.printValue(value, 0, false)
  50. }
  51. // prettyError writes err to standard output.
  52. func prettyError(vm *otto.Otto, err error, w io.Writer) {
  53. failure := err.Error()
  54. if ottoErr, ok := err.(*otto.Error); ok {
  55. failure = ottoErr.String()
  56. }
  57. fmt.Fprint(w, ErrorColor("%s", failure))
  58. }
  59. func (re *JSRE) prettyPrintJS(call otto.FunctionCall) otto.Value {
  60. for _, v := range call.ArgumentList {
  61. prettyPrint(call.Otto, v, re.output)
  62. fmt.Fprintln(re.output)
  63. }
  64. return otto.UndefinedValue()
  65. }
  66. type ppctx struct {
  67. vm *otto.Otto
  68. w io.Writer
  69. }
  70. func (ctx ppctx) indent(level int) string {
  71. return strings.Repeat(indentString, level)
  72. }
  73. func (ctx ppctx) printValue(v otto.Value, level int, inArray bool) {
  74. switch {
  75. case v.IsObject():
  76. ctx.printObject(v.Object(), level, inArray)
  77. case v.IsNull():
  78. fmt.Fprint(ctx.w, SpecialColor("null"))
  79. case v.IsUndefined():
  80. fmt.Fprint(ctx.w, SpecialColor("undefined"))
  81. case v.IsString():
  82. s, _ := v.ToString()
  83. fmt.Fprint(ctx.w, StringColor("%q", s))
  84. case v.IsBoolean():
  85. b, _ := v.ToBoolean()
  86. fmt.Fprint(ctx.w, SpecialColor("%t", b))
  87. case v.IsNaN():
  88. fmt.Fprint(ctx.w, NumberColor("NaN"))
  89. case v.IsNumber():
  90. s, _ := v.ToString()
  91. fmt.Fprint(ctx.w, NumberColor("%s", s))
  92. default:
  93. fmt.Fprint(ctx.w, "<unprintable>")
  94. }
  95. }
  96. func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
  97. switch obj.Class() {
  98. case "Array", "GoArray":
  99. lv, _ := obj.Get("length")
  100. len, _ := lv.ToInteger()
  101. if len == 0 {
  102. fmt.Fprintf(ctx.w, "[]")
  103. return
  104. }
  105. if level > maxPrettyPrintLevel {
  106. fmt.Fprint(ctx.w, "[...]")
  107. return
  108. }
  109. fmt.Fprint(ctx.w, "[")
  110. for i := int64(0); i < len; i++ {
  111. el, err := obj.Get(strconv.FormatInt(i, 10))
  112. if err == nil {
  113. ctx.printValue(el, level+1, true)
  114. }
  115. if i < len-1 {
  116. fmt.Fprintf(ctx.w, ", ")
  117. }
  118. }
  119. fmt.Fprint(ctx.w, "]")
  120. case "Object":
  121. // Print values from bignumber.js as regular numbers.
  122. if ctx.isBigNumber(obj) {
  123. fmt.Fprint(ctx.w, NumberColor("%s", toString(obj)))
  124. return
  125. }
  126. // Otherwise, print all fields indented, but stop if we're too deep.
  127. keys := ctx.fields(obj)
  128. if len(keys) == 0 {
  129. fmt.Fprint(ctx.w, "{}")
  130. return
  131. }
  132. if level > maxPrettyPrintLevel {
  133. fmt.Fprint(ctx.w, "{...}")
  134. return
  135. }
  136. fmt.Fprintln(ctx.w, "{")
  137. for i, k := range keys {
  138. v, _ := obj.Get(k)
  139. fmt.Fprintf(ctx.w, "%s%s: ", ctx.indent(level+1), k)
  140. ctx.printValue(v, level+1, false)
  141. if i < len(keys)-1 {
  142. fmt.Fprintf(ctx.w, ",")
  143. }
  144. fmt.Fprintln(ctx.w)
  145. }
  146. if inArray {
  147. level--
  148. }
  149. fmt.Fprintf(ctx.w, "%s}", ctx.indent(level))
  150. case "Function":
  151. // Use toString() to display the argument list if possible.
  152. if robj, err := obj.Call("toString"); err != nil {
  153. fmt.Fprint(ctx.w, FunctionColor("function()"))
  154. } else {
  155. desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
  156. desc = strings.Replace(desc, " (", "(", 1)
  157. fmt.Fprint(ctx.w, FunctionColor("%s", desc))
  158. }
  159. case "RegExp":
  160. fmt.Fprint(ctx.w, StringColor("%s", toString(obj)))
  161. default:
  162. if v, _ := obj.Get("toString"); v.IsFunction() && level <= maxPrettyPrintLevel {
  163. s, _ := obj.Call("toString")
  164. fmt.Fprintf(ctx.w, "<%s %s>", obj.Class(), s.String())
  165. } else {
  166. fmt.Fprintf(ctx.w, "<%s>", obj.Class())
  167. }
  168. }
  169. }
  170. func (ctx ppctx) fields(obj *otto.Object) []string {
  171. var (
  172. vals, methods []string
  173. seen = make(map[string]bool)
  174. )
  175. add := func(k string) {
  176. if seen[k] || boringKeys[k] || strings.HasPrefix(k, "_") {
  177. return
  178. }
  179. seen[k] = true
  180. if v, _ := obj.Get(k); v.IsFunction() {
  181. methods = append(methods, k)
  182. } else {
  183. vals = append(vals, k)
  184. }
  185. }
  186. iterOwnAndConstructorKeys(ctx.vm, obj, add)
  187. sort.Strings(vals)
  188. sort.Strings(methods)
  189. return append(vals, methods...)
  190. }
  191. func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
  192. seen := make(map[string]bool)
  193. iterOwnKeys(vm, obj, func(prop string) {
  194. seen[prop] = true
  195. f(prop)
  196. })
  197. if cp := constructorPrototype(obj); cp != nil {
  198. iterOwnKeys(vm, cp, func(prop string) {
  199. if !seen[prop] {
  200. f(prop)
  201. }
  202. })
  203. }
  204. }
  205. func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
  206. Object, _ := vm.Object("Object")
  207. rv, _ := Object.Call("getOwnPropertyNames", obj.Value())
  208. gv, _ := rv.Export()
  209. switch gv := gv.(type) {
  210. case []interface{}:
  211. for _, v := range gv {
  212. f(v.(string))
  213. }
  214. case []string:
  215. for _, v := range gv {
  216. f(v)
  217. }
  218. default:
  219. panic(fmt.Errorf("Object.getOwnPropertyNames returned unexpected type %T", gv))
  220. }
  221. }
  222. func (ctx ppctx) isBigNumber(v *otto.Object) bool {
  223. // Handle numbers with custom constructor.
  224. if v, _ := v.Get("constructor"); v.Object() != nil {
  225. if strings.HasPrefix(toString(v.Object()), "function BigNumber") {
  226. return true
  227. }
  228. }
  229. // Handle default constructor.
  230. BigNumber, _ := ctx.vm.Object("BigNumber.prototype")
  231. if BigNumber == nil {
  232. return false
  233. }
  234. bv, _ := BigNumber.Call("isPrototypeOf", v)
  235. b, _ := bv.ToBoolean()
  236. return b
  237. }
  238. func toString(obj *otto.Object) string {
  239. s, _ := obj.Call("toString")
  240. return s.String()
  241. }
  242. func constructorPrototype(obj *otto.Object) *otto.Object {
  243. if v, _ := obj.Get("constructor"); v.Object() != nil {
  244. if v, _ = v.Object().Get("prototype"); v.Object() != nil {
  245. return v.Object()
  246. }
  247. }
  248. return nil
  249. }