Commit 3d5eb4cf authored by Lukas 'Eipi' Eipert's avatar Lukas 'Eipi' Eipert Committed by Vitaly Slobodin

Run eslint on node scripts and configs

This re-adds our config/, scripts/ and *.config.js files to eslint,
together with some rules to make it a little easier for those
node-scripts, e.g. console logging or importing node or dev dependencies
should be fine.
parent 79e19c5e
/app/assets/javascripts/locale/**/app.js /app/assets/javascripts/locale/**/app.js
/config/
/builds/ /builds/
/coverage/ /coverage/
/coverage-frontend/ /coverage-frontend/
/coverage-javascript/ /coverage-javascript/
/node_modules/ /node_modules/
/public/ /public/
/scripts/
/tmp/ /tmp/
/vendor/ /vendor/
jest.config.js
jest.config.*.js
karma.config.js
webpack.config.js
...@@ -89,3 +89,15 @@ overrides: ...@@ -89,3 +89,15 @@ overrides:
rules: rules:
'@gitlab/require-i18n-strings': off '@gitlab/require-i18n-strings': off
'@gitlab/no-runtime-template-compiler': off '@gitlab/no-runtime-template-compiler': off
- files:
- 'config/**/*'
- 'scripts/**/*'
- '*.config.js'
- 'jest.*.js'
rules:
'@gitlab/require-i18n-strings': off
import/no-extraneous-dependencies: off
import/no-commonjs: off
import/no-nodejs-modules: off
filenames/match-regex: off
no-console: off
/* eslint-disable import/no-commonjs, filenames/match-regex */
const BABEL_ENV = process.env.BABEL_ENV || process.env.NODE_ENV || null; const BABEL_ENV = process.env.BABEL_ENV || process.env.NODE_ENV || null;
let presets = [ let presets = [
......
/* eslint-disable max-classes-per-file, no-underscore-dangle */
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
...@@ -7,6 +8,7 @@ const log = (msg, ...rest) => console.log(`IncrementalWebpackCompiler: ${msg}`, ...@@ -7,6 +8,7 @@ const log = (msg, ...rest) => console.log(`IncrementalWebpackCompiler: ${msg}`,
// Five seconds seem to work fine and the user can read the message // Five seconds seem to work fine and the user can read the message
const TIMEOUT = 5000; const TIMEOUT = 5000;
/* eslint-disable class-methods-use-this */
class NoopCompiler { class NoopCompiler {
constructor() { constructor() {
this.enabled = false; this.enabled = false;
...@@ -20,6 +22,7 @@ class NoopCompiler { ...@@ -20,6 +22,7 @@ class NoopCompiler {
setupMiddleware() {} setupMiddleware() {}
} }
/* eslint-enable class-methods-use-this */
class IncrementalWebpackCompiler { class IncrementalWebpackCompiler {
constructor(historyFilePath) { constructor(historyFilePath) {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* Returns true if the given module is required from eslint * Returns true if the given module is required from eslint
*/ */
const isESLint = (mod) => { const isESLint = (mod) => {
let parent = mod.parent; let { parent } = mod;
while (parent) { while (parent) {
if (parent.filename && parent.filename.includes('/eslint')) { if (parent.filename && parent.filename.includes('/eslint')) {
......
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const crypto = require('crypto'); const crypto = require('crypto');
const path = require('path');
const CACHE_PATHS = [ const CACHE_PATHS = [
'./config/webpack.config.js', './config/webpack.config.js',
......
const path = require('path'); /* eslint-disable no-inner-declarations, no-param-reassign */
const glob = require('glob');
const chalk = require('chalk'); const chalk = require('chalk');
const webpack = require('webpack');
const argumentsParser = require('commander'); const argumentsParser = require('commander');
const webpackConfig = require('./webpack.config.js'); const glob = require('glob');
const path = require('path');
const webpack = require('webpack');
const IS_EE = require('./helpers/is_ee_env'); const IS_EE = require('./helpers/is_ee_env');
const webpackConfig = require('./webpack.config.js');
const ROOT_PATH = path.resolve(__dirname, '..'); const ROOT_PATH = path.resolve(__dirname, '..');
const SPECS_PATH = /^(?:\.[\\\/])?(ee[\\\/])?spec[\\\/]javascripts[\\\/]/; const SPECS_PATH = /^(?:\.[\\/])?(ee[\\/])?spec[\\/]javascripts[\\/]/;
function exitError(message) { function exitError(message) {
console.error(chalk.red(`\nError: ${message}\n`)); console.error(chalk.red(`\nError: ${message}\n`));
...@@ -77,7 +78,7 @@ if (specFilters.length) { ...@@ -77,7 +78,7 @@ if (specFilters.length) {
root: ROOT_PATH, root: ROOT_PATH,
matchBase: true, matchBase: true,
}) })
.filter((path) => path.endsWith('spec.js')), .filter((filePath) => filePath.endsWith('spec.js')),
); );
// flatten // flatten
...@@ -97,14 +98,14 @@ if (specFilters.length) { ...@@ -97,14 +98,14 @@ if (specFilters.length) {
} }
const CE_FILES = filteredSpecFiles.filter((file) => !file.startsWith('ee')); const CE_FILES = filteredSpecFiles.filter((file) => !file.startsWith('ee'));
createContext(CE_FILES, /[^e]{2}[\\\/]spec[\\\/]javascripts$/, 'spec/javascripts'); createContext(CE_FILES, /[^e]{2}[\\/]spec[\\/]javascripts$/, 'spec/javascripts');
const EE_FILES = filteredSpecFiles.filter((file) => file.startsWith('ee')); const EE_FILES = filteredSpecFiles.filter((file) => file.startsWith('ee'));
createContext(EE_FILES, /ee[\\\/]spec[\\\/]javascripts$/, 'ee/spec/javascripts'); createContext(EE_FILES, /ee[\\/]spec[\\/]javascripts$/, 'ee/spec/javascripts');
} }
// Karma configuration // Karma configuration
module.exports = function (config) { module.exports = (config) => {
process.env.TZ = 'Etc/UTC'; process.env.TZ = 'Etc/UTC';
const fixturesPath = `tmp/tests/frontend/fixtures${IS_EE ? '-ee' : ''}`; const fixturesPath = `tmp/tests/frontend/fixtures${IS_EE ? '-ee' : ''}`;
......
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const glob = require('glob'); const SOURCEGRAPH_VERSION = require('@sourcegraph/code-host-integration/package.json').version;
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const StatsWriterPlugin = require('webpack-stats-plugin').StatsWriterPlugin;
const CompressionPlugin = require('compression-webpack-plugin'); const CompressionPlugin = require('compression-webpack-plugin');
const MonacoWebpackPlugin = require('./plugins/monaco_webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CopyWebpackPlugin = require('copy-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin');
const vendorDllHash = require('./helpers/vendor_dll_hash'); const glob = require('glob');
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const VUE_LOADER_VERSION = require('vue-loader/package.json').version;
const VUE_VERSION = require('vue/package.json').version;
const webpack = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { StatsWriterPlugin } = require('webpack-stats-plugin');
const WEBPACK_VERSION = require('webpack/package.json').version;
const createIncrementalWebpackCompiler = require('./helpers/incremental_webpack_compiler'); const createIncrementalWebpackCompiler = require('./helpers/incremental_webpack_compiler');
const IS_EE = require('./helpers/is_ee_env');
const vendorDllHash = require('./helpers/vendor_dll_hash');
const MonacoWebpackPlugin = require('./plugins/monaco_webpack');
const ROOT_PATH = path.resolve(__dirname, '..'); const ROOT_PATH = path.resolve(__dirname, '..');
const VENDOR_DLL = process.env.WEBPACK_VENDOR_DLL && process.env.WEBPACK_VENDOR_DLL !== 'false'; const VENDOR_DLL = process.env.WEBPACK_VENDOR_DLL && process.env.WEBPACK_VENDOR_DLL !== 'false';
const CACHE_PATH = process.env.WEBPACK_CACHE_PATH || path.join(ROOT_PATH, 'tmp/cache'); const CACHE_PATH = process.env.WEBPACK_CACHE_PATH || path.join(ROOT_PATH, 'tmp/cache');
const IS_PRODUCTION = process.env.NODE_ENV === 'production'; const IS_PRODUCTION = process.env.NODE_ENV === 'production';
const IS_DEV_SERVER = process.env.WEBPACK_DEV_SERVER === 'true'; const IS_DEV_SERVER = process.env.WEBPACK_DEV_SERVER === 'true';
const IS_EE = require('./helpers/is_ee_env');
const DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost'; const DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost';
const DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808; const DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808;
const DEV_SERVER_PUBLIC_ADDR = process.env.DEV_SERVER_PUBLIC_ADDR; const { DEV_SERVER_PUBLIC_ADDR } = process.env;
const DEV_SERVER_ALLOWED_HOSTS = const DEV_SERVER_ALLOWED_HOSTS =
process.env.DEV_SERVER_ALLOWED_HOSTS && process.env.DEV_SERVER_ALLOWED_HOSTS.split(','); process.env.DEV_SERVER_ALLOWED_HOSTS && process.env.DEV_SERVER_ALLOWED_HOSTS.split(',');
const DEV_SERVER_HTTPS = process.env.DEV_SERVER_HTTPS && process.env.DEV_SERVER_HTTPS !== 'false'; const DEV_SERVER_HTTPS = process.env.DEV_SERVER_HTTPS && process.env.DEV_SERVER_HTTPS !== 'false';
...@@ -38,11 +47,6 @@ const WEBPACK_OUTPUT_PATH = path.join(ROOT_PATH, 'public/assets/webpack'); ...@@ -38,11 +47,6 @@ const WEBPACK_OUTPUT_PATH = path.join(ROOT_PATH, 'public/assets/webpack');
const WEBPACK_PUBLIC_PATH = '/assets/webpack/'; const WEBPACK_PUBLIC_PATH = '/assets/webpack/';
const SOURCEGRAPH_PACKAGE = '@sourcegraph/code-host-integration'; const SOURCEGRAPH_PACKAGE = '@sourcegraph/code-host-integration';
const VUE_VERSION = require('vue/package.json').version;
const VUE_LOADER_VERSION = require('vue-loader/package.json').version;
const WEBPACK_VERSION = require('webpack/package.json').version;
const SOURCEGRAPH_VERSION = require(path.join(SOURCEGRAPH_PACKAGE, 'package.json')).version;
const SOURCEGRAPH_PATH = path.join('sourcegraph', SOURCEGRAPH_VERSION, '/'); const SOURCEGRAPH_PATH = path.join('sourcegraph', SOURCEGRAPH_VERSION, '/');
const SOURCEGRAPH_OUTPUT_PATH = path.join(WEBPACK_OUTPUT_PATH, SOURCEGRAPH_PATH); const SOURCEGRAPH_OUTPUT_PATH = path.join(WEBPACK_OUTPUT_PATH, SOURCEGRAPH_PATH);
const SOURCEGRAPH_PUBLIC_PATH = path.join(WEBPACK_PUBLIC_PATH, SOURCEGRAPH_PATH); const SOURCEGRAPH_PUBLIC_PATH = path.join(WEBPACK_PUBLIC_PATH, SOURCEGRAPH_PATH);
...@@ -67,19 +71,19 @@ function generateEntries() { ...@@ -67,19 +71,19 @@ function generateEntries() {
}); });
watchAutoEntries = [path.join(ROOT_PATH, 'app/assets/javascripts/pages/')]; watchAutoEntries = [path.join(ROOT_PATH, 'app/assets/javascripts/pages/')];
function generateAutoEntries(path, prefix = '.') { function generateAutoEntries(entryPath, prefix = '.') {
const chunkPath = path.replace(/\/index\.js$/, ''); const chunkPath = entryPath.replace(/\/index\.js$/, '');
const chunkName = chunkPath.replace(/\//g, '.'); const chunkName = chunkPath.replace(/\//g, '.');
autoEntriesMap[chunkName] = `${prefix}/${path}`; autoEntriesMap[chunkName] = `${prefix}/${entryPath}`;
} }
pageEntries.forEach((path) => generateAutoEntries(path)); pageEntries.forEach((entryPath) => generateAutoEntries(entryPath));
if (IS_EE) { if (IS_EE) {
const eePageEntries = glob.sync('pages/**/index.js', { const eePageEntries = glob.sync('pages/**/index.js', {
cwd: path.join(ROOT_PATH, 'ee/app/assets/javascripts'), cwd: path.join(ROOT_PATH, 'ee/app/assets/javascripts'),
}); });
eePageEntries.forEach((path) => generateAutoEntries(path, 'ee')); eePageEntries.forEach((entryPath) => generateAutoEntries(entryPath, 'ee'));
watchAutoEntries.push(path.join(ROOT_PATH, 'ee/app/assets/javascripts/pages/')); watchAutoEntries.push(path.join(ROOT_PATH, 'ee/app/assets/javascripts/pages/'));
} }
...@@ -198,9 +202,9 @@ module.exports = { ...@@ -198,9 +202,9 @@ module.exports = {
}, },
{ {
test: /\.js$/, test: /\.js$/,
exclude: (path) => exclude: (modulePath) =>
/node_modules\/(?!tributejs)|node_modules|vendor[\\/]assets/.test(path) && /node_modules\/(?!tributejs)|node_modules|vendor[\\/]assets/.test(modulePath) &&
!/\.vue\.js/.test(path), !/\.vue\.js/.test(modulePath),
loader: 'babel-loader', loader: 'babel-loader',
options: { options: {
cacheDirectory: path.join(CACHE_PATH, 'babel-loader'), cacheDirectory: path.join(CACHE_PATH, 'babel-loader'),
...@@ -354,7 +358,7 @@ module.exports = { ...@@ -354,7 +358,7 @@ module.exports = {
// webpack-rails only needs assetsByChunkName to function properly // webpack-rails only needs assetsByChunkName to function properly
new StatsWriterPlugin({ new StatsWriterPlugin({
filename: 'manifest.json', filename: 'manifest.json',
transform: function (data, opts) { transform(data, opts) {
const stats = opts.compiler.getStats().toJson({ const stats = opts.compiler.getStats().toJson({
chunkModules: false, chunkModules: false,
source: false, source: false,
...@@ -412,6 +416,7 @@ module.exports = { ...@@ -412,6 +416,7 @@ module.exports = {
`Warning: No vendor DLL found at: ${dll.cacheFrom}. Compiling DLL automatically.`, `Warning: No vendor DLL found at: ${dll.cacheFrom}. Compiling DLL automatically.`,
); );
// eslint-disable-next-line global-require
const dllConfig = require('./webpack.vendor.config.js'); const dllConfig = require('./webpack.vendor.config.js');
const dllCompiler = webpack(dllConfig); const dllCompiler = webpack(dllConfig);
...@@ -435,7 +440,7 @@ module.exports = { ...@@ -435,7 +440,7 @@ module.exports = {
} }
dll.exists = true; dll.exists = true;
callback(); return callback();
}); });
} }
}); });
...@@ -459,6 +464,7 @@ module.exports = { ...@@ -459,6 +464,7 @@ module.exports = {
!IS_EE && !IS_EE &&
new webpack.NormalModuleReplacementPlugin(/^ee_component\/(.*)\.vue/, (resource) => { new webpack.NormalModuleReplacementPlugin(/^ee_component\/(.*)\.vue/, (resource) => {
// eslint-disable-next-line no-param-reassign
resource.request = path.join( resource.request = path.join(
ROOT_PATH, ROOT_PATH,
'app/assets/javascripts/vue_shared/components/empty_component.js', 'app/assets/javascripts/vue_shared/components/empty_component.js',
...@@ -521,7 +527,7 @@ module.exports = { ...@@ -521,7 +527,7 @@ module.exports = {
// output the in-memory heap size upon compilation and exit // output the in-memory heap size upon compilation and exit
WEBPACK_MEMORY_TEST && { WEBPACK_MEMORY_TEST && {
apply(compiler) { apply(compiler) {
compiler.hooks.emit.tapAsync('ReportMemoryConsumptionPlugin', (compilation, callback) => { compiler.hooks.emit.tapAsync('ReportMemoryConsumptionPlugin', () => {
console.log('Assets compiled...'); console.log('Assets compiled...');
if (global.gc) { if (global.gc) {
console.log('Running garbage collection...'); console.log('Running garbage collection...');
...@@ -552,7 +558,9 @@ module.exports = { ...@@ -552,7 +558,9 @@ module.exports = {
); );
// exit in case we're running webpack-dev-server // exit in case we're running webpack-dev-server
IS_DEV_SERVER && process.exit(); if (IS_DEV_SERVER) {
process.exit();
}
}); });
}, },
}, },
......
const path = require('path'); const path = require('path');
const webpack = require('webpack'); const webpack = require('webpack');
const vendorDllHash = require('./helpers/vendor_dll_hash');
const { YarnCheck } = require('yarn-check-webpack-plugin'); const { YarnCheck } = require('yarn-check-webpack-plugin');
const vendorDllHash = require('./helpers/vendor_dll_hash');
const ROOT_PATH = path.resolve(__dirname, '..'); const ROOT_PATH = path.resolve(__dirname, '..');
......
...@@ -27,7 +27,7 @@ module.exports = (path) => { ...@@ -27,7 +27,7 @@ module.exports = (path) => {
// workaround for eslint-import-resolver-jest only resolving in test files // workaround for eslint-import-resolver-jest only resolving in test files
// see https://github.com/JoinColony/eslint-import-resolver-jest#note // see https://github.com/JoinColony/eslint-import-resolver-jest#note
if (isESLint(module)) { if (isESLint(module)) {
testMatch = testMatch.map((path) => path.replace('_spec.js', '')); testMatch = testMatch.map((modulePath) => modulePath.replace('_spec.js', ''));
} }
const TEST_FIXTURES_PATTERN = 'test_fixtures(/.*)$'; const TEST_FIXTURES_PATTERN = 'test_fixtures(/.*)$';
......
const path = require('path'); const packageJson = require('../../package.json');
const packageJson = require(path.join(process.cwd(), 'package.json'));
const blockedDependencies = packageJson.blockedDependencies || {}; const blockedDependencies = packageJson.blockedDependencies || {};
const dependencies = packageJson.dependencies; const { dependencies } = packageJson;
const devDependencies = packageJson.devDependencies; const { devDependencies } = packageJson;
const blockedDependenciesNames = Object.keys(blockedDependencies); const blockedDependenciesNames = Object.keys(blockedDependencies);
const blockedDependenciesFound = blockedDependenciesNames.filter( const blockedDependenciesFound = blockedDependenciesNames.filter(
(blockedDependency) => dependencies[blockedDependency] || devDependencies[blockedDependency], (blockedDependency) => dependencies[blockedDependency] || devDependencies[blockedDependency],
......
...@@ -7,9 +7,9 @@ if (process.env.RAILS_ENV !== 'production') { ...@@ -7,9 +7,9 @@ if (process.env.RAILS_ENV !== 'production') {
process.exit(0); process.exit(0);
} }
const path = require('path');
const fs = require('fs'); const fs = require('fs');
const glob = require('glob'); const glob = require('glob');
const path = require('path');
const pjs = require('postcss'); const pjs = require('postcss');
const paths = glob.sync('public/assets/page_bundles/_mixins_and_variables_and_functions*.css', { const paths = glob.sync('public/assets/page_bundles/_mixins_and_variables_and_functions*.css', {
......
...@@ -5,6 +5,7 @@ const { ...@@ -5,6 +5,7 @@ const {
decorateJSParserWithVueSupport, decorateJSParserWithVueSupport,
decorateExtractorWithHelpers, decorateExtractorWithHelpers,
} = require('gettext-extractor-vue'); } = require('gettext-extractor-vue');
const vue2TemplateCompiler = require('vue-template-compiler');
const ensureSingleLine = require('../../app/assets/javascripts/locale/ensure_single_line.js'); const ensureSingleLine = require('../../app/assets/javascripts/locale/ensure_single_line.js');
const args = argumentsParser const args = argumentsParser
...@@ -37,12 +38,12 @@ const jsParser = extractor.createJsParser([ ...@@ -37,12 +38,12 @@ const jsParser = extractor.createJsParser([
]); ]);
const vueParser = decorateJSParserWithVueSupport(jsParser, { const vueParser = decorateJSParserWithVueSupport(jsParser, {
vue2TemplateCompiler: require('vue-template-compiler'), vue2TemplateCompiler,
}); });
function printJson() { function printJson() {
const messages = extractor.getMessages().reduce((result, message) => { const messages = extractor.getMessages().reduce((acc, message) => {
let text = message.text; let { text } = message;
if (message.textPlural) { if (message.textPlural) {
text += `\u0000${message.textPlural}`; text += `\u0000${message.textPlural}`;
} }
...@@ -50,25 +51,35 @@ function printJson() { ...@@ -50,25 +51,35 @@ function printJson() {
message.references.forEach((reference) => { message.references.forEach((reference) => {
const filename = reference.replace(/:\d+$/, ''); const filename = reference.replace(/:\d+$/, '');
if (!Array.isArray(result[filename])) { if (!Array.isArray(acc[filename])) {
result[filename] = []; acc[filename] = [];
} }
result[filename].push([text, reference]); acc[filename].push([text, reference]);
}); });
return result; return acc;
}, {}); }, {});
console.log(JSON.stringify(messages)); console.log(JSON.stringify(messages));
} }
if (args.file) { async function main() {
vueParser.parseFile(args.file).then(() => printJson()); if (args.file) {
} else if (args.all) { return vueParser.parseFile(args.file).then(() => printJson());
vueParser.parseFilesGlob('{ee/app,app}/assets/javascripts/**/*.{js,vue}').then(() => printJson()); }
} else {
console.warn('ERROR: Please use the script correctly:'); if (args.all) {
return vueParser
.parseFilesGlob('{ee/app,app}/assets/javascripts/**/*.{js,vue}')
.then(() => printJson());
}
throw new Error('ERROR: Please use the script correctly:');
}
main().catch((error) => {
console.warn(error.message);
args.outputHelp(); args.outputHelp();
process.exit(1); process.exit(1);
} });
...@@ -31,28 +31,6 @@ let numTestFiles = 0; ...@@ -31,28 +31,6 @@ let numTestFiles = 0;
const isVerbose = process.argv.some((arg) => arg === '-v'); const isVerbose = process.argv.some((arg) => arg === '-v');
const countSourceFiles = (path) =>
forEachFileIn(path, (fileName) => {
if (fileName.endsWith('.vue') || fileName.endsWith('.js')) {
if (isVerbose) {
console.log(`source file: ${fileName}`);
}
numSourceFiles += 1;
}
});
const countTestFiles = (path) =>
forEachFileIn(path, (fileName) => {
if (fileName.endsWith('_spec.js')) {
if (isVerbose) {
console.log(`test file: ${fileName}`);
}
numTestFiles += 1;
}
});
function forEachFileIn(dirPath, callback) { function forEachFileIn(dirPath, callback) {
fs.readdir(dirPath, (err, files) => { fs.readdir(dirPath, (err, files) => {
if (err) { if (err) {
...@@ -75,6 +53,28 @@ function forEachFileIn(dirPath, callback) { ...@@ -75,6 +53,28 @@ function forEachFileIn(dirPath, callback) {
}); });
} }
const countSourceFiles = (currentPath) =>
forEachFileIn(currentPath, (fileName) => {
if (fileName.endsWith('.vue') || fileName.endsWith('.js')) {
if (isVerbose) {
console.log(`source file: ${fileName}`);
}
numSourceFiles += 1;
}
});
const countTestFiles = (currentPath) =>
forEachFileIn(currentPath, (fileName) => {
if (fileName.endsWith('_spec.js')) {
if (isVerbose) {
console.log(`test file: ${fileName}`);
}
numTestFiles += 1;
}
});
console.log(`Source directories: ${sourceDirectories.join(', ')}`); console.log(`Source directories: ${sourceDirectories.join(', ')}`);
console.log(`Test directories: ${testDirectories.join(', ')}`); console.log(`Test directories: ${testDirectories.join(', ')}`);
......
const { create } = require('istanbul-reports'); const { sync } = require('glob');
const { createCoverageMap } = require('istanbul-lib-coverage'); const { createCoverageMap } = require('istanbul-lib-coverage');
const { createContext } = require('istanbul-lib-report'); const { createContext } = require('istanbul-lib-report');
const { create } = require('istanbul-reports');
const { resolve } = require('path'); const { resolve } = require('path');
const { sync } = require('glob');
const coverageMap = createCoverageMap(); const coverageMap = createCoverageMap();
...@@ -12,7 +12,7 @@ const reportFiles = sync(`${coverageDir}/*/coverage-final.json`); ...@@ -12,7 +12,7 @@ const reportFiles = sync(`${coverageDir}/*/coverage-final.json`);
// Normalize coverage report generated by jest that has additional "data" key // Normalize coverage report generated by jest that has additional "data" key
// https://github.com/facebook/jest/issues/2418#issuecomment-423806659 // https://github.com/facebook/jest/issues/2418#issuecomment-423806659
const normalizeReport = (report) => { const normalizeReport = (report) => {
const normalizedReport = Object.assign({}, report); const normalizedReport = { ...report };
Object.entries(normalizedReport).forEach(([k, v]) => { Object.entries(normalizedReport).forEach(([k, v]) => {
if (v.data) normalizedReport[k] = v.data; if (v.data) normalizedReport[k] = v.data;
}); });
...@@ -20,11 +20,14 @@ const normalizeReport = (report) => { ...@@ -20,11 +20,14 @@ const normalizeReport = (report) => {
}; };
reportFiles reportFiles
.map((reportFile) => require(reportFile)) .map((reportFile) => {
// eslint-disable-next-line global-require, import/no-dynamic-require
return require(reportFile);
})
.map(normalizeReport) .map(normalizeReport)
.forEach((report) => coverageMap.merge(report)); .forEach((report) => coverageMap.merge(report));
const context = createContext({ coverageMap: coverageMap, dir: 'coverage-frontend' }); const context = createContext({ coverageMap, dir: 'coverage-frontend' });
['json', 'lcov', 'text-summary', 'clover', 'cobertura'].forEach((reporter) => { ['json', 'lcov', 'text-summary', 'clover', 'cobertura'].forEach((reporter) => {
create(reporter, {}).execute(context); create(reporter, {}).execute(context);
......
const Sequencer = require('@jest/test-sequencer').default; const Sequencer = require('@jest/test-sequencer').default;
const sortByPath = (test1, test2) => {
if (test1.path < test2.path) {
return -1;
}
if (test1.path > test2.path) {
return 1;
}
return 0;
};
class ParallelCISequencer extends Sequencer { class ParallelCISequencer extends Sequencer {
constructor() { constructor() {
super(); super();
...@@ -8,7 +18,7 @@ class ParallelCISequencer extends Sequencer { ...@@ -8,7 +18,7 @@ class ParallelCISequencer extends Sequencer {
} }
sort(tests) { sort(tests) {
const sortedTests = this.sortByPath(tests); const sortedTests = [...tests].sort(sortByPath);
const testsForThisRunner = this.distributeAcrossCINodes(sortedTests); const testsForThisRunner = this.distributeAcrossCINodes(sortedTests);
console.log(`CI_NODE_INDEX: ${this.ciNodeIndex}`); console.log(`CI_NODE_INDEX: ${this.ciNodeIndex}`);
...@@ -19,18 +29,6 @@ class ParallelCISequencer extends Sequencer { ...@@ -19,18 +29,6 @@ class ParallelCISequencer extends Sequencer {
return testsForThisRunner; return testsForThisRunner;
} }
sortByPath(tests) {
return tests.sort((test1, test2) => {
if (test1.path < test2.path) {
return -1;
}
if (test1.path > test2.path) {
return 1;
}
return 0;
});
}
distributeAcrossCINodes(tests) { distributeAcrossCINodes(tests) {
return tests.filter((test, index) => { return tests.filter((test, index) => {
return index % this.ciNodeTotal === this.ciNodeIndex - 1; return index % this.ciNodeTotal === this.ciNodeIndex - 1;
......
const stylelint = require('stylelint'); const stylelint = require('stylelint');
const utils = require('./stylelint-utils'); const utils = require('./stylelint-utils');
const ruleName = 'stylelint-gitlab/duplicate-selectors'; const ruleName = 'stylelint-gitlab/duplicate-selectors';
const messages = stylelint.utils.ruleMessages(ruleName, { const messages = stylelint.utils.ruleMessages(ruleName, {
...@@ -8,12 +9,13 @@ const messages = stylelint.utils.ruleMessages(ruleName, { ...@@ -8,12 +9,13 @@ const messages = stylelint.utils.ruleMessages(ruleName, {
}, },
}); });
module.exports = stylelint.createPlugin(ruleName, function (enabled) { module.exports = stylelint.createPlugin(ruleName, (enabled) => {
if (!enabled) { if (!enabled) {
return; return;
} }
return function (root, result) { // eslint-disable-next-line consistent-return
return (root, result) => {
const selectorGroups = {}; const selectorGroups = {};
utils.createPropertiesHashmap(root, result, ruleName, messages, selectorGroups, true); utils.createPropertiesHashmap(root, result, ruleName, messages, selectorGroups, true);
}; };
......
...@@ -10,12 +10,13 @@ const messages = stylelint.utils.ruleMessages(ruleName, { ...@@ -10,12 +10,13 @@ const messages = stylelint.utils.ruleMessages(ruleName, {
}, },
}); });
module.exports = stylelint.createPlugin(ruleName, function (enabled) { module.exports = stylelint.createPlugin(ruleName, (enabled) => {
if (!enabled) { if (!enabled) {
return; return;
} }
return function (root, result) { // eslint-disable-next-line consistent-return
return (root, result) => {
utils.createPropertiesHashmap(root, result, ruleName, messages, utilityClasses, false); utils.createPropertiesHashmap(root, result, ruleName, messages, utilityClasses, false);
}; };
}); });
......
const sass = require('node-sass');
const postcss = require('postcss');
const fs = require('fs'); const fs = require('fs');
const sass = require('node-sass');
const path = require('path'); const path = require('path');
const postcss = require('postcss');
const prettier = require('prettier'); const prettier = require('prettier');
const utils = require('./stylelint-utils'); const utils = require('./stylelint-utils');
const ROOT_PATH = path.resolve(__dirname, '../../..'); const ROOT_PATH = path.resolve(__dirname, '../../..');
const hashMapPath = path.resolve(__dirname, './utility-classes-map.js'); const hashMapPath = path.resolve(__dirname, './utility-classes-map.js');
...@@ -22,19 +23,28 @@ sass.render( ...@@ -22,19 +23,28 @@ sass.render(
includePaths: [path.resolve(ROOT_PATH, 'node_modules/bootstrap/scss')], includePaths: [path.resolve(ROOT_PATH, 'node_modules/bootstrap/scss')],
}, },
(err, result) => { (err, result) => {
if (err) console.error('Error ', err); if (err) {
return console.error('Error ', err);
}
const cssResult = result.css.toString(); const cssResult = result.css.toString();
// We just use postcss to create a CSS tree // We just use postcss to create a CSS tree
postcss([]) return postcss([])
.process(cssResult, { .process(cssResult, {
// This suppresses a postcss warning // This suppresses a postcss warning
from: undefined, from: undefined,
}) })
.then((result) => { .then((processedResult) => {
const selectorGroups = {}; const selectorGroups = {};
utils.createPropertiesHashmap(result.root, result, null, null, selectorGroups, true); utils.createPropertiesHashmap(
processedResult.root,
processedResult,
null,
null,
selectorGroups,
true,
);
const prettierOptions = prettier.resolveConfig.sync(hashMapPath); const prettierOptions = prettier.resolveConfig.sync(hashMapPath);
const prettyHashmap = prettier.format( const prettyHashmap = prettier.format(
...@@ -42,12 +52,12 @@ sass.render( ...@@ -42,12 +52,12 @@ sass.render(
prettierOptions, prettierOptions,
); );
fs.writeFile(hashMapPath, prettyHashmap, function (err) { fs.writeFile(hashMapPath, prettyHashmap, (e) => {
if (err) { if (e) {
return console.log(err); return console.log(e);
} }
console.log('The file was saved!'); return console.log('The file was saved!');
}); });
}); });
}, },
......
const stylelint = require('stylelint');
const md5 = require('md5'); const md5 = require('md5');
const stylelint = require('stylelint');
module.exports.createPropertiesHashmap = ( module.exports.createPropertiesHashmap = (
ruleRoot, ruleRoot,
...@@ -15,7 +15,7 @@ module.exports.createPropertiesHashmap = ( ...@@ -15,7 +15,7 @@ module.exports.createPropertiesHashmap = (
if ( if (
rule && rule &&
rule.parent && rule.parent &&
rule.parent.type != 'atrule' && rule.parent.type !== 'atrule' &&
!( !(
selector.includes('-webkit-') || selector.includes('-webkit-') ||
selector.includes('-moz-') || selector.includes('-moz-') ||
...@@ -25,7 +25,7 @@ module.exports.createPropertiesHashmap = ( ...@@ -25,7 +25,7 @@ module.exports.createPropertiesHashmap = (
) )
) { ) {
let cssArray = []; let cssArray = [];
rule.nodes.forEach(function (property) { rule.nodes.forEach((property) => {
const { prop, value } = property; const { prop, value } = property;
if (property && value) { if (property && value) {
const propval = `${prop}${value}${property.important ? '!important' : ''}`; const propval = `${prop}${value}${property.important ? '!important' : ''}`;
...@@ -41,11 +41,11 @@ module.exports.createPropertiesHashmap = ( ...@@ -41,11 +41,11 @@ module.exports.createPropertiesHashmap = (
const selObj = selectorGroups[hashValue]; const selObj = selectorGroups[hashValue];
const selectorLine = `${selector} (${ const selectorLine = `${selector} (${
rule.source.input.file ? rule.source.input.file + ' -' : '' rule.source.input.file ? `${rule.source.input.file} -` : ''
}${rule.source.start.line}:${rule.source.start.column})`; }${rule.source.start.line}:${rule.source.start.column})`;
if (selObj) { if (selObj) {
if (selectorGroups[hashValue].selectors.indexOf(selector) == -1) { if (selectorGroups[hashValue].selectors.indexOf(selector) === -1) {
let lastSelector = let lastSelector =
selectorGroups[hashValue].selectors[selectorGroups[hashValue].selectors.length - 1]; selectorGroups[hashValue].selectors[selectorGroups[hashValue].selectors.length - 1];
...@@ -67,6 +67,7 @@ module.exports.createPropertiesHashmap = ( ...@@ -67,6 +67,7 @@ module.exports.createPropertiesHashmap = (
} }
} }
} else if (addSelectors) { } else if (addSelectors) {
// eslint-disable-next-line no-param-reassign
selectorGroups[hashValue] = { selectorGroups[hashValue] = {
selectors: [selectorLine], selectors: [selectorLine],
}; };
......
...@@ -2,8 +2,8 @@ const nodemon = require('nodemon'); ...@@ -2,8 +2,8 @@ const nodemon = require('nodemon');
const DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost'; const DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost';
const DEV_SERVER_PORT = process.env.DEV_SERVER_PORT || '3808'; const DEV_SERVER_PORT = process.env.DEV_SERVER_PORT || '3808';
const STATIC_MODE = process.env.DEV_SERVER_STATIC && process.env.DEV_SERVER_STATIC != 'false'; const STATIC_MODE = process.env.DEV_SERVER_STATIC && process.env.DEV_SERVER_STATIC !== 'false';
const DLL_MODE = process.env.WEBPACK_VENDOR_DLL && process.env.WEBPACK_VENDOR_DLL != 'false'; const DLL_MODE = process.env.WEBPACK_VENDOR_DLL && process.env.WEBPACK_VENDOR_DLL !== 'false';
const baseConfig = { const baseConfig = {
ignoreRoot: ['.git', 'node_modules/*/'], ignoreRoot: ['.git', 'node_modules/*/'],
...@@ -30,7 +30,7 @@ if (STATIC_MODE) { ...@@ -30,7 +30,7 @@ if (STATIC_MODE) {
// run webpack through webpack-dev-server, optionally compiling a DLL to reduce memory // run webpack through webpack-dev-server, optionally compiling a DLL to reduce memory
else { else {
let watch = ['config/webpack.config.js']; const watch = ['config/webpack.config.js'];
// if utilizing the vendor DLL, we need to restart the process when dependency changes occur // if utilizing the vendor DLL, we need to restart the process when dependency changes occur
if (DLL_MODE) { if (DLL_MODE) {
...@@ -51,7 +51,7 @@ else { ...@@ -51,7 +51,7 @@ else {
// print useful messages for nodemon events // print useful messages for nodemon events
nodemon nodemon
.on('start', function () { .on('start', () => {
console.log(`Starting webpack webserver on http://${DEV_SERVER_HOST}:${DEV_SERVER_PORT}`); console.log(`Starting webpack webserver on http://${DEV_SERVER_HOST}:${DEV_SERVER_PORT}`);
if (STATIC_MODE) { if (STATIC_MODE) {
console.log('You are starting webpack in compile-once mode'); console.log('You are starting webpack in compile-once mode');
...@@ -59,10 +59,10 @@ nodemon ...@@ -59,10 +59,10 @@ nodemon
console.log('If you change them often, you might want to unset DEV_SERVER_STATIC'); console.log('If you change them often, you might want to unset DEV_SERVER_STATIC');
} }
}) })
.on('quit', function () { .on('quit', () => {
console.log('Shutting down webpack process'); console.log('Shutting down webpack process');
process.exit(); process.exit();
}) })
.on('restart', function (files) { .on('restart', (files) => {
console.log('Restarting webpack process due to: ', files); console.log('Restarting webpack process due to: ', files);
}); });
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment