Skip to content

Commit

Permalink
Replace prettier by stylistic to lint JavaScript (#3303)
Browse files Browse the repository at this point in the history
In the latest versions of ESLint, more and more formatting rules were
removed or declared deprecated. These rules have been integrated into
the new Stylistic package (https://eslint.style/guide/why) and expanded.

Stylistic acts as a better formatter  for JavaScript as Prettier.

With this PR there are many changes that make the code more uniform, but
it may be difficult to review due to the large amount. Even if I have no
worries about the changes, perhaps this would be something for the
release after next.

Let me know what you think.
  • Loading branch information
KristjanESPERANTO authored Dec 25, 2023
1 parent 4e7b68a commit 0b70274
Show file tree
Hide file tree
Showing 64 changed files with 1,040 additions and 1,028 deletions.
50 changes: 45 additions & 5 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"extends": ["eslint:recommended", "plugin:import/recommended", "plugin:jest/recommended", "plugin:jsdoc/recommended", "plugin:prettier/recommended"],
"extends": ["eslint:recommended", "plugin:@stylistic/all-extends", "plugin:import/recommended", "plugin:jest/recommended", "plugin:jsdoc/recommended"],
"plugins": [],
"env": {
"browser": true,
"es2022": true,
"es2023": true,
"jest/globals": true,
"node": true
},
Expand All @@ -16,7 +16,7 @@
},
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2022,
"ecmaVersion": 2023,
"ecmaFeatures": {
"globalReturn": true
}
Expand All @@ -38,6 +38,46 @@
"no-throw-literal": "error",
"no-unused-vars": "off",
"no-useless-return": "error",
"prefer-template": "error"
}
"object-shorthand": ["error", "methods"],
"prefer-template": "error",
"@stylistic/array-element-newline": ["error", "consistent"],
"@stylistic/arrow-parens": ["error", "always"],
"@stylistic/brace-style": "off",
"@stylistic/comma-dangle": ["error", "never"],
"@stylistic/dot-location": ["error", "property"],
"@stylistic/function-call-argument-newline": ["error", "consistent"],
"@stylistic/function-paren-newline": ["error", "consistent"],
"@stylistic/implicit-arrow-linebreak": ["error", "beside"],
"@stylistic/max-statements-per-line": ["error", { "max": 2 }],
"@stylistic/multiline-ternary": ["error", "always-multiline"],
"@stylistic/newline-per-chained-call": ["error", { "ignoreChainWithDepth": 4 }],
"@stylistic/no-extra-parens": "off",
"@stylistic/no-tabs": "off",
"@stylistic/object-curly-spacing": ["error", "always"],
"@stylistic/object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }],
"@stylistic/operator-linebreak": ["error", "before"],
"@stylistic/padded-blocks": "off",
"@stylistic/quote-props": ["error", "as-needed"],
"@stylistic/quotes": ["error", "double"],
"@stylistic/indent": ["error", "tab"],
"@stylistic/semi": ["error", "always"],
"@stylistic/space-before-function-paren": ["error", "always"],
"@stylistic/spaced-comment": "off"
},
"overrides": [
{
"files": ["config/config.js.sample"],
"rules": {
"@stylistic/comma-dangle": "off",
"@stylistic/indent": "off",
"@stylistic/no-multi-spaces": "off"
}
},
{
"files": ["tests/configs/modules/weather/*.js"],
"rules": {
"@stylistic/quotes": "off"
}
}
]
}
2 changes: 1 addition & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.eslintignore
*.js
.prettierignore
/config
/coverage
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ _This release is scheduled to be released on 2024-01-01._
- Updated dependencies
- Clock module: optionally display current moon phase in addition to rise/set times
- electron is now per default started without gpu, if needed it must be enabled with new env var `ELECTRON_ENABLE_GPU=1` on startup (#3226)
- Replace prettier by stylistic in ESLint config to lint JavaScript

### Fixed

Expand Down
11 changes: 6 additions & 5 deletions clientonly/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@
/**
* Helper function to get server address/hostname from either the commandline or env
*/
function getServerAddress() {
function getServerAddress () {

/**
* Get command line parameters
* Assumes that a cmdline parameter is defined with `--key [value]`
* @param {string} key key to look for at the command line
* @param {string} defaultValue value if no key is given at the command line
* @returns {string} the value of the parameter
*/
function getCommandLineParameter(key, defaultValue = undefined) {
function getCommandLineParameter (key, defaultValue = undefined) {
const index = process.argv.indexOf(`--${key}`);
const value = index > -1 ? process.argv[index + 1] : undefined;
return value !== undefined ? String(value) : defaultValue;
Expand All @@ -35,7 +36,7 @@
* @param {string} url location where the server is running.
* @returns {Promise} the config
*/
function getServerConfig(url) {
function getServerConfig (url) {
// Return new pending promise
return new Promise((resolve, reject) => {
// Select http or https module, depending on requested url
Expand Down Expand Up @@ -64,7 +65,7 @@
* @param {string} message error message to print
* @param {number} code error code for the exit call
*/
function fail(message, code = 1) {
function fail (message, code = 1) {
if (message !== undefined && typeof message === "string") {
console.log(message);
} else {
Expand Down Expand Up @@ -121,4 +122,4 @@
} else {
fail();
}
})();
}());
20 changes: 10 additions & 10 deletions config/config.js.sample
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ let config = {
// - "0.0.0.0", "::" to listen on any interface
// Default, when address config is left out or empty, is "localhost"
port: 8080,
basePath: "/", // The URL path where MagicMirror² is hosted. If you are using a Reverse proxy
// you must set the sub path here. basePath must end with a /
basePath: "/", // The URL path where MagicMirror² is hosted. If you are using a Reverse proxy
// you must set the sub path here. basePath must end with a /
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses
// or add a specific IPv4 of 192.168.1.5 :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.1.5"],
// or IPv4 range of 192.168.3.0 --> 192.168.3.15 use CIDR format :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.3.0/28"],
// or add a specific IPv4 of 192.168.1.5 :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.1.5"],
// or IPv4 range of 192.168.3.0 --> 192.168.3.15 use CIDR format :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.3.0/28"],

useHttps: false, // Support HTTPS or not, default "false" will use HTTP
httpsPrivateKey: "", // HTTPS private key path, only require when useHttps is true
httpsCertificate: "", // HTTPS Certificate path, only require when useHttps is true
useHttps: false, // Support HTTPS or not, default "false" will use HTTP
httpsPrivateKey: "", // HTTPS private key path, only require when useHttps is true
httpsCertificate: "", // HTTPS Certificate path, only require when useHttps is true

language: "en",
locale: "en-US",
Expand Down Expand Up @@ -109,4 +109,4 @@ let config = {
};

/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {module.exports = config;}
if (typeof module !== "undefined") { module.exports = config; }
8 changes: 4 additions & 4 deletions js/animateCSS.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,12 @@ const AnimateCSSOut = [
* @param {string} [animation] animation name.
* @param {number} [animationTime] animation duration.
*/
function addAnimateCSS(element, animation, animationTime) {
function addAnimateCSS (element, animation, animationTime) {
const animationName = `animate__${animation}`;
const node = document.getElementById(element);
if (!node) {
// don't execute animate: we don't find div
Log.warn(`addAnimateCSS: node not found for`, element);
Log.warn("addAnimateCSS: node not found for", element);
return;
}
node.style.setProperty("--animate-duration", `${animationTime}s`);
Expand All @@ -151,12 +151,12 @@ function addAnimateCSS(element, animation, animationTime) {
* @param {string} [element] div element to animate.
* @param {string} [animation] animation name.
*/
function removeAnimateCSS(element, animation) {
function removeAnimateCSS (element, animation) {
const animationName = `animate__${animation}`;
const node = document.getElementById(element);
if (!node) {
// don't execute animate: we don't find div
Log.warn(`removeAnimateCSS: node not found for`, element);
Log.warn("removeAnimateCSS: node not found for", element);
return;
}
node.classList.remove("animate__animated", animationName);
Expand Down
12 changes: 6 additions & 6 deletions js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ process.on("uncaughtException", function (err) {
* The core app.
* @class
*/
function App() {
function App () {
let nodeHelpers = [];
let httpServer;

Expand All @@ -56,7 +56,7 @@ function App() {
* @async
* @returns {Promise<object>} the loaded config or the defaults if something goes wrong
*/
async function loadConfig() {
async function loadConfig () {
Log.log("Loading config ...");
const defaults = require(`${__dirname}/defaults`);

Expand Down Expand Up @@ -136,7 +136,7 @@ function App() {
* if it encounters one option from the deprecated.js list
* @param {object} userConfig The user config
*/
function checkDeprecatedOptions(userConfig) {
function checkDeprecatedOptions (userConfig) {
const deprecated = require(`${global.root_path}/js/deprecated`);
const deprecatedOptions = deprecated.configs;

Expand All @@ -150,7 +150,7 @@ function App() {
* Loads a specific module.
* @param {string} module The name of the module (including subpath).
*/
function loadModule(module) {
function loadModule (module) {
const elements = module.split("/");
const moduleName = elements[elements.length - 1];
let moduleFolder = `${__dirname}/../modules/${module}`;
Expand Down Expand Up @@ -204,7 +204,7 @@ function App() {
* @param {Module[]} modules All modules to be loaded
* @returns {Promise} A promise that is resolved when all modules been loaded
*/
async function loadModules(modules) {
async function loadModules (modules) {
Log.log("Loading module helpers ...");

for (let module of modules) {
Expand All @@ -221,7 +221,7 @@ function App() {
* @returns {number} A positive number if a is larger than b, a negative
* number if a is smaller and 0 if they are the same
*/
function cmpVersions(a, b) {
function cmpVersions (a, b) {
let i, diff;
const regExStrip0 = /(\.0+)+$/;
const segmentsA = a.replace(regExStrip0, "").split(".");
Expand Down
4 changes: 2 additions & 2 deletions js/check_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ const Utils = require(`${rootPath}/js/utils.js`);
* Check if set by environment variable MM_CONFIG_FILE
* @returns {string} path and filename of the config file
*/
function getConfigFile() {
function getConfigFile () {
// FIXME: This function should be in core. Do you want refactor me ;) ?, be good!
return path.resolve(process.env.MM_CONFIG_FILE || `${rootPath}/config/config.js`);
}

/**
* Checks the config file using eslint.
*/
function checkConfigFile() {
function checkConfigFile () {
const configFileName = getConfigFile();

// Check if file is present
Expand Down
36 changes: 18 additions & 18 deletions js/class.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*/
(function () {
let initializing = false;
const fnTest = /xyz/.test(function () {
const fnTest = (/xyz/).test(function () {
xyz;
})
? /\b_super\b/
Expand All @@ -36,31 +36,31 @@
// Copy the properties over onto the new prototype
for (const name in prop) {
// Check if we're overwriting an existing function
prototype[name] =
typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name])
prototype[name]
= typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name])
? (function (name, fn) {
return function () {
const tmp = this._super;
return function () {
const tmp = this._super;

// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];

// The method only need to be bound temporarily, so we
// remove it when we're done executing
const ret = fn.apply(this, arguments);
this._super = tmp;
// The method only need to be bound temporarily, so we
// remove it when we're done executing
const ret = fn.apply(this, arguments);
this._super = tmp;

return ret;
};
})(name, prop[name])
return ret;
};
}(name, prop[name]))
: prop[name];
}

/**
* The dummy class constructor
*/
function Class() {
function Class () {
// All construction is actually done in the init method
if (!initializing && this.init) {
this.init.apply(this, arguments);
Expand All @@ -78,14 +78,14 @@

return Class;
};
})();
}());

/**
* Define the clone method for later use. Helper Method.
* @param {object} obj Object to be cloned
* @returns {object} the cloned object
*/
function cloneObject(obj) {
function cloneObject (obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
Expand Down
6 changes: 3 additions & 3 deletions js/electron.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ let mainWindow;
/**
*
*/
function createWindow() {
function createWindow () {
// see https://www.electronjs.org/docs/latest/api/screen
// Create a window that fills the screen's available work area.
let electronSize = (800, 600);
Expand Down Expand Up @@ -121,11 +121,11 @@ function createWindow() {
mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
let curHeaders = details.responseHeaders;
if (config["ignoreXOriginHeader"] || false) {
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !/x-frame-options/i.test(header[0])));
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !(/x-frame-options/i).test(header[0])));
}

if (config["ignoreContentSecurityPolicy"] || false) {
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !/content-security-policy/i.test(header[0])));
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !(/content-security-policy/i).test(header[0])));
}

callback({ responseHeaders: curHeaders });
Expand Down
8 changes: 5 additions & 3 deletions js/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* MIT Licensed.
*/
const Loader = (function () {

/* Create helper variables */

const loadedModuleFiles = [];
Expand Down Expand Up @@ -196,10 +197,11 @@ const Loader = (function () {

/* Public Methods */
return {

/**
* Load all modules as defined in the config.
*/
loadModules: async function () {
async loadModules () {
let moduleData = getModuleData();

/**
Expand Down Expand Up @@ -230,7 +232,7 @@ const Loader = (function () {
* @param {Module} module The module that calls the loadFile function.
* @returns {Promise} resolved when the file is loaded
*/
loadFileForModule: async function (fileName, module) {
async loadFileForModule (fileName, module) {
if (loadedFiles.indexOf(fileName.toLowerCase()) !== -1) {
Log.log(`File already loaded: ${fileName}`);
return;
Expand All @@ -256,4 +258,4 @@ const Loader = (function () {
return loadFile(module.file(fileName));
}
};
})();
}());
Loading

0 comments on commit 0b70274

Please sign in to comment.