pretty.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright 2015 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. "sort"
  20. "strconv"
  21. "strings"
  22. "github.com/fatih/color"
  23. "github.com/robertkrimen/otto"
  24. )
  25. const (
  26. maxPrettyPrintLevel = 3
  27. indentString = " "
  28. )
  29. var (
  30. functionColor = color.New(color.FgMagenta)
  31. specialColor = color.New(color.Bold)
  32. numberColor = color.New(color.FgRed)
  33. stringColor = color.New(color.FgGreen)
  34. )
  35. // these fields are hidden when printing objects.
  36. var boringKeys = map[string]bool{
  37. "valueOf": true,
  38. "toString": true,
  39. "toLocaleString": true,
  40. "hasOwnProperty": true,
  41. "isPrototypeOf": true,
  42. "propertyIsEnumerable": true,
  43. "constructor": true,
  44. }
  45. // prettyPrint writes value to standard output.
  46. func prettyPrint(vm *otto.Otto, value otto.Value) {
  47. ppctx{vm}.printValue(value, 0, false)
  48. }
  49. func prettyPrintJS(call otto.FunctionCall) otto.Value {
  50. for _, v := range call.ArgumentList {
  51. prettyPrint(call.Otto, v)
  52. fmt.Println()
  53. }
  54. return otto.UndefinedValue()
  55. }
  56. type ppctx struct{ vm *otto.Otto }
  57. func (ctx ppctx) indent(level int) string {
  58. return strings.Repeat(indentString, level)
  59. }
  60. func (ctx ppctx) printValue(v otto.Value, level int, inArray bool) {
  61. switch {
  62. case v.IsObject():
  63. ctx.printObject(v.Object(), level, inArray)
  64. case v.IsNull():
  65. specialColor.Print("null")
  66. case v.IsUndefined():
  67. specialColor.Print("undefined")
  68. case v.IsString():
  69. s, _ := v.ToString()
  70. stringColor.Printf("%q", s)
  71. case v.IsBoolean():
  72. b, _ := v.ToBoolean()
  73. specialColor.Printf("%t", b)
  74. case v.IsNaN():
  75. numberColor.Printf("NaN")
  76. case v.IsNumber():
  77. s, _ := v.ToString()
  78. numberColor.Printf("%s", s)
  79. default:
  80. fmt.Printf("<unprintable>")
  81. }
  82. }
  83. func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
  84. switch obj.Class() {
  85. case "Array":
  86. lv, _ := obj.Get("length")
  87. len, _ := lv.ToInteger()
  88. if len == 0 {
  89. fmt.Printf("[]")
  90. return
  91. }
  92. if level > maxPrettyPrintLevel {
  93. fmt.Print("[...]")
  94. return
  95. }
  96. fmt.Print("[")
  97. for i := int64(0); i < len; i++ {
  98. el, err := obj.Get(strconv.FormatInt(i, 10))
  99. if err == nil {
  100. ctx.printValue(el, level+1, true)
  101. }
  102. if i < len-1 {
  103. fmt.Printf(", ")
  104. }
  105. }
  106. fmt.Print("]")
  107. case "Object":
  108. // Print values from bignumber.js as regular numbers.
  109. if ctx.isBigNumber(obj) {
  110. numberColor.Print(toString(obj))
  111. return
  112. }
  113. // Otherwise, print all fields indented, but stop if we're too deep.
  114. keys := ctx.fields(obj)
  115. if len(keys) == 0 {
  116. fmt.Print("{}")
  117. return
  118. }
  119. if level > maxPrettyPrintLevel {
  120. fmt.Print("{...}")
  121. return
  122. }
  123. fmt.Println("{")
  124. for i, k := range keys {
  125. v, _ := obj.Get(k)
  126. fmt.Printf("%s%s: ", ctx.indent(level+1), k)
  127. ctx.printValue(v, level+1, false)
  128. if i < len(keys)-1 {
  129. fmt.Printf(",")
  130. }
  131. fmt.Println()
  132. }
  133. if inArray {
  134. level--
  135. }
  136. fmt.Printf("%s}", ctx.indent(level))
  137. case "Function":
  138. // Use toString() to display the argument list if possible.
  139. if robj, err := obj.Call("toString"); err != nil {
  140. functionColor.Print("function()")
  141. } else {
  142. desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
  143. desc = strings.Replace(desc, " (", "(", 1)
  144. functionColor.Print(desc)
  145. }
  146. case "RegExp":
  147. stringColor.Print(toString(obj))
  148. default:
  149. if v, _ := obj.Get("toString"); v.IsFunction() && level <= maxPrettyPrintLevel {
  150. s, _ := obj.Call("toString")
  151. fmt.Printf("<%s %s>", obj.Class(), s.String())
  152. } else {
  153. fmt.Printf("<%s>", obj.Class())
  154. }
  155. }
  156. }
  157. func (ctx ppctx) fields(obj *otto.Object) []string {
  158. var (
  159. vals, methods []string
  160. seen = make(map[string]bool)
  161. )
  162. add := func(k string) {
  163. if seen[k] || boringKeys[k] {
  164. return
  165. }
  166. seen[k] = true
  167. if v, _ := obj.Get(k); v.IsFunction() {
  168. methods = append(methods, k)
  169. } else {
  170. vals = append(vals, k)
  171. }
  172. }
  173. iterOwnAndConstructorKeys(ctx.vm, obj, add)
  174. sort.Strings(vals)
  175. sort.Strings(methods)
  176. return append(vals, methods...)
  177. }
  178. func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
  179. seen := make(map[string]bool)
  180. iterOwnKeys(vm, obj, func(prop string) {
  181. seen[prop] = true
  182. f(prop)
  183. })
  184. if cp := constructorPrototype(obj); cp != nil {
  185. iterOwnKeys(vm, cp, func(prop string) {
  186. if !seen[prop] {
  187. f(prop)
  188. }
  189. })
  190. }
  191. }
  192. func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
  193. Object, _ := vm.Object("Object")
  194. rv, _ := Object.Call("getOwnPropertyNames", obj.Value())
  195. gv, _ := rv.Export()
  196. switch gv := gv.(type) {
  197. case []interface{}:
  198. for _, v := range gv {
  199. f(v.(string))
  200. }
  201. case []string:
  202. for _, v := range gv {
  203. f(v)
  204. }
  205. default:
  206. panic(fmt.Errorf("Object.getOwnPropertyNames returned unexpected type %T", gv))
  207. }
  208. }
  209. func (ctx ppctx) isBigNumber(v *otto.Object) bool {
  210. BigNumber, err := ctx.vm.Run("BigNumber.prototype")
  211. if err != nil {
  212. panic(err)
  213. }
  214. cp := constructorPrototype(v)
  215. return cp != nil && cp.Value() == BigNumber
  216. }
  217. func toString(obj *otto.Object) string {
  218. s, _ := obj.Call("toString")
  219. return s.String()
  220. }
  221. func constructorPrototype(obj *otto.Object) *otto.Object {
  222. if v, _ := obj.Get("constructor"); v.Object() != nil {
  223. if v, _ = v.Object().Get("prototype"); v.Object() != nil {
  224. return v.Object()
  225. }
  226. }
  227. return nil
  228. }