Skip to content

Commit

Permalink
fix: report syntax error instead of throw (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
ikatyang authored Oct 28, 2018
1 parent 042ad90 commit 8b62595
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 8 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
},
"dependencies": {
"eslint-plugin-prettier": "^2.2.0",
"lines-and-columns": "^1.1.6",
"tslib": "^1.7.1"
},
"devDependencies": {
Expand Down
43 changes: 35 additions & 8 deletions src/prettierRule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as utils from 'eslint-plugin-prettier';
import LineAndColumn from 'lines-and-columns';
import * as path from 'path';
import * as prettier from 'prettier';
import * as tslint from 'tslint';
Expand Down Expand Up @@ -60,19 +61,45 @@ class Walker extends tslint.AbstractWalker<any[]> {
}

const source = sourceFile.getFullText();
const formatted = prettier.format(source, {
parser: 'typescript',
...options,
});

if (source === formatted) {
return;
}
try {
const formatted = prettier.format(source, {
parser: 'typescript',
...options,
});

if (source === formatted) {
return;
}

reportDifferences(this, source, formatted);
reportDifferences(this, source, formatted);
} catch (e) {
// istanbul ignore else
if (e.loc) {
reportSyntaxError(this, source, e);
} else {
throw e;
}
}
}
}

function reportSyntaxError(
walkContext: tslint.WalkContext<any>,
source: string,
error: { message: string; loc: { start: { line: number; column: number } } },
) {
const locator = new LineAndColumn(source);
const offset = locator.indexForLocation({
column: error.loc.start.column - 1,
line: error.loc.start.line - 1,
})!;
const message = error.message
.split('\n')[0]
.replace(/\s*\(\d+:\d+\)\s*$/, '');
walkContext.addFailureAt(offset, 1, `SyntaxError: ${message}`);
}

function reportDifferences(
walkContext: tslint.WalkContext<any>,
source: string,
Expand Down
2 changes: 2 additions & 0 deletions tests/prettier/default/syntax-error.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
hello world
~ [SyntaxError: ';' expected.]
4 changes: 4 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,10 @@ lcid@^1.0.0:
dependencies:
invert-kv "^1.0.0"

lines-and-columns@^1.1.6:
version "1.1.6"
resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00"

load-json-file@^1.0.0:
version "1.1.0"
resolved "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0"
Expand Down

0 comments on commit 8b62595

Please sign in to comment.