getTree does the actual heavy lifting and recursion for PrintTree TODO: provide a way to print the tree as a JSON object?
(n *sitter.Node, source []byte)
| 520 | // getTree does the actual heavy lifting and recursion for PrintTree |
| 521 | // TODO: provide a way to print the tree as a JSON object? |
| 522 | func getTree(n *sitter.Node, source []byte) string { |
| 523 | |
| 524 | out := &strings.Builder{} |
| 525 | |
| 526 | c := sitter.NewTreeCursor(n) |
| 527 | defer c.Close() |
| 528 | |
| 529 | // walkies |
| 530 | depth := 0 |
| 531 | recurse := true |
| 532 | for { |
| 533 | if recurse && c.CurrentNode().IsNamed() { |
| 534 | fieldName := c.CurrentFieldName() |
| 535 | if fieldName != "" { |
| 536 | fieldName += ": " |
| 537 | } |
| 538 | |
| 539 | contentStr := "" |
| 540 | if c.CurrentNode().ChildCount() == 0 || c.CurrentNode().Type() == "string" { |
| 541 | contentStr = fmt.Sprintf(" (%s)", content(c.CurrentNode(), source)) |
| 542 | } |
| 543 | fmt.Fprintf(out, "%s%s%s%s\n", strings.Repeat(" ", depth), fieldName, c.CurrentNode().Type(), contentStr) |
| 544 | } |
| 545 | |
| 546 | // descend into the tree |
| 547 | if recurse && c.GoToFirstChild() { |
| 548 | recurse = true |
| 549 | depth++ |
| 550 | continue |
| 551 | } |
| 552 | |
| 553 | // move sideways |
| 554 | if c.GoToNextSibling() { |
| 555 | recurse = true |
| 556 | continue |
| 557 | } |
| 558 | |
| 559 | // climb back up the tree, but make sure we don't descend right back to where we were |
| 560 | if c.GoToParent() { |
| 561 | depth-- |
| 562 | recurse = false |
| 563 | continue |
| 564 | } |
| 565 | break |
| 566 | } |
| 567 | |
| 568 | return strings.TrimSpace(out.String()) |
| 569 | } |