MagicMirror/js/check_config.js

77 lines
2.1 KiB
JavaScript
Raw Normal View History

/* Magic Mirror
*
2020-06-14 11:04:11 +02:00
* Check the configuration file for errors
*
2020-06-14 11:04:11 +02:00
* By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
* MIT Licensed.
*/
const Linter = require("eslint").Linter;
const linter = new Linter();
const path = require("path");
const fs = require("fs");
const rootPath = path.resolve(__dirname + "/../");
const config = require(rootPath + "/.eslintrc.json");
2020-05-31 22:12:26 +02:00
const Log = require(rootPath + "/js/logger.js");
const Utils = require(rootPath + "/js/utils.js");
/**
2020-07-27 20:14:10 +02:00
* Returns a string with path of configuration file.
2019-06-04 10:15:50 +02:00
* Check if set by environment variable MM_CONFIG_FILE
2020-07-27 20:14:10 +02:00
*
* @returns {string} path and filename of the config file
*/
function getConfigFile() {
// FIXME: This function should be in core. Do you want refactor me ;) ?, be good!
let configFileName = path.resolve(rootPath + "/config/config.js");
if (process.env.MM_CONFIG_FILE) {
configFileName = path.resolve(process.env.MM_CONFIG_FILE);
}
return configFileName;
}
/**
2020-07-27 20:14:10 +02:00
* Checks the config file using eslint.
*/
2018-01-25 20:07:51 +01:00
function checkConfigFile() {
const configFileName = getConfigFile();
2020-06-14 11:04:11 +02:00
2018-01-25 20:07:51 +01:00
// Check if file is present
if (fs.existsSync(configFileName) === false) {
2020-05-31 22:12:26 +02:00
Log.error(Utils.colors.error("File not found: "), configFileName);
2020-06-14 11:04:11 +02:00
throw new Error("No config file present!");
2018-01-25 20:07:51 +01:00
}
2020-06-14 11:04:11 +02:00
2020-07-27 20:14:10 +02:00
// Check permission
2018-01-25 20:07:51 +01:00
try {
fs.accessSync(configFileName, fs.F_OK);
} catch (e) {
2020-05-31 22:12:26 +02:00
Log.log(Utils.colors.error(e));
2020-06-14 11:04:11 +02:00
throw new Error("No permission to access config file!");
2018-01-25 20:07:51 +01:00
}
2018-01-25 20:07:51 +01:00
// Validate syntax of the configuration file.
2020-05-31 22:12:26 +02:00
Log.info(Utils.colors.info("Checking file... "), configFileName);
2020-05-18 09:53:34 +02:00
2018-01-25 20:07:51 +01:00
// I'm not sure if all ever is utf-8
fs.readFile(configFileName, "utf-8", function (err, data) {
if (err) {
throw err;
}
const messages = linter.verify(data, config);
if (messages.length === 0) {
2020-05-31 22:12:26 +02:00
Log.log("Your configuration file doesn't contain syntax errors :)");
2018-01-25 20:07:51 +01:00
return true;
} else {
2020-05-18 09:53:34 +02:00
// In case the there errors show messages and return
2020-05-25 18:57:15 +02:00
messages.forEach((error) => {
2020-05-31 22:12:26 +02:00
Log.log("Line", error.line, "col", error.column, error.message);
});
2020-06-14 11:04:11 +02:00
throw new Error("Wrong syntax in config file!");
}
2018-01-25 20:07:51 +01:00
});
}
checkConfigFile();