From ac5678eb92fae9129b3d3cb587e3c8b5aeae50d1 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 17 Jun 2020 17:17:14 +0300 Subject: [PATCH] Add better error messages --- index.js | 43 ++++++++++++++++++++++++++++++++++++++----- json.js | 4 ++++ package.json | 10 +++++----- stream.js | 2 +- 4 files changed, 48 insertions(+), 11 deletions(-) create mode 100644 json.js diff --git a/index.js b/index.js index 0f0c93c..0f9279e 100755 --- a/index.js +++ b/index.js @@ -3,11 +3,9 @@ const os = require('os') const fs = require('fs') const path = require('path') -const JSON = require('lossless-json') +const JSON = require('./json') const std = require('./std') -JSON.config({circularRefs: false}) - try { require(path.join(os.homedir(), '.fxrc')) // Should be required before config.js usage. } catch (err) { @@ -91,7 +89,13 @@ function handle(input) { args.shift() } - const json = JSON.parse(input) + let json + try { + json = JSON.parse(input) + } catch (e) { + printError(e, input) + process.exit(1) + } if (args.length === 0 && stdout.isTTY) { require('./fx')(filename, json) @@ -101,7 +105,6 @@ function handle(input) { apply(json) } - function apply(json) { let output = json @@ -139,3 +142,33 @@ function snippet(i, code) { const chalk = require('chalk') return `\n ${pre} ${chalk.red.underline(code)} ${post}\n` } + +function printError(e, input) { + if (e.char) { + let lineNumber = 1, start = e.char - 70, end = e.char + 50 + if (start < 0) start = 0 + if (end > input.length) end = input.length + + for (let i = 0; i < input.length && i < start; i++) { + if (input[i] === '\n') lineNumber++ + } + + let lines = input + .substring(start, end) + .split('\n') + + if (lines.length > 1) { + lines = lines.slice(1) + lineNumber++ + } + + const chalk = require('chalk') + process.stderr.write(`\n`) + for (let line of lines) { + process.stderr.write(` ${chalk.yellow(lineNumber)} ${line}\n`) + lineNumber++ + } + process.stderr.write(`\n`) + } + process.stderr.write(e.toString() + '\n') +} diff --git a/json.js b/json.js new file mode 100644 index 0000000..1928531 --- /dev/null +++ b/json.js @@ -0,0 +1,4 @@ +'use strict' +const LosslessJSON = require('lossless-json') +LosslessJSON.config({circularRefs: false}) +module.exports.parse = LosslessJSON.parse diff --git a/package.json b/package.json index 6214747..73b0d90 100644 --- a/package.json +++ b/package.json @@ -48,14 +48,14 @@ }, "dependencies": { "@medv/blessed": "^2.0.1", - "chalk": "^3.0.0", + "chalk": "^4.1.0", "indent-string": "^4.0.0", - "lossless-json": "^1.0.3", + "lossless-json": "^1.0.4", "string-width": "^4.2.0" }, "devDependencies": { - "ava": "^2.4.0", - "pkg": "^4.4.2", - "release-it": "^12.4.3" + "ava": "^3.9.0", + "pkg": "^4.4.8", + "release-it": "^13.6.3" } } diff --git a/stream.js b/stream.js index 7a31a28..b36361f 100644 --- a/stream.js +++ b/stream.js @@ -1,5 +1,5 @@ 'use strict' -const JSON = require('lossless-json') +const JSON = require('./json') function apply(cb, input) { let json