-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathcode-excerpt.js
97 lines (74 loc) · 2.16 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import {pathToFileURL} from 'node:url';
import {Chalk} from 'chalk'; // eslint-disable-line unicorn/import-style
import {test} from 'tap';
import {temporaryFile, temporaryWriteSync} from 'tempy';
import {set as setChalk} from '../lib/chalk.js';
import codeExcerpt from '../lib/code-excerpt.js';
setChalk({level: 1});
const chalk = new Chalk({level: 1});
test('read code excerpt', t => {
const file = pathToFileURL(temporaryWriteSync(`function a() {
alert();
}`));
const excerpt = codeExcerpt({
file, line: 2, isWithinProject: true, isDependency: false,
});
const expected = [
` ${chalk.grey('1:')} function a() {`,
chalk.bgRed.bold(' 2: alert(); '),
` ${chalk.grey('3:')} } `,
].join('\n');
t.equal(excerpt, expected);
t.end();
});
test('truncate lines', t => {
const file = pathToFileURL(temporaryWriteSync(`function a() {
alert();
}`));
const excerpt = codeExcerpt({
file, line: 2, isWithinProject: true, isDependency: false,
}, {maxWidth: 14});
const expected = [
` ${chalk.grey('1:')} functio…`,
chalk.bgRed.bold(' 2: alert…'),
` ${chalk.grey('3:')} } `,
].join('\n');
t.equal(excerpt, expected);
t.end();
});
test('format line numbers', t => {
const file = pathToFileURL(temporaryWriteSync(`
function a() {
alert();
}`));
const excerpt = codeExcerpt({
file, line: 10, isWithinProject: true, isDependency: false,
});
const expected = [
` ${chalk.grey(' 9:')} function a() {`,
chalk.bgRed.bold(' 10: alert(); '),
` ${chalk.grey('11:')} } `,
].join('\n');
t.equal(excerpt, expected);
t.end();
});
test('noop if file cannot be read', t => {
const file = pathToFileURL(temporaryFile());
const excerpt = codeExcerpt({
file, line: 10, isWithinProject: true, isDependency: false,
});
t.equal(excerpt, null);
t.end();
});
test('noop if file is not within project', t => {
const excerpt = codeExcerpt({isWithinProject: false, file: import.meta.url, line: 1});
t.equal(excerpt, null);
t.end();
});
test('noop if file is a dependency', t => {
const excerpt = codeExcerpt({
isWithinProject: true, isDependency: true, file: import.meta.url, line: 1,
});
t.equal(excerpt, null);
t.end();
});