|
| 1 | +import { build_tree, print_tree } from './utils' |
| 2 | + |
| 3 | +export namespace AsciiTree { |
| 4 | + export const generate = (paths: string[]): string => { |
| 5 | + const root = build_tree(paths) |
| 6 | + return print_tree(root).join('\n') |
| 7 | + } |
| 8 | + |
| 9 | + export const extract_paths = (text: string): string[] => { |
| 10 | + const found_paths = new Set<string>() |
| 11 | + let tree_stack: { level: number; name: string }[] = [] |
| 12 | + |
| 13 | + const lines = text.split('\n') |
| 14 | + for (const line of lines) { |
| 15 | + const idx1 = line.indexOf('├── ') |
| 16 | + const idx2 = line.indexOf('└── ') |
| 17 | + const idx = |
| 18 | + idx1 != -1 && idx2 != -1 ? Math.min(idx1, idx2) : Math.max(idx1, idx2) |
| 19 | + |
| 20 | + if (idx != -1) { |
| 21 | + const prefix = line.substring(0, idx) |
| 22 | + if (/^[│\s]*$/.test(prefix)) { |
| 23 | + let name = line.substring(idx + 4).trim() |
| 24 | + if (name.startsWith('`') && name.endsWith('`')) { |
| 25 | + name = name.substring(1, name.length - 1).trim() |
| 26 | + } |
| 27 | + const level = prefix.length |
| 28 | + |
| 29 | + while ( |
| 30 | + tree_stack.length > 0 && |
| 31 | + tree_stack[tree_stack.length - 1].level >= level |
| 32 | + ) { |
| 33 | + tree_stack.pop() |
| 34 | + } |
| 35 | + |
| 36 | + tree_stack.push({ level, name }) |
| 37 | + |
| 38 | + const full_path = tree_stack.map((n) => n.name).join('/') |
| 39 | + found_paths.add(full_path.replace(/[.?!]+$/, '')) |
| 40 | + } else { |
| 41 | + tree_stack = [] |
| 42 | + } |
| 43 | + } else { |
| 44 | + tree_stack = [] |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return Array.from(found_paths) |
| 49 | + } |
| 50 | +} |
0 commit comments