Created
October 10, 2024 19:08
-
-
Save sapslaj/638eea913e4d3e69904d5909fc355520 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Construct } from 'constructs'; | |
function renderConstructTree(scope: Construct, renderNode?: (construct: Construct) => string): string { | |
let result = ''; | |
function renderBranch(tree: Construct, branch: string) { | |
if (renderNode === undefined) { | |
renderNode = (c: Construct) => `${c.constructor.name} [${c.node.id}]`; | |
} | |
const isGraphHead = branch.length === 0; | |
if (!isGraphHead) { | |
result += '\n'; | |
} | |
result += branch; | |
if (!isGraphHead) { | |
if (!tree.node.children || tree.node.children.length === 0) { | |
result += '─ '; | |
} else { | |
result += '┬ '; | |
} | |
} | |
result += renderNode(tree); | |
let baseBranch = branch; | |
if (!isGraphHead) { | |
const isChildOfLastBranch = branch.slice(-2) === '└─'; | |
baseBranch = branch.slice(0, -2) + (isChildOfLastBranch ? ' ' : '│ '); | |
} | |
const nextBranch = baseBranch + '├─'; | |
const lastBranch = baseBranch + '└─'; | |
tree.node.children.forEach((child, index) => { | |
renderBranch(child, tree.node.children.length - 1 === index ? lastBranch : nextBranch); | |
}); | |
} | |
renderBranch(scope, ''); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment