Skip to content

Instantly share code, notes, and snippets.

@sapslaj
Created October 10, 2024 19:08
Show Gist options
  • Save sapslaj/638eea913e4d3e69904d5909fc355520 to your computer and use it in GitHub Desktop.
Save sapslaj/638eea913e4d3e69904d5909fc355520 to your computer and use it in GitHub Desktop.
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