Skip to content

Commit

Permalink
fix: invalid cases
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Nov 22, 2023
1 parent 1fa00e7 commit b118db8
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 12 deletions.
39 changes: 34 additions & 5 deletions packages/vite/src/node/__tests__/__snapshots__/utils.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,43 @@ exports[`generateCodeFrames > end 5`] = `
"
`;

exports[`generateCodeFrames > end 6`] = `
"
1 | import foo from './foo'
| ^^^^^^^^^^^^^^^^^^^^^^^
2 | foo()
| ^^^^^
"
`;

exports[`generateCodeFrames > invalid start > end 1`] = `
"
1 | import foo from './foo'
| ^
2 | foo()
"
`;

exports[`generateCodeFrames > range 1`] = `
"
1 |
2 | import foo from './foo'
3 |
1 | import foo from './foo'
2 |
3 | foo()
| ^
4 | // 1
5 | // 2
"
`;

exports[`generateCodeFrames > range 2`] = `
"
1 | import foo from './foo'
2 |
3 | foo()
| ^^^^^
4 | // 1
| ^
4 | foo()
5 |
5 | // 2
"
`;

Expand Down
20 changes: 16 additions & 4 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,10 @@ foo()
import foo from './foo'
foo()
// bar
// baz
`
// 1
// 2
// 3
`.trim()

const expectSnapshot = (value: string) => {
try {
Expand Down Expand Up @@ -226,10 +226,22 @@ foo()
expectSnapshot(generateCodeFrame(source, 0, 29))
expectSnapshot(generateCodeFrame(source, 0, source.length))
expectSnapshot(generateCodeFrame(source, 0, source.length + 1))
expectSnapshot(generateCodeFrame(source, 0, source.length + 100))
})

test('range', () => {
expectSnapshot(generateCodeFrame(longSource, { line: 3, column: 0 }))
expectSnapshot(
generateCodeFrame(
longSource,
{ line: 3, column: 0 },
{ line: 4, column: 0 },
),
)
})

test('invalid start > end', () => {
expectSnapshot(generateCodeFrame(source, 2, 0))
})
})

Expand Down
8 changes: 5 additions & 3 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -505,8 +505,11 @@ export function generateCodeFrame(
start: number | Pos = 0,
end?: number | Pos,
): string {
start = posToNumber(source, start)
end = end !== undefined ? posToNumber(source, end) : start
start = Math.max(posToNumber(source, start), 0)
end = Math.min(
end !== undefined ? posToNumber(source, end) : start,
source.length,
)
const lines = source.split(splitRE)
let count = 0
const res: string[] = []
Expand All @@ -530,7 +533,6 @@ export function generateCodeFrame(
end > count ? lineLength - pad : end - start,
)
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length))
count++
} else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1)
Expand Down

0 comments on commit b118db8

Please sign in to comment.