Commit c3f3a829 authored by Tasso Evangelista's avatar Tasso Evangelista Committed by GitHub

Merge pull request #887 from RocketChat/improve/eslint

[IMPROVE] Update ESLint rules following Rocket.Chat guidelines
parents 8a484df6 154a8516
......@@ -8,9 +8,12 @@ charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{js,coffee,html,less,json}]
[*.{js,coffee,html,less,css,json}]
indent_style = tab
[*.i18n.json]
indent_style = space
indent_size = 4
indent_size = 2
[*.md]
trim_trailing_whitespace = false
node_modules
app
e2e
src/public/lib/bugsnag.js
src/public/vendor/*
scripts/istanbul-reporter.js
/node_modules
/app
/src/public/lib/bugsnag.js
/src/public/vendor/*
/scripts/istanbul-reporter.js
{
"extends": [
"@rocket.chat/eslint-config"
],
"globals": {
"_": false,
"Bugsnag": false
}
}
{
"parserOptions": {
"sourceType": "module"
},
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true,
"jquery": true
},
"rules": {
"no-var": 2,
"prefer-const": 2,
"no-multi-spaces": 2,
"no-eval": 2,
"no-extend-native": 2,
"no-multi-str": 2,
"no-use-before-define": 2,
"no-const-assign": 2,
"no-cond-assign": 2,
"no-constant-condition": 2,
"no-control-regex": 2,
"no-debugger": 2,
"no-delete-var": 2,
"no-dupe-keys": 2,
"no-dupe-args": 2,
"no-duplicate-case": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast": 2,
"no-extra-semi": 2,
"no-fallthrough": 2,
"no-func-assign": 2,
"no-inner-declarations": [2, "functions"],
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-mixed-spaces-and-tabs": 2,
"no-sparse-arrays": 2,
"no-negated-in-lhs": 2,
"no-obj-calls": 2,
"no-octal": 2,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-undef": 2,
"no-unreachable": 2,
"no-unused-vars": [2, {
"vars": "all",
"args": "after-used"
}],
"no-lonely-if": 2,
"no-trailing-spaces": 2,
"complexity": [1, 31],
"space-in-parens": [2, "never"],
"space-before-function-paren": [2, "always"],
"space-before-blocks": [2, "always"],
"indent": [2, 4, {"SwitchCase": 1}],
"keyword-spacing": 2,
"block-spacing": 2,
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
"computed-property-spacing": 2,
"comma-spacing": 2,
"comma-style": 2,
"guard-for-in": 2,
"wrap-iife": 2,
"block-scoped-var": 2,
"curly": [2, "all"],
"eqeqeq": [2, "allow-null"],
"new-cap": [2, {
"capIsNewExceptions": ["Match.Optional", "Match.Maybe", "Match.ObjectIncluding"]
}],
"use-isnan": 2,
"valid-typeof": 2,
"linebreak-style": [2, "unix"],
"semi": [2, "always"]
},
"globals": {
"_" : false,
"Bugsnag" : false
}
}
......@@ -127,7 +127,8 @@ Using [electron-mocha](https://github.com/jprichardson/electron-mocha) test runn
yarn e2e
```
Using [mocha](https://mochajs.org/) test runner and [spectron](http://electron.atom.io/spectron/). This task searches for all files in `e2e` directory which respect pattern `*.e2e.js`.
Using [mocha](https://mochajs.org/) test runner and [spectron](http://electron.atom.io/spectron/).
This task searches for all files in `src/e2e` directory which respect pattern `*.e2e.js`.
### Code coverage
......
import { expect } from 'chai';
import { app, startApp, stopApp } from './utils';
import packageJson from '../package.json';
describe('application', function () {
before(startApp);
after(stopApp);
it('shows the main window', async function () {
expect(await app.browserWindow.isVisible()).to.be.true;
expect(await app.browserWindow.getTitle()).to.be.equal(packageJson.productName);
});
});
import path from 'path';
import electron from 'electron';
import { Application } from 'spectron';
export let app = null;
let logFetchInterval = null;
export async function startApp () {
this.timeout(10000);
app = new Application({
path: electron,
cwd: process.cwd(),
args: [path.join(__dirname, '..')],
quitTimeout: 5000,
startTimeout: 5000,
waitTimeout: 5000,
});
await app.start();
await app.client.waitUntilWindowLoaded();
logFetchInterval = setInterval(fetchLogs, 100);
};
export async function stopApp () {
this.timeout(10000);
if (app && app.isRunning()) {
clearInterval(logFetchInterval);
fetchLogs();
await app.stop();
app = null;
}
};
const fetchLogs = async () => {
const logs = await app.client.getMainProcessLogs();
logs.forEach(log => console.log(log));
};
export const menuItem = (menuId, cb) => ({
get exists() {
return app.client.execute((menuId) => {
const { Menu } = require('electron').remote;
const appMenu = Menu.getApplicationMenu();
const menuItem = appMenu.getMenuItemById(menuId);
return !!menuItem;
}, menuId).then(({ value }) => value);
},
get enabled() {
return app.client.execute((menuId) => {
const { Menu } = require('electron').remote;
const appMenu = Menu.getApplicationMenu();
const menuItem = appMenu.getMenuItemById(menuId);
return menuItem.enabled;
}, menuId).then(({ value }) => value);
},
get visible() {
return app.client.execute((menuId) => {
const { Menu } = require('electron').remote;
const appMenu = Menu.getApplicationMenu();
const menuItem = appMenu.getMenuItemById(menuId);
return menuItem.visible;
}, menuId).then(({ value }) => value);
},
get label() {
return app.client.execute((menuId) => {
const { Menu } = require('electron').remote;
const appMenu = Menu.getApplicationMenu();
const menuItem = appMenu.getMenuItemById(menuId);
return menuItem.label;
}, menuId).then(({ value }) => value);
},
click() {
return app.client.execute((menuId) => {
const { Menu } = require('electron').remote;
const appMenu = Menu.getApplicationMenu();
const menuItem = appMenu.getMenuItemById(menuId);
menuItem.click();
}, menuId);
}
});
......@@ -20,7 +20,7 @@
"release": "gulp release --env=production",
"release-dev": "gulp release --env=development",
"release-mas-dev": "build --publish never --mac mas-dev --c.mac.provisioningProfile=Development.provisionprofile",
"lint": "eslint .",
"lint": "eslint src",
"pretest": "gulp build-unit-tests --env=test",
"test": "electron-mocha app/specs.js.autogenerated --renderer --require source-map-support/register",
"coverage": "npm test -- -R scripts/istanbul-reporter",
......@@ -38,6 +38,7 @@
"node-mac-notifier": "^1.1.0"
},
"devDependencies": {
"@rocket.chat/eslint-config": "^0.1.2",
"chai": "^4.1.2",
"conventional-changelog-cli": "^2.0.5",
"electron": "^2.0.9",
......
import './branding/branding.js';
import { start } from './scripts/start';
import { remote } from 'electron';
const app = remote.app;
const { app } = remote;
Bugsnag.metaData = {
// platformId: app.process.platform,
// platformArch: app.process.arch,
// electronVersion: app.process.versions.electron,
version: app.getVersion()
// platformVersion: cordova.platformVersion
// build: appInfo.build
// platformId: app.process.platform,
// platformArch: app.process.arch,
// electronVersion: app.process.versions.electron,
version: app.getVersion(),
// platformVersion: cordova.platformVersion
// build: appInfo.build
};
Bugsnag.appVersion = app.getVersion();
......
......@@ -21,90 +21,90 @@ process.env.GOOGLE_API_KEY = 'AIzaSyADqUh_c1Qhji3Cp1NE43YrcpuPkmhXD-c';
const isMacOS = process.platform === 'darwin';
const unsetDefaultApplicationMenu = () => {
if (!isMacOS) {
Menu.setApplicationMenu(null);
return;
}
const emptyMenuTemplate = [{
submenu: [
{
label: i18n.__('Quit_App', app.getName()),
accelerator: 'CommandOrControl+Q',
click () {
app.quit();
}
}
]
}];
Menu.setApplicationMenu(Menu.buildFromTemplate(emptyMenuTemplate));
if (!isMacOS) {
Menu.setApplicationMenu(null);
return;
}
const emptyMenuTemplate = [{
submenu: [
{
label: i18n.__('Quit_App', app.getName()),
accelerator: 'CommandOrControl+Q',
click() {
app.quit();
},
},
],
}];
Menu.setApplicationMenu(Menu.buildFromTemplate(emptyMenuTemplate));
};
const setUserDataPath = () => {
const appName = app.getName();
const dirName = env.name === 'production' ? appName : `${ appName } (${ env.name })`;
const appName = app.getName();
const dirName = env.name === 'production' ? appName : `${ appName } (${ env.name })`;
app.setPath('userData', path.join(app.getPath('appData'), dirName));
app.setPath('userData', path.join(app.getPath('appData'), dirName));
};
const migrateOlderVersionUserData = () => {
const olderAppName = 'Rocket.Chat+';
const dirName = env.name === 'production' ? olderAppName : `${ olderAppName } (${ env.name })`;
const olderUserDataPath = path.join(app.getPath('appData'), dirName);
try {
jetpack.copy(olderUserDataPath, app.getPath('userData'), { overwrite: true });
jetpack.remove(olderUserDataPath);
} catch (e) {
return;
}
const olderAppName = 'Rocket.Chat+';
const dirName = env.name === 'production' ? olderAppName : `${ olderAppName } (${ env.name })`;
const olderUserDataPath = path.join(app.getPath('appData'), dirName);
try {
jetpack.copy(olderUserDataPath, app.getPath('userData'), { overwrite: true });
jetpack.remove(olderUserDataPath);
} catch (e) {
return;
}
};
const parseProtocolUrls = (args) =>
args.filter(arg => /^rocketchat:\/\/./.test(arg))
.map(uri => url.parse(uri))
.map(({ hostname, pathname, query }) => {
const { insecure } = querystring.parse(query);
return `${ insecure === 'true' ? 'http' : 'https' }://${ hostname }${ pathname || '' }`;
});
args.filter((arg) => /^rocketchat:\/\/./.test(arg))
.map((uri) => url.parse(uri))
.map(({ hostname, pathname, query }) => {
const { insecure } = querystring.parse(query);
return `${ insecure === 'true' ? 'http' : 'https' }://${ hostname }${ pathname || '' }`;
});
const addServers = (protocolUrls) => parseProtocolUrls(protocolUrls)
.forEach(serverUrl => addServer(serverUrl));
.forEach((serverUrl) => addServer(serverUrl));
const isSecondInstance = app.makeSingleInstance((argv) => {
addServers(argv.slice(2));
addServers(argv.slice(2));
});
if (isSecondInstance && !process.mas) {
app.quit();
app.quit();
}
// macOS only
app.on('open-url', (event, url) => {
event.preventDefault();
addServers([ url ]);
event.preventDefault();
addServers([url]);
});
app.on('ready', () => {
unsetDefaultApplicationMenu();
setUserDataPath();
migrateOlderVersionUserData();
unsetDefaultApplicationMenu();
setUserDataPath();
migrateOlderVersionUserData();
if (!app.isDefaultProtocolClient('rocketchat')) {
app.setAsDefaultProtocolClient('rocketchat');
}
if (!app.isDefaultProtocolClient('rocketchat')) {
app.setAsDefaultProtocolClient('rocketchat');
}
createMainWindow();
createMainWindow();
getMainWindow().then(mainWindow => certificate.initWindow(mainWindow));
getMainWindow().then((mainWindow) => certificate.initWindow(mainWindow));
autoUpdate();
autoUpdate();
});
app.on('window-all-closed', () => {
app.quit();
app.quit();
});
ipcMain.on('getSystemIdleTime', (event) => {
event.returnValue = idle.getIdleTime();
event.returnValue = idle.getIdleTime();
});
......@@ -8,127 +8,127 @@ const userDataDir = jetpack.cwd(app.getPath('userData'));
const updateSettingsFileName = 'update.json';
const loadUpdateSettings = (dir) => {
try {
return dir.read(updateSettingsFileName, 'json') || {};
} catch (error) {
console.error(error);
return {};
}
try {
return dir.read(updateSettingsFileName, 'json') || {};
} catch (error) {
console.error(error);
return {};
}
};
const appUpdateSettings = loadUpdateSettings(appDir);
const userUpdateSettings = loadUpdateSettings(userDataDir);
const updateSettings = (() => {
const defaultUpdateSettings = { autoUpdate: true };
const defaultUpdateSettings = { autoUpdate: true };
if (appUpdateSettings.forced) {
return Object.assign({}, defaultUpdateSettings, appUpdateSettings);
} else {
return Object.assign({}, defaultUpdateSettings, appUpdateSettings, userUpdateSettings);
}
if (appUpdateSettings.forced) {
return Object.assign({}, defaultUpdateSettings, appUpdateSettings);
} else {
return Object.assign({}, defaultUpdateSettings, appUpdateSettings, userUpdateSettings);
}
})();
delete updateSettings.forced;
const saveUpdateSettings = () => {
if (appUpdateSettings.forced) {
return;
}
if (appUpdateSettings.forced) {
return;
}
userDataDir.write(updateSettingsFileName, userUpdateSettings, { atomic: true });
userDataDir.write(updateSettingsFileName, userUpdateSettings, { atomic: true });
};
let checkForUpdatesEvent;
function updateDownloaded () {
dialog.showMessageBox({
title: i18n.__('Update_ready'),
message: i18n.__('Update_ready_message'),
buttons: [
i18n.__('Update_Install_Later'),
i18n.__('Update_Install_Now')
],
defaultId: 1
}, (response) => {
if (response === 0) {
dialog.showMessageBox({
title: i18n.__('Update_installing_later'),
message: i18n.__('Update_installing_later_message')
});
} else {
autoUpdater.quitAndInstall();
setTimeout(() => app.quit(), 1000);
}
});
function updateDownloaded() {
dialog.showMessageBox({
title: i18n.__('Update_ready'),
message: i18n.__('Update_ready_message'),
buttons: [
i18n.__('Update_Install_Later'),
i18n.__('Update_Install_Now'),
],
defaultId: 1,
}, (response) => {
if (response === 0) {
dialog.showMessageBox({
title: i18n.__('Update_installing_later'),
message: i18n.__('Update_installing_later_message'),
});
} else {
autoUpdater.quitAndInstall();
setTimeout(() => app.quit(), 1000);
}
});
}
function updateNotAvailable () {
if (checkForUpdatesEvent) {
checkForUpdatesEvent.sender.send('update-result', false);
checkForUpdatesEvent = null;
}
function updateNotAvailable() {
if (checkForUpdatesEvent) {
checkForUpdatesEvent.sender.send('update-result', false);
checkForUpdatesEvent = null;
}
}
function updateAvailable ({version}) {
if (checkForUpdatesEvent) {
checkForUpdatesEvent.sender.send('update-result', true);
checkForUpdatesEvent = null;
} else if (updateSettings.skip === version) {
return;
}
let window = new BrowserWindow({
title: i18n.__('Update_Available'),
width: 600,
height: 330,
show : false,
center: true,
resizable: false,
maximizable: false,
minimizable: false
});
window.loadURL(`file://${__dirname}/public/update.html`);
window.setMenuBarVisibility(false);
window.webContents.on('did-finish-load', () => {
window.webContents.send('new-version', version);
window.show();
});
ipcMain.once('update-response', (e, type) => {
switch (type) {
case 'skip':
userUpdateSettings.skip = version;
saveUpdateSettings();
dialog.showMessageBox({
title: i18n.__('Update_skip'),
message: i18n.__('Update_skip_message')
}, () => window.close());
break;
case 'remind':
dialog.showMessageBox({
title: i18n.__('Update_remind'),
message: i18n.__('Update_remind_message')
}, () => window.close());
break;
case 'update':
dialog.showMessageBox({
title: i18n.__('Update_downloading'),
message: i18n.__('Update_downloading_message')
}, () => window.close());
autoUpdater.downloadUpdate();
break;
}
});
window.on('closed', () => {
window = null;
ipcMain.removeAllListeners('update-response');
});
function updateAvailable({ version }) {
if (checkForUpdatesEvent) {
checkForUpdatesEvent.sender.send('update-result', true);
checkForUpdatesEvent = null;
} else if (updateSettings.skip === version) {
return;
}
let window = new BrowserWindow({
title: i18n.__('Update_Available'),
width: 600,
height: 330,
show : false,
center: true,
resizable: false,
maximizable: false,
minimizable: false,
});
window.loadURL(`file://${ __dirname }/public/update.html`);
window.setMenuBarVisibility(false);
window.webContents.on('did-finish-load', () => {
window.webContents.send('new-version', version);
window.show();
});
ipcMain.once('update-response', (e, type) => {
switch (type) {
case 'skip':
userUpdateSettings.skip = version;
saveUpdateSettings();
dialog.showMessageBox({
title: i18n.__('Update_skip'),
message: i18n.__('Update_skip_message'),
}, () => window.close());
break;
case 'remind':
dialog.showMessageBox({
title: i18n.__('Update_remind'),
message: i18n.__('Update_remind_message'),
}, () => window.close());
break;
case 'update':
dialog.showMessageBox({
title: i18n.__('Update_downloading'),
message: i18n.__('Update_downloading_message'),
}, () => window.close());
autoUpdater.downloadUpdate();
break;
}
});
window.on('closed', () => {
window = null;
ipcMain.removeAllListeners('update-response');
});
}
export const canUpdate = () =>
(process.platform === 'linux' && Boolean(process.env.APPIMAGE)) ||
(process.platform === 'linux' && Boolean(process.env.APPIMAGE)) ||
(process.platform === 'win32' && !process.windowsStore) ||
(process.platform === 'darwin' && !process.mas);
......@@ -137,28 +137,28 @@ export const canAutoUpdate = () => updateSettings.autoUpdate !== false;
export const canSetAutoUpdate = () => !appUpdateSettings.forced || appUpdateSettings.autoUpdate !== false;
export const setAutoUpdate = (canAutoUpdate) => {
if (!canSetAutoUpdate()) {
return;
}
if (!canSetAutoUpdate()) {
return;
}
updateSettings.autoUpdate = userUpdateSettings.autoUpdate = Boolean(canAutoUpdate);
saveUpdateSettings();
updateSettings.autoUpdate = userUpdateSettings.autoUpdate = Boolean(canAutoUpdate);
saveUpdateSettings();
};
ipcMain.on('can-update', (event) => {
event.returnValue = canUpdate();
event.returnValue = canUpdate();
});
ipcMain.on('can-auto-update', (event) => {
event.returnValue = canAutoUpdate();
event.returnValue = canAutoUpdate();
});
ipcMain.on('can-set-auto-update', (event) => {
event.returnValue = canSetAutoUpdate();
event.returnValue = canSetAutoUpdate();
});
ipcMain.on('set-auto-update', (event, canAutoUpdate) => {
setAutoUpdate(canAutoUpdate);
setAutoUpdate(canAutoUpdate);
});
autoUpdater.autoDownload = false;
......@@ -167,14 +167,14 @@ autoUpdater.on('update-not-available', updateNotAvailable);
autoUpdater.on('update-downloaded', updateDownloaded);
ipcMain.on('check-for-updates', (event) => {
if (canAutoUpdate() && canUpdate()) {
checkForUpdatesEvent = event;
autoUpdater.checkForUpdates();
}
if (canAutoUpdate() && canUpdate()) {
checkForUpdatesEvent = event;
autoUpdater.checkForUpdates();
}
});
export default () => {
if (canAutoUpdate() && canUpdate()) {