-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathcode-excerpt.js
49 lines (37 loc) · 1.27 KB
/
code-excerpt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import fs from 'node:fs';
import truncate from 'cli-truncate';
import codeExcerpt from 'code-excerpt';
import {chalk} from './chalk.js';
const formatLineNumber = (lineNumber, maxLineNumber) =>
' '.repeat(Math.max(0, String(maxLineNumber).length - String(lineNumber).length)) + lineNumber;
export default function excerptCode(source, options = {}) {
if (!source.isWithinProject || source.isDependency) {
return null;
}
const {file, line} = source;
const maxWidth = (options.maxWidth ?? 0) || 80;
let contents;
try {
contents = fs.readFileSync(new URL(file), 'utf8');
} catch {
return null;
}
const excerpt = codeExcerpt(contents, line, {around: 1});
if (!excerpt) {
return null;
}
const lines = excerpt.map(item => ({
line: item.line,
value: truncate(item.value, maxWidth - String(line).length - 5),
}));
const extendedWidth = Math.max(...lines.map(item => item.value.length));
return lines
.map(item => {
const isErrorSource = item.line === line;
const lineNumber = formatLineNumber(item.line, line) + ':';
const coloredLineNumber = isErrorSource ? lineNumber : chalk.grey(lineNumber);
const result = ` ${coloredLineNumber} ${item.value.padEnd(extendedWidth)}`;
return isErrorSource ? chalk.bgRed.bold(result) : result;
})
.join('\n');
}