(source, options = {})
| 9 | ' '.repeat(Math.max(0, String(maxLineNumber).length - String(lineNumber).length)) + lineNumber; |
| 10 | |
| 11 | export default function excerptCode(source, options = {}) { |
| 12 | if (!source.isWithinProject || source.isDependency) { |
| 13 | return null; |
| 14 | } |
| 15 | |
| 16 | const {file, line} = source; |
| 17 | const maxWidth = (options.maxWidth ?? 0) || 80; |
| 18 | |
| 19 | let contents; |
| 20 | try { |
| 21 | contents = fs.readFileSync(new URL(file), 'utf8'); |
| 22 | } catch { |
| 23 | return null; |
| 24 | } |
| 25 | |
| 26 | const excerpt = codeExcerpt(contents, line, {around: 1}); |
| 27 | if (!excerpt) { |
| 28 | return null; |
| 29 | } |
| 30 | |
| 31 | const lines = excerpt.map(item => ({ |
| 32 | line: item.line, |
| 33 | value: truncate(item.value, maxWidth - String(line).length - 5), |
| 34 | })); |
| 35 | |
| 36 | const extendedWidth = Math.max(...lines.map(item => item.value.length)); |
| 37 | |
| 38 | return lines |
| 39 | .map(item => { |
| 40 | const isErrorSource = item.line === line; |
| 41 | |
| 42 | const lineNumber = formatLineNumber(item.line, line) + ':'; |
| 43 | const coloredLineNumber = isErrorSource ? lineNumber : chalk.grey(lineNumber); |
| 44 | const result = ` ${coloredLineNumber} ${item.value.padEnd(extendedWidth)}`; |
| 45 | |
| 46 | return isErrorSource ? chalk.bgRed.bold(result) : result; |
| 47 | }) |
| 48 | .join('\n'); |
| 49 | } |
nothing calls this directly
no test coverage detected