Format elm compiler errors in terminal.

This commit is contained in:
Dillon Kearns 2021-06-24 08:53:26 -07:00
parent 0dd2f8ecb6
commit bc78f9cb1f
2 changed files with 61 additions and 1 deletions

View File

@ -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));

View File

@ -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 };