* A docstring is indented to its definition, so every line after the first * carries that indentation. Strip the common prefix (PEP 257's rule: the first * line is exempt because it starts right after the opening quotes) and drop * blank edges, so the stored prose reads the same as a comment-deri
(raw: string)
| 93 | * blank edges, so the stored prose reads the same as a comment-derived one. |
| 94 | */ |
| 95 | function dedentDocstring(raw: string): string { |
| 96 | const lines = raw.replace(/\r\n?/g, '\n').split('\n').map((line) => { |
| 97 | let column = 0; |
| 98 | return Array.from(line, (char) => { |
| 99 | const width = char === '\t' ? 8 - column % 8 : 1; |
| 100 | column += width; |
| 101 | return char === '\t' ? ' '.repeat(width) : char; |
| 102 | }).join(''); |
| 103 | }); |
| 104 | const rest = lines.slice(1).filter((l) => l.trim().length > 0); |
| 105 | const indent = rest.length === 0 |
| 106 | ? 0 |
| 107 | : Math.min(...rest.map((l) => l.length - l.trimStart().length)); |
| 108 | const out = [ |
| 109 | lines[0]?.trim() ?? '', |
| 110 | ...lines.slice(1).map((l) => l.slice(indent).trimEnd()), |
| 111 | ]; |
| 112 | while (out.length > 0 && out[0]!.trim() === '') out.shift(); |
| 113 | while (out.length > 0 && out[out.length - 1]!.trim() === '') out.pop(); |
| 114 | return out.join('\n'); |
| 115 | } |