Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shows location of error in code when using cli (revised again) #73

Closed
wants to merge 10 commits into from
24 changes: 24 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const argv = require('yargs')
}).argv;
const glob = require('globby').sync;
const read = require('read-input');
const chalk = require('chalk');
const ejsLint = require('./index.js');

const opts = {
Expand All @@ -33,7 +34,9 @@ read(glob(argv._))
errored = true;
let message = `${err.message} (${err.line}:${err.column})`;
if (file.name) message += ` in ${file.name}`;
message += `\n${errorContext(err, file)}`;
console.error(message);

}
});
if (errored) process.exit(1);
Expand All @@ -42,3 +45,24 @@ read(glob(argv._))
console.error(err);
process.exit(1);
});

function errorContext(err, file) {
const lines = file.data.split(/\r?\n/);
const lineText = lines[err.line - 1];
const before = lineText.substr(0, err.column - 1);
const duringText = lineText.substr(err.column - 1, 1);
const during = chalk.bgRed(duringText);
const after = lineText.substr(err.column);
const caret = '^';
const lineBreak = '\n';
const caretLine = addSpaces(err.column - 1) + caret;
return before + during + after + lineBreak +caretLine;
}

function addSpaces(n) {
let str = '';
for (let i=0; i<n; i++) {
str += ' ';
}
return str;
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"unit": "nyc --check-coverage mocha --ui tdd --check-leaks"
},
"dependencies": {
"chalk": "^4.0.0",
"colors": "^1.4.0",
kenirwin marked this conversation as resolved.
Show resolved Hide resolved
"ejs": "3.0.1",
"ejs-include-regex": "^1.0.0",
"globby": "^11.0.0",
Expand Down
3 changes: 2 additions & 1 deletion test/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ suite('cli', () => {
});
test('invalid input', (done) => {
execFile(ejslint, ['test/fixtures/invalid.ejs'], (err, stdout, stderr) => {
const expectedContext = `\n<% ] %>\n ^`;
assert.equal(err.code, 1, 'expected exit code of 1');
assert.equal(
stderr.trim(),
'Unexpected token (3:4) in test/fixtures/invalid.ejs',
`Unexpected token (3:4) in test/fixtures/invalid.ejs${expectedContext}`,
);
done();
});
Expand Down