MCPcopy Create free account
hub / github.com/avajs/ava / excerptCode

Function excerptCode

lib/code-excerpt.js:11–49  ·  view source on GitHub ↗
(source, options = {})

Source from the content-addressed store, hash-verified

9 ' '.repeat(Math.max(0, String(maxLineNumber).length - String(lineNumber).length)) + lineNumber;
10
11export 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}

Callers

nothing calls this directly

Calls 1

formatLineNumberFunction · 0.85

Tested by

no test coverage detected