MagicMirror/js/check_config.js

68 lines
1.9 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");
2021-01-05 19:01:59 +01:00
const rootPath = path.resolve(`${__dirname}/../`);
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!
2021-01-05 19:01:59 +01:00
return path.resolve(process.env.MM_CONFIG_FILE || `${rootPath}/config/config.js`);
}
/**
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-06-20 12:07:04 +02:00
Log.error(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
2021-01-05 19:01:59 +01:00
const configFile = fs.readFileSync(configFileName, "utf-8");
const errors = linter.verify(configFile);
if (errors.length === 0) {
Log.info(Utils.colors.pass("Your configuration file doesn't contain syntax errors :)"));
} else {
Log.error(Utils.colors.error("Your configuration file contains syntax errors :("));
for (const error of errors) {
Log.error(`Line ${error.line} column ${error.column}: ${error.message}`);
}
2021-01-05 19:01:59 +01:00
}
2018-01-25 20:07:51 +01:00
}
checkConfigFile();