key.go 1002 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package tracker
  2. import "github.com/pelletier/go-toml/v2/unstable"
  3. // KeyTracker is a tracker that keeps track of the current Key as the AST is
  4. // walked.
  5. type KeyTracker struct {
  6. k []string
  7. }
  8. // UpdateTable sets the state of the tracker with the AST table node.
  9. func (t *KeyTracker) UpdateTable(node *unstable.Node) {
  10. t.reset()
  11. t.Push(node)
  12. }
  13. // UpdateArrayTable sets the state of the tracker with the AST array table node.
  14. func (t *KeyTracker) UpdateArrayTable(node *unstable.Node) {
  15. t.reset()
  16. t.Push(node)
  17. }
  18. // Push the given key on the stack.
  19. func (t *KeyTracker) Push(node *unstable.Node) {
  20. it := node.Key()
  21. for it.Next() {
  22. t.k = append(t.k, string(it.Node().Data))
  23. }
  24. }
  25. // Pop key from stack.
  26. func (t *KeyTracker) Pop(node *unstable.Node) {
  27. it := node.Key()
  28. for it.Next() {
  29. t.k = t.k[:len(t.k)-1]
  30. }
  31. }
  32. // Key returns the current key
  33. func (t *KeyTracker) Key() []string {
  34. k := make([]string, len(t.k))
  35. copy(k, t.k)
  36. return k
  37. }
  38. func (t *KeyTracker) reset() {
  39. t.k = t.k[:0]
  40. }