refactor (eslint): use cordova-eslint (#910)

This commit is contained in:
エリス
2020-01-31 22:02:48 +09:00
committed by GitHub
parent 8e98de6e7c
commit de105e8651
30 changed files with 196 additions and 212 deletions
+5 -5
View File
@@ -23,12 +23,12 @@ var ConfigParser = require('cordova-common').ConfigParser;
var Api = require('./templates/cordova/Api');
var argv = require('nopt')({
'help': Boolean,
'cli': Boolean,
'shared': Boolean,
'link': Boolean,
help: Boolean,
cli: Boolean,
shared: Boolean,
link: Boolean,
'activity-name': [String, undefined]
}, { 'd': '--verbose' });
}, { d: '--verbose' });
if (argv.help || argv.argv.remain.length === 0) {
console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'create')) + ' <path_to_new_project> <package_name> <project_name> [<template_path>] [--activity-name <activity_name>] [--link]');
+4 -6
View File
@@ -140,7 +140,7 @@ function copyScripts (projectPath) {
// Copy in the new ones.
fs.copySync(srcScriptsDir, destScriptsDir);
let nodeModulesDir = path.join(ROOT, 'node_modules');
const nodeModulesDir = path.join(ROOT, 'node_modules');
if (fs.existsSync(nodeModulesDir)) fs.copySync(nodeModulesDir, path.join(destScriptsDir, 'node_modules'));
fs.copySync(path.join(bin, 'check_reqs'), path.join(destScriptsDir, 'check_reqs'));
@@ -156,7 +156,7 @@ function copyScripts (projectPath) {
// `require` path for the two libraries. if there's a better way to share
// modules across both the repo and generated projects, we should make sure
// to remove/update this.
let templatesCordovaRegex = /templates\/cordova\//;
const templatesCordovaRegex = /templates\/cordova\//;
utils.replaceFileContents(android_sdk_version, templatesCordovaRegex, '');
utils.replaceFileContents(check_reqs, templatesCordovaRegex, '');
}
@@ -218,7 +218,6 @@ function validateProjectName (project_name) {
* @return {Promise<String>} Directory where application has been created
*/
exports.create = function (project_path, config, options, events) {
options = options || {};
// Set default values for path, package and name
@@ -229,8 +228,8 @@ exports.create = function (project_path, config, options, events) {
}
var package_name = config.android_packageName() || config.packageName() || 'my.cordova.project';
var project_name = config.name() ?
config.name().replace(/[^\w.]/g, '_') : 'CordovaExample';
var project_name = config.name()
? config.name().replace(/[^\w.]/g, '_') : 'CordovaExample';
var safe_activity_name = config.android_activityName() || options.activityName || 'MainActivity';
var target_api = check_reqs.get_target();
@@ -312,7 +311,6 @@ function generateDoneMessage (type, link) {
// Returns a promise.
exports.update = function (projectPath, options, events) {
var errorString =
'An in-place platform update is not supported. \n' +
'The `platforms` folder is always treated as a build artifact in the CLI workflow.\n' +
+7 -7
View File
@@ -31,13 +31,13 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(args[2]) >= 0) {
// Do some basic argument parsing
var buildOpts = nopt({
'verbose': Boolean,
'silent': Boolean,
'debug': Boolean,
'release': Boolean,
'nobuild': Boolean,
'buildConfig': path
}, { 'd': '--verbose' });
verbose: Boolean,
silent: Boolean,
debug: Boolean,
release: Boolean,
nobuild: Boolean,
buildConfig: path
}, { d: '--verbose' });
// Make buildOptions compatible with PlatformApi build method spec
buildOpts.argv = buildOpts.argv.original;
+3 -3
View File
@@ -32,9 +32,9 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=
// Do some basic argument parsing
var opts = nopt({
'verbose': Boolean,
'silent': Boolean
}, { 'd': '--verbose' });
verbose: Boolean,
silent: Boolean
}, { d: '--verbose' });
// Make buildOptions compatible with PlatformApi clean method spec
opts.argv = opts.argv.original;
+3
View File
@@ -49,6 +49,8 @@ module.exports.print_newest_available_sdk_target = function () {
});
};
// Versions should not be represented as float, so we disable quote-props here
/* eslint-disable quote-props */
module.exports.version_string_to_api_level = {
'4.0': 14,
'4.0.3': 15,
@@ -64,6 +66,7 @@ module.exports.version_string_to_api_level = {
'7.1.1': 25,
'8.0': 26
};
/* eslint-enable quote-props */
function parse_targets (output) {
var target_out = output.split('\n');
+1 -1
View File
@@ -113,7 +113,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {
let shouldWarn = false;
const signingKeys = ['keystore', 'alias', 'storePassword', 'password', 'keystoreType'];
for (let key in packageArgs) {
for (const key in packageArgs) {
if (!shouldWarn && signingKeys.indexOf(key) > -1) {
// If we enter this condition, we have a key used for signing a build,
// but we are missing some required signing properties
+1 -1
View File
@@ -82,7 +82,7 @@ function findOutputFilesHelper (dir, build_type, arch, extension) {
if (files.length === 0) return files;
// Assume arch-specific build if newest apk has -x86 or -arm.
let archSpecific = !!/-x86|-arm/.exec(path.basename(files[0]));
const archSpecific = !!/-x86|-arm/.exec(path.basename(files[0]));
// And show only arch-specific ones (or non-arch-specific)
files = files.filter(p => !!/-x86|-arm/.exec(path.basename(p)) === archSpecific);
+4 -6
View File
@@ -31,7 +31,7 @@ var android_sdk = require('./android_sdk');
const { createEditor } = require('properties-parser');
function forgivingWhichSync (cmd) {
let whichResult = which.sync(cmd, { nothrow: true });
const whichResult = which.sync(cmd, { nothrow: true });
// On null, returns empty string to maintain backwards compatibility
// realpathSync follows symlinks
@@ -39,11 +39,11 @@ function forgivingWhichSync (cmd) {
}
function getJDKDirectory (directory) {
let p = path.resolve(directory, 'java');
const p = path.resolve(directory, 'java');
if (fs.existsSync(p)) {
let directories = fs.readdirSync(p);
const directories = fs.readdirSync(p);
for (let i = 0; i < directories.length; i++) {
let dir = directories[i];
const dir = directories[i];
if (/^(jdk)+./.test(dir)) {
return path.resolve(directory, 'java', dir);
}
@@ -119,7 +119,6 @@ module.exports.get_gradle_wrapper = function () {
var program_dir;
// OK, This hack only works on Windows, not on Mac OS or Linux. We will be deleting this eventually!
if (module.exports.isWindows()) {
var result = execa.sync(path.join(__dirname, 'getASPath.bat'));
// console.log('result.stdout =' + result.stdout.toString());
// console.log('result.stderr =' + result.stderr.toString());
@@ -431,7 +430,6 @@ var Requirement = function (id, name, version, installed) {
* @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.
*/
module.exports.check_all = function () {
var requirements = [
new Requirement('java', 'Java JDK'),
new Requirement('androidSdk', 'Android SDK'),
+5 -5
View File
@@ -17,10 +17,10 @@
under the License.
*/
let fs = require('fs');
let path = require('path');
let propertiesParser = require('properties-parser');
let events = require('cordova-common').events;
const fs = require('fs');
const path = require('path');
const propertiesParser = require('properties-parser');
const events = require('cordova-common').events;
class GradlePropertiesParser {
/**
@@ -82,7 +82,7 @@ class GradlePropertiesParser {
_configureProperties (properties) {
// Iterate though the properties and set only if missing.
Object.keys(properties).forEach(key => {
let value = this.gradleFile.get(key);
const value = this.gradleFile.get(key);
if (!value) {
// Handles the case of adding missing defaults or new properties that are missing.
+1 -6
View File
@@ -43,7 +43,7 @@ const CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds
const EXEC_KILL_SIGNAL = 'SIGKILL';
function forgivingWhichSync (cmd) {
let whichResult = which.sync(cmd, { nothrow: true });
const whichResult = which.sync(cmd, { nothrow: true });
// On null, returns empty string to maintain backwards compatibility
// realpathSync follows symlinks
@@ -104,7 +104,6 @@ module.exports.list_images_using_avdmanager = function () {
if (response[i].match(/Name:\s/)) {
emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
} */
}
return emulator_list;
});
@@ -147,7 +146,6 @@ module.exports.list_images_using_android = function () {
if (response[i].match(/Name:\s/)) {
emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
} */
}
return emulator_list;
});
@@ -429,7 +427,6 @@ module.exports.resolveTarget = function (target) {
* Returns a promise.
*/
module.exports.install = function (givenTarget, buildResults) {
var target;
// We need to find the proper path to the Android Manifest
const manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml');
@@ -453,7 +450,6 @@ module.exports.install = function (givenTarget, buildResults) {
// This promise is always resolved, even if 'adb uninstall' fails to uninstall app
// or the app doesn't installed at all, so no error catching needed.
return Promise.resolve().then(function () {
var apk_path = build.findBestApkForArchitecture(buildResults, target.arch);
var execOptions = {
cwd: os.tmpdir(),
@@ -512,7 +508,6 @@ module.exports.install = function (givenTarget, buildResults) {
});
// unlock screen
}).then(function () {
events.emit('verbose', 'Unlocking screen...');
return Adb.shell(target.target, 'input keyevent 82');
}).then(function () {
+1 -1
View File
@@ -65,7 +65,7 @@ var handlers = {
removeFile(path.resolve(project.projectDir, dest));
}
},
'framework': {
framework: {
install: function (obj, plugin, project, options) {
var src = obj.src;
if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));
+35 -35
View File
@@ -29,7 +29,7 @@ var FileUpdater = require('cordova-common').FileUpdater;
var PlatformJson = require('cordova-common').PlatformJson;
var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;
var PluginInfoProvider = require('cordova-common').PluginInfoProvider;
let utils = require('./utils');
const utils = require('./utils');
const GradlePropertiesParser = require('./config/GradlePropertiesParser');
@@ -49,7 +49,7 @@ module.exports.prepare = function (cordovaProject, options) {
const isGradlePluginKotlinEnabled = this._config.getPreference('GradlePluginKotlinEnabled', 'android');
const gradlePluginKotlinCodeStyle = this._config.getPreference('GradlePluginKotlinCodeStyle', 'android');
let gradlePropertiesUserConfig = {};
const gradlePropertiesUserConfig = {};
if (minSdkVersion) gradlePropertiesUserConfig.cdvMinSdkVersion = minSdkVersion;
if (maxSdkVersion) gradlePropertiesUserConfig.cdvMaxSdkVersion = maxSdkVersion;
if (targetSdkVersion) gradlePropertiesUserConfig.cdvTargetSdkVersion = targetSdkVersion;
@@ -63,7 +63,7 @@ module.exports.prepare = function (cordovaProject, options) {
gradlePropertiesUserConfig['android.enableJetifier'] = androidXEnabled;
}
let gradlePropertiesParser = new GradlePropertiesParser(this.locations.root);
const gradlePropertiesParser = new GradlePropertiesParser(this.locations.root);
gradlePropertiesParser.configure(gradlePropertiesUserConfig);
// Update own www dir with project's www assets and plugins' assets and js-files
@@ -222,9 +222,9 @@ function updateProjectAccordingTo (platformConfig, locations) {
.write();
// Java file paths shouldn't be hard coded
let javaDirectory = path.join(locations.javaSrc, manifestId.replace(/\./g, '/'));
let javaPattern = /\.java$/;
let java_files = utils.scanDirectory(javaDirectory, javaPattern, true).filter(function (f) {
const javaDirectory = path.join(locations.javaSrc, manifestId.replace(/\./g, '/'));
const javaPattern = /\.java$/;
const java_files = utils.scanDirectory(javaDirectory, javaPattern, true).filter(function (f) {
return utils.grep(f, /extends\s+CordovaActivity/g) !== null;
});
@@ -234,7 +234,7 @@ function updateProjectAccordingTo (platformConfig, locations) {
events.emit('log', 'Multiple candidate Java files that extend CordovaActivity found. Guessing at the first one, ' + java_files[0]);
}
let destFile = java_files[0];
const destFile = java_files[0];
// var destFile = path.join(locations.root, 'app', 'src', 'main', 'java', androidPkgName.replace(/\./g, '/'), path.basename(java_files[0]));
// fs.ensureDirSync(path.dirname(destFile));
@@ -245,9 +245,9 @@ function updateProjectAccordingTo (platformConfig, locations) {
utils.replaceFileContents(destFile, /package [\w.]*;/, 'package ' + androidPkgName + ';');
events.emit('verbose', 'Wrote out Android package name "' + androidPkgName + '" to ' + destFile);
var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin() ?
manifestId.toUpperCase() !== androidPkgName.toUpperCase() :
manifestId !== androidPkgName;
var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin()
? manifestId.toUpperCase() !== androidPkgName.toUpperCase()
: manifestId !== androidPkgName;
if (removeOrigPkg) {
// If package was name changed we need to remove old java with main activity
@@ -351,7 +351,7 @@ function cleanSplashes (projectRoot, projectConfig, platformResourcesDir) {
}
function updateIcons (cordovaProject, platformResourcesDir) {
let icons = cordovaProject.projectConfig.getIcons('android');
const icons = cordovaProject.projectConfig.getIcons('android');
// Skip if there are no app defined icons in config.xml
if (icons.length === 0) {
@@ -361,14 +361,14 @@ function updateIcons (cordovaProject, platformResourcesDir) {
// 1. loop icons determin if there is an error in the setup.
// 2. during initial loop, also setup for legacy support.
let errorMissingAttributes = [];
let errorLegacyIconNeeded = [];
const errorMissingAttributes = [];
const errorLegacyIconNeeded = [];
let hasAdaptive = false;
icons.forEach((icon, key) => {
if (
(icon.background && !icon.foreground)
|| (!icon.background && icon.foreground)
|| (!icon.background && !icon.foreground && !icon.src)
(icon.background && !icon.foreground) ||
(!icon.background && icon.foreground) ||
(!icon.background && !icon.foreground && !icon.src)
) {
errorMissingAttributes.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));
}
@@ -377,10 +377,10 @@ function updateIcons (cordovaProject, platformResourcesDir) {
hasAdaptive = true;
if (
!icon.src
&& (
icon.foreground.startsWith('@color')
|| path.extname(path.basename(icon.foreground)) === '.xml'
!icon.src &&
(
icon.foreground.startsWith('@color') ||
path.extname(path.basename(icon.foreground)) === '.xml'
)
) {
errorLegacyIconNeeded.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));
@@ -390,7 +390,7 @@ function updateIcons (cordovaProject, platformResourcesDir) {
}
});
let errorMessage = [];
const errorMessage = [];
if (errorMissingAttributes.length > 0) {
errorMessage.push('One of the following attributes are set but missing the other for the density type: ' + errorMissingAttributes.join(', ') + '. Please ensure that all require attributes are defined.');
}
@@ -413,7 +413,7 @@ function updateIcons (cordovaProject, platformResourcesDir) {
mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher.xml')
);
let preparedIcons = prepareIcons(icons);
const preparedIcons = prepareIcons(icons);
if (hasAdaptive) {
resourceMap = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir);
@@ -426,8 +426,8 @@ function updateIcons (cordovaProject, platformResourcesDir) {
}
function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformResourcesDir) {
let android_icons = preparedIcons.android_icons;
let default_icon = preparedIcons.default_icon;
const android_icons = preparedIcons.android_icons;
const default_icon = preparedIcons.default_icon;
// The source paths for icons and splashes are relative to
// project's config.xml location, so we use it as base path.
@@ -436,7 +436,7 @@ function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformReso
let targetPathBackground;
let targetPathForeground;
for (let density in android_icons) {
for (const density in android_icons) {
let backgroundVal = '@mipmap/ic_launcher_background';
let foregroundVal = '@mipmap/ic_launcher_foreground';
@@ -476,7 +476,7 @@ function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformReso
<foreground android:drawable="` + foregroundVal + `" />
</adaptive-icon>`;
let launcherXmlPath = path.join(platformResourcesDir, 'mipmap-' + density + '-v26', 'ic_launcher.xml');
const launcherXmlPath = path.join(platformResourcesDir, 'mipmap-' + density + '-v26', 'ic_launcher.xml');
// Remove the XML from the resourceMap so the file does not get removed.
delete resourceMap[launcherXmlPath];
@@ -520,8 +520,8 @@ function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformReso
}
function updateIconResourceForLegacy (preparedIcons, resourceMap, platformResourcesDir) {
let android_icons = preparedIcons.android_icons;
let default_icon = preparedIcons.default_icon;
const android_icons = preparedIcons.android_icons;
const default_icon = preparedIcons.default_icon;
// The source paths for icons and splashes are relative to
// project's config.xml location, so we use it as base path.
@@ -550,7 +550,7 @@ function prepareIcons (icons) {
192: 'xxxhdpi'
};
let android_icons = {};
const android_icons = {};
let default_icon;
// find the best matching icon for a given density or size
@@ -580,8 +580,8 @@ function prepareIcons (icons) {
if (!size && !icon.density) {
if (default_icon) {
let found = {};
let favor = {};
const found = {};
const favor = {};
// populating found icon.
if (icon.background && icon.foreground) {
@@ -624,7 +624,7 @@ function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {
return;
}
let resourceMap = Object.assign(
const resourceMap = Object.assign(
{},
mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.png'),
mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.png'),
@@ -644,10 +644,10 @@ function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {
* Gets a map containing resources of a specified name from all drawable folders in a directory.
*/
function mapImageResources (rootDir, subDir, type, resourceName) {
let pathMap = {};
let pattern = new RegExp(type + '+-.+');
const pathMap = {};
const pattern = new RegExp(type + '+-.+');
utils.scanDirectory(path.join(rootDir, subDir), pattern).forEach(function (drawableFolder) {
let imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);
const imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);
pathMap[imagePath] = null;
});
return pathMap;
-1
View File
@@ -34,7 +34,6 @@ var events = require('cordova-common').events;
* @returns {Promise}
*/
module.exports.retryPromise = function (attemptsLeft, promiseFunction) {
// NOTE:
// get all trailing arguments, by skipping the first two (attemptsLeft and
// promiseFunction) because they shouldn't get passed to promiseFunction
+6 -6
View File
@@ -49,9 +49,9 @@ exports.replaceFileContents = function (file, searchRegex, replacementString) {
* @returns string|null
*/
exports.grep = function (file, regex) {
let contents = fs.readFileSync(file).toString().replace(/\\r/g, '').split('\n');
const contents = fs.readFileSync(file).toString().replace(/\\r/g, '').split('\n');
for (let i = 0; i < contents.length; i++) {
let line = contents[i];
const line = contents[i];
if (regex.test(line)) {
return line;
}
@@ -71,12 +71,12 @@ exports.scanDirectory = function (directory, regex, recursive) {
let output = [];
if (fs.existsSync(directory)) {
let items = fs.readdirSync(directory);
const items = fs.readdirSync(directory);
for (let i = 0; i < items.length; i++) {
let item = items[i];
let itemPath = path.join(directory, item);
let stats = fs.statSync(itemPath);
const item = items[i];
const itemPath = path.join(directory, item);
const stats = fs.statSync(itemPath);
if (regex.test(itemPath)) {
output.push(itemPath);
+11 -11
View File
@@ -30,17 +30,17 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=
// Do some basic argument parsing
var runOpts = nopt({
'verbose': Boolean,
'silent': Boolean,
'debug': Boolean,
'release': Boolean,
'nobuild': Boolean,
'buildConfig': path,
'archs': String,
'device': Boolean,
'emulator': Boolean,
'target': String
}, { 'd': '--verbose' });
verbose: Boolean,
silent: Boolean,
debug: Boolean,
release: Boolean,
nobuild: Boolean,
buildConfig: path,
archs: String,
device: Boolean,
emulator: Boolean,
target: String
}, { d: '--verbose' });
// Make runOptions compatible with PlatformApi run method spec
runOpts.argv = runOpts.argv.remain;
+4 -4
View File
@@ -21,10 +21,10 @@
var path = require('path');
var Api = require('./templates/cordova/Api');
var args = require('nopt')({
'link': Boolean,
'shared': Boolean,
'help': Boolean
}, { 'd': '--verbose' });
link: Boolean,
shared: Boolean,
help: Boolean
}, { d: '--verbose' });
if (args.help || args.argv.remain.length === 0) {
console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'update')) + ' <path_to_project> [--link]');