Skip to content

Commit 90b46d9

Browse files
committed
Prettier tree string for TreeNode
1 parent 9693b0d commit 90b46d9

File tree

1 file changed

+19
-6
lines changed
  • sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees

1 file changed

+19
-6
lines changed

sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreeNode.scala

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ abstract class TreeNode[BaseType <: TreeNode[BaseType]] extends Product {
368368
override def toString: String = treeString
369369

370370
/** Returns a string representation of the nodes in this tree */
371-
def treeString: String = generateTreeString(0, new StringBuilder).toString
371+
def treeString: String = generateTreeString(0, Nil, new StringBuilder).toString
372372

373373
/**
374374
* Returns a string representation of the nodes in this tree, where each operator is numbered.
@@ -395,11 +395,24 @@ abstract class TreeNode[BaseType <: TreeNode[BaseType]] extends Product {
395395
}
396396

397397
/** Appends the string represent of this node and its children to the given StringBuilder. */
398-
protected def generateTreeString(depth: Int, builder: StringBuilder): StringBuilder = {
399-
builder.append(" " * depth)
400-
builder.append(simpleString)
401-
builder.append("\n")
402-
children.foreach(_.generateTreeString(depth + 1, builder))
398+
protected def generateTreeString(
399+
depth: Int, lastChildren: Seq[Boolean], builder: StringBuilder): StringBuilder = {
400+
val prefix = if (depth == 0) {
401+
""
402+
} else {
403+
(lastChildren.init.map { isLast =>
404+
if (isLast) " " else ": "
405+
} :+ (if (lastChildren.last) s"+- " else ":- ")).mkString
406+
}
407+
408+
val head = prefix + simpleString
409+
builder.append(head + "\n")
410+
411+
if (children.nonEmpty) {
412+
children.init.foreach(_.generateTreeString(depth + 1, lastChildren :+ false, builder))
413+
children.last.generateTreeString(depth + 1, lastChildren :+ true, builder)
414+
}
415+
403416
builder
404417
}
405418

0 commit comments

Comments
 (0)