repl.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright (c) 2013-2014, Jeffrey Wilcke. All rights reserved.
  2. //
  3. // This library is free software; you can redistribute it and/or
  4. // modify it under the terms of the GNU General Public
  5. // License as published by the Free Software Foundation; either
  6. // version 2.1 of the License, or (at your option) any later version.
  7. //
  8. // This library is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. // General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this library; if not, write to the Free Software
  15. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. // MA 02110-1301 USA
  17. package ethrepl
  18. import (
  19. "bufio"
  20. "fmt"
  21. "io"
  22. "os"
  23. "path"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/ethlog"
  26. "github.com/ethereum/go-ethereum/ethutil"
  27. "github.com/ethereum/go-ethereum/javascript"
  28. )
  29. var logger = ethlog.NewLogger("REPL")
  30. type Repl interface {
  31. Start()
  32. Stop()
  33. }
  34. type JSRepl struct {
  35. re *javascript.JSRE
  36. prompt string
  37. history *os.File
  38. running bool
  39. }
  40. func NewJSRepl(ethereum *eth.Ethereum) *JSRepl {
  41. hist, err := os.OpenFile(path.Join(ethutil.Config.ExecPath, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  42. if err != nil {
  43. panic(err)
  44. }
  45. return &JSRepl{re: javascript.NewJSRE(ethereum), prompt: "> ", history: hist}
  46. }
  47. func (self *JSRepl) Start() {
  48. if !self.running {
  49. self.running = true
  50. logger.Infoln("init JS Console")
  51. reader := bufio.NewReader(self.history)
  52. for {
  53. line, err := reader.ReadString('\n')
  54. if err != nil && err == io.EOF {
  55. break
  56. } else if err != nil {
  57. fmt.Println("error reading history", err)
  58. break
  59. }
  60. addHistory(line[:len(line)-1])
  61. }
  62. self.read()
  63. }
  64. }
  65. func (self *JSRepl) Stop() {
  66. if self.running {
  67. self.running = false
  68. self.re.Stop()
  69. logger.Infoln("exit JS Console")
  70. self.history.Close()
  71. }
  72. }
  73. func (self *JSRepl) parseInput(code string) {
  74. defer func() {
  75. if r := recover(); r != nil {
  76. fmt.Println("[native] error", r)
  77. }
  78. }()
  79. value, err := self.re.Run(code)
  80. if err != nil {
  81. fmt.Println(err)
  82. return
  83. }
  84. self.PrintValue(value)
  85. }