Skip to content

Commit 4e88d70

Browse files
hyobanXiNiHaantfu
authored
fix: report syntax error (#4)
Co-authored-by: XiNiHa <[email protected]> Co-authored-by: Anthony Fu <[email protected]>
1 parent 1c3a9bb commit 4e88d70

File tree

3 files changed

+56
-9
lines changed

3 files changed

+56
-9
lines changed

.vscode/settings.json

+11-1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,16 @@
3636
"markdown",
3737
"json",
3838
"jsonc",
39-
"yaml"
39+
"yaml",
40+
"toml",
41+
"xml",
42+
"gql",
43+
"graphql",
44+
"astro",
45+
"css",
46+
"less",
47+
"scss",
48+
"pcss",
49+
"postcss"
4050
]
4151
}

src/rules/dprint.ts

+13-2
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,20 @@ export default {
3939
return {
4040
Program() {
4141
const sourceCode = context.sourceCode.text
42-
const formatted = format(sourceCode, context.filename, context.options[0] || {})
42+
try {
43+
const formatted = format(sourceCode, context.filename, context.options[0] || {})
4344

44-
reportDifferences(context, sourceCode, formatted)
45+
reportDifferences(context, sourceCode, formatted)
46+
}
47+
catch (error) {
48+
context.report({
49+
loc: {
50+
start: { line: 1, column: 0 },
51+
end: { line: 1, column: 0 },
52+
},
53+
message: 'Failed to format the code',
54+
})
55+
}
4556
},
4657
}
4758
},

src/rules/prettier.ts

+32-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { join } from 'node:path'
2-
import type { Rule } from 'eslint'
2+
import type { AST, Rule } from 'eslint'
33
import { createSyncFn } from 'synckit'
44
import type { Options } from 'prettier'
55
import { messages, reportDifferences } from 'eslint-formatting-reporter'
@@ -36,12 +36,38 @@ export default {
3636
return {
3737
Program() {
3838
const sourceCode = context.sourceCode.text
39-
const formatted = format(sourceCode, {
40-
filepath: context.filename,
41-
...(context.options[0] || {}),
42-
})
39+
try {
40+
const formatted = format(sourceCode, {
41+
filepath: context.filename,
42+
...(context.options[0] || {}),
43+
})
4344

44-
reportDifferences(context, sourceCode, formatted)
45+
reportDifferences(context, sourceCode, formatted)
46+
}
47+
catch (err) {
48+
if (!(err instanceof SyntaxError)) {
49+
context.report({
50+
loc: {
51+
start: { line: 1, column: 0 },
52+
end: { line: 1, column: 0 },
53+
},
54+
message: 'Failed to format the code',
55+
})
56+
return
57+
}
58+
59+
let message = `Parsing error: ${err.message}`
60+
61+
const error = (err) as SyntaxError & { codeFrame: string, loc: AST.SourceLocation }
62+
63+
if (error.codeFrame)
64+
message = message.replace(`\n${error.codeFrame}`, '')
65+
66+
if (error.loc)
67+
message = message.replace(/ \(\d+:\d+\)$/, '')
68+
69+
context.report({ message, loc: error.loc })
70+
}
4571
},
4672
}
4773
},

0 commit comments

Comments
 (0)