key.go 991 B

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