From bc78f9cb1ff29b85d8f7193df683b3cc13b5429c Mon Sep 17 00:00:00 2001 From: Dillon Kearns Date: Thu, 24 Jun 2021 08:53:26 -0700 Subject: [PATCH] Format elm compiler errors in terminal. --- generator/src/dev-server.js | 4 ++- generator/src/error-formatter.js | 58 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 generator/src/error-formatter.js diff --git a/generator/src/dev-server.js b/generator/src/dev-server.js index 7d037b15..233e954b 100644 --- a/generator/src/dev-server.js +++ b/generator/src/dev-server.js @@ -10,6 +10,7 @@ const codegen = require("./codegen.js"); const kleur = require("kleur"); const serveStatic = require("serve-static"); const connect = require("connect"); +const { restoreColor } = require("./error-formatter"); let Elm; async function start(options) { @@ -262,7 +263,8 @@ async function start(options) { } } } catch (error) { - console.log({ error }); + console.log(restoreColor(error)); + if (req.url.includes("content.json")) { res.writeHead(500, { "Content-Type": "application/json" }); res.end(JSON.stringify(error.errorsJson)); diff --git a/generator/src/error-formatter.js b/generator/src/error-formatter.js new file mode 100644 index 00000000..3ff33a85 --- /dev/null +++ b/generator/src/error-formatter.js @@ -0,0 +1,58 @@ +const kleur = require("kleur"); + +/* Thanks to elm-live for this code! + https://github.com/wking-io/elm-live/blob/e317b4914c471addea7243c47f28dcebe27a5d36/lib/src/build.js#L65 + */ + +/** + * parseHeader :: (String, String) -> String + * + * This function takes in the error title and the path to the file with the error and formats it like elm make's regular output + **/ +const parseHeader = (title, path) => + kleur.cyan( + `-- ${title.replace("-", " ")} --------------- ${path || ""} +` + ); + +/** + * parseMsg :: String|Object -> String + * + * This function takes in the error message and makes sure that it has the proper formatting + **/ +function parseMsg(msg) { + if (typeof msg === "string") { + return msg; + } else { + if (msg.underline) { + return kleur.underline(msg.string); + } else if (msg.color) { + return kleur[msg.color.toLowerCase()](msg.string); + } else { + return msg.string; + } + } +} + +/** + * parseMsg :: { errors: Array } -> String + * + * This function takes in the array of compiler errors and maps over them to generate a formatted compiler error + **/ +const restoreColor = (error) => { + return JSON.parse(error) + .errors.map(({ problems, path }) => + problems.map(restoreProblem(path)).join("\n\n\n") + ) + .join("\n\n\n\n\n"); +}; + +/** + * parseMsg :: { errors: Array } -> String + * + * This function takes in the array of compiler errors and maps over them to generate a formatted compiler error + **/ +const restoreProblem = (path) => ({ title, message }) => + [parseHeader(title, path), ...message.map(parseMsg)].join(""); + +module.exports = { restoreColor };