pretty.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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)
  48. }
  49. type ppctx struct{ vm *otto.Otto }
  50. func (ctx ppctx) indent(level int) string {
  51. return strings.Repeat(indentString, level)
  52. }
  53. func (ctx ppctx) printValue(v otto.Value, level int) {
  54. switch {
  55. case v.IsObject():
  56. ctx.printObject(v.Object(), level)
  57. case v.IsNull():
  58. specialColor.Print("null")
  59. case v.IsUndefined():
  60. specialColor.Print("undefined")
  61. case v.IsString():
  62. s, _ := v.ToString()
  63. stringColor.Printf("%q", s)
  64. case v.IsBoolean():
  65. b, _ := v.ToBoolean()
  66. specialColor.Printf("%t", b)
  67. case v.IsNaN():
  68. numberColor.Printf("NaN")
  69. case v.IsNumber():
  70. s, _ := v.ToString()
  71. numberColor.Printf("%s", s)
  72. default:
  73. fmt.Printf("<unprintable>")
  74. }
  75. }
  76. func (ctx ppctx) printObject(obj *otto.Object, level int) {
  77. switch obj.Class() {
  78. case "Array":
  79. lv, _ := obj.Get("length")
  80. len, _ := lv.ToInteger()
  81. if len == 0 {
  82. fmt.Printf("[]")
  83. return
  84. }
  85. if level > maxPrettyPrintLevel {
  86. fmt.Print("[...]")
  87. return
  88. }
  89. fmt.Print("[")
  90. for i := int64(0); i < len; i++ {
  91. el, err := obj.Get(strconv.FormatInt(i, 10))
  92. if err == nil {
  93. ctx.printValue(el, level+1)
  94. }
  95. if i < len-1 {
  96. fmt.Printf(", ")
  97. }
  98. }
  99. fmt.Print("]")
  100. case "Object":
  101. // Print values from bignumber.js as regular numbers.
  102. if ctx.isBigNumber(obj) {
  103. numberColor.Print(toString(obj))
  104. return
  105. }
  106. // Otherwise, print all fields indented, but stop if we're too deep.
  107. keys := ctx.fields(obj)
  108. if len(keys) == 0 {
  109. fmt.Print("{}")
  110. return
  111. }
  112. if level > maxPrettyPrintLevel {
  113. fmt.Print("{...}")
  114. return
  115. }
  116. fmt.Println("{")
  117. for i, k := range keys {
  118. v, _ := obj.Get(k)
  119. fmt.Printf("%s%s: ", ctx.indent(level+1), k)
  120. ctx.printValue(v, level+1)
  121. if i < len(keys)-1 {
  122. fmt.Printf(",")
  123. }
  124. fmt.Println()
  125. }
  126. fmt.Printf("%s}", ctx.indent(level))
  127. case "Function":
  128. // Use toString() to display the argument list if possible.
  129. if robj, err := obj.Call("toString"); err != nil {
  130. functionColor.Print("function()")
  131. } else {
  132. desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
  133. desc = strings.Replace(desc, " (", "(", 1)
  134. functionColor.Print(desc)
  135. }
  136. case "RegExp":
  137. stringColor.Print(toString(obj))
  138. default:
  139. if v, _ := obj.Get("toString"); v.IsFunction() && level <= maxPrettyPrintLevel {
  140. s, _ := obj.Call("toString")
  141. fmt.Printf("<%s %s>", obj.Class(), s.String())
  142. } else {
  143. fmt.Printf("<%s>", obj.Class())
  144. }
  145. }
  146. }
  147. func (ctx ppctx) fields(obj *otto.Object) []string {
  148. var (
  149. vals, methods []string
  150. seen = make(map[string]bool)
  151. )
  152. add := func(k string) {
  153. if seen[k] || boringKeys[k] {
  154. return
  155. }
  156. seen[k] = true
  157. if v, _ := obj.Get(k); v.IsFunction() {
  158. methods = append(methods, k)
  159. } else {
  160. vals = append(vals, k)
  161. }
  162. }
  163. // add own properties
  164. ctx.doOwnProperties(obj.Value(), add)
  165. // add properties of the constructor
  166. if cp := constructorPrototype(obj); cp != nil {
  167. ctx.doOwnProperties(cp.Value(), add)
  168. }
  169. sort.Strings(vals)
  170. sort.Strings(methods)
  171. return append(vals, methods...)
  172. }
  173. func (ctx ppctx) doOwnProperties(v otto.Value, f func(string)) {
  174. Object, _ := ctx.vm.Object("Object")
  175. rv, _ := Object.Call("getOwnPropertyNames", v)
  176. gv, _ := rv.Export()
  177. for _, v := range gv.([]interface{}) {
  178. f(v.(string))
  179. }
  180. }
  181. func (ctx ppctx) isBigNumber(v *otto.Object) bool {
  182. BigNumber, err := ctx.vm.Run("BigNumber.prototype")
  183. if err != nil {
  184. panic(err)
  185. }
  186. cp := constructorPrototype(v)
  187. return cp != nil && cp.Value() == BigNumber
  188. }
  189. func toString(obj *otto.Object) string {
  190. s, _ := obj.Call("toString")
  191. return s.String()
  192. }
  193. func constructorPrototype(obj *otto.Object) *otto.Object {
  194. if v, _ := obj.Get("constructor"); v.Object() != nil {
  195. if v, _ = v.Object().Get("prototype"); v.Object() != nil {
  196. return v.Object()
  197. }
  198. }
  199. return nil
  200. }