A simple command line REPL (read-eval-print loop) that drives a simple in-memory key/value storage system.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.2 KiB

  1. package kvrepl
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. )
  7. // Parse decides what commands to run and returns a string containing the
  8. // value of a read or an error if one occurred.
  9. func Parse(s string, d *DB) (string, error) {
  10. args := strings.Split(s, " ")
  11. switch strings.ToLower(args[0]) {
  12. case "read":
  13. return read(args[1:], whichDB(d))
  14. case "write":
  15. return "", write(args[1:], whichDB(d))
  16. case "delete":
  17. return "", del(args[1:], whichDB(d))
  18. case "start":
  19. if len(args) != 1 {
  20. return "", fmt.Errorf("incorrect usage: START")
  21. }
  22. d.nest++
  23. d.PKV = false
  24. // copy contents of KV1 to KV2
  25. d.KV2 = make(map[string]string)
  26. for k, v := range d.KV1 {
  27. d.KV2[k] = v
  28. }
  29. case "commit":
  30. if len(args) != 1 {
  31. return "", fmt.Errorf("incorrect usage: COMMIT")
  32. }
  33. if d.PKV {
  34. return "", fmt.Errorf("not in a transaction")
  35. }
  36. if d.nest == 0 {
  37. d.PKV = true
  38. // copy contents of KV2 to KV1
  39. d.KV1 = make(map[string]string)
  40. for k, v := range d.KV2 {
  41. d.KV1[k] = v
  42. }
  43. }
  44. case "abort":
  45. if len(args) != 1 {
  46. return "", fmt.Errorf("incorrect usage: ABORT")
  47. }
  48. d.PKV = true
  49. case "quit":
  50. fmt.Println("goodbye")
  51. os.Exit(0)
  52. default:
  53. fmt.Println("not known command")
  54. }
  55. return "", nil
  56. }