main.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "path/filepath"
  6. )
  7. import "gitlab.com/beoran/muesli"
  8. import "github.com/peterh/liner"
  9. type LogTracer struct {
  10. }
  11. func (t * LogTracer) Trace(vm muesli.VM, ast muesli.Ast, val muesli.ListValue) bool {
  12. log.Printf("Trace: %s %v", ast.String(), val)
  13. return false
  14. }
  15. func runLine(vm *muesli.VM, in string) error {
  16. parser := muesli.NewParserFromString(in)
  17. ast := parser.Parse()
  18. err := ast.ToError()
  19. if err != nil {
  20. return err
  21. }
  22. vm.RunAst(*ast, muesli.NewListValue())
  23. return nil
  24. }
  25. func runLines(vm *muesli.VM, line *liner.State) error {
  26. for {
  27. if in, err := line.Prompt("> "); err == nil {
  28. err = runLine(vm, in)
  29. if err != nil {
  30. log.Print("Error %s: ", err)
  31. }
  32. line.AppendHistory(in)
  33. } else if err == liner.ErrPromptAborted {
  34. log.Print("Aborted")
  35. return nil
  36. } else {
  37. log.Print("Error reading line: ", err)
  38. }
  39. }
  40. return nil
  41. }
  42. func main() {
  43. vm := muesli.NewVM()
  44. vm.Tracer = &LogTracer{}
  45. vm.RegisterBuiltins()
  46. line := liner.NewLiner()
  47. defer line.Close()
  48. line.SetCtrlCAborts(true)
  49. home, _ := os.UserHomeDir()
  50. historyName := filepath.Join(home, ".muesli_history")
  51. /* line.SetCompleter(func(line string) (c []string) {
  52. for _, n := range names {
  53. if strings.HasPrefix(n, strings.ToLower(line)) {
  54. c = append(c, n)
  55. }
  56. }
  57. return
  58. })
  59. */
  60. if f, err := os.Open(historyName); err == nil {
  61. line.ReadHistory(f)
  62. f.Close()
  63. }
  64. runLines(vm, line)
  65. if f, err := os.Create(historyName); err != nil {
  66. log.Print("Error writing history file: ", err)
  67. } else {
  68. line.WriteHistory(f)
  69. f.Close()
  70. }
  71. }