Skip to content

Commit

Permalink
Show location in code when using CLI (#73)
Browse files Browse the repository at this point in the history
Manually merges and resolves #73
Fixes #70
  • Loading branch information
kenirwin authored and RyanZim committed Apr 10, 2020
1 parent cb977ec commit 366ed9e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
23 changes: 23 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,6 +34,7 @@ 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);
}
});
Expand All @@ -42,3 +44,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;
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"unit": "nyc --check-coverage mocha --ui tdd --check-leaks"
},
"dependencies": {
"chalk": "^4.0.0",
"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

0 comments on commit 366ed9e

Please sign in to comment.