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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 196 additions and 212 deletions

View File

@ -1,10 +1,27 @@
root: true # Licensed to the Apache Software Foundation (ASF) under one
extends: semistandard # or more contributor license agreements. See the NOTICE file
rules: # distributed with this work for additional information
indent: # regarding copyright ownership. The ASF licenses this file
- error # to you under the Apache License, Version 2.0 (the
- 4 # "License"); you may not use this file except in compliance
camelcase: off # with the License. You may obtain a copy of the License at
padded-blocks: off #
operator-linebreak: off # http://www.apache.org/licenses/LICENSE-2.0
no-throw-literal: off #
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
extends: '@cordova/eslint-config/node'
overrides:
- files: [spec/**/*.js]
extends: '@cordova/eslint-config/node-tests'
rules:
prefer-promise-reject-errors: off
- files: [cordova-js-src/**/*.js]
extends: '@cordova/eslint-config/browser'

View File

@ -23,12 +23,12 @@ var ConfigParser = require('cordova-common').ConfigParser;
var Api = require('./templates/cordova/Api'); var Api = require('./templates/cordova/Api');
var argv = require('nopt')({ var argv = require('nopt')({
'help': Boolean, help: Boolean,
'cli': Boolean, cli: Boolean,
'shared': Boolean, shared: Boolean,
'link': Boolean, link: Boolean,
'activity-name': [String, undefined] 'activity-name': [String, undefined]
}, { 'd': '--verbose' }); }, { d: '--verbose' });
if (argv.help || argv.argv.remain.length === 0) { 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]'); 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]');

View File

@ -140,7 +140,7 @@ function copyScripts (projectPath) {
// Copy in the new ones. // Copy in the new ones.
fs.copySync(srcScriptsDir, destScriptsDir); 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')); if (fs.existsSync(nodeModulesDir)) fs.copySync(nodeModulesDir, path.join(destScriptsDir, 'node_modules'));
fs.copySync(path.join(bin, 'check_reqs'), path.join(destScriptsDir, 'check_reqs')); 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 // `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 // modules across both the repo and generated projects, we should make sure
// to remove/update this. // to remove/update this.
let templatesCordovaRegex = /templates\/cordova\//; const templatesCordovaRegex = /templates\/cordova\//;
utils.replaceFileContents(android_sdk_version, templatesCordovaRegex, ''); utils.replaceFileContents(android_sdk_version, templatesCordovaRegex, '');
utils.replaceFileContents(check_reqs, templatesCordovaRegex, ''); utils.replaceFileContents(check_reqs, templatesCordovaRegex, '');
} }
@ -218,7 +218,6 @@ function validateProjectName (project_name) {
* @return {Promise<String>} Directory where application has been created * @return {Promise<String>} Directory where application has been created
*/ */
exports.create = function (project_path, config, options, events) { exports.create = function (project_path, config, options, events) {
options = options || {}; options = options || {};
// Set default values for path, package and name // 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 package_name = config.android_packageName() || config.packageName() || 'my.cordova.project';
var project_name = config.name() ? var project_name = config.name()
config.name().replace(/[^\w.]/g, '_') : 'CordovaExample'; ? config.name().replace(/[^\w.]/g, '_') : 'CordovaExample';
var safe_activity_name = config.android_activityName() || options.activityName || 'MainActivity'; var safe_activity_name = config.android_activityName() || options.activityName || 'MainActivity';
var target_api = check_reqs.get_target(); var target_api = check_reqs.get_target();
@ -312,7 +311,6 @@ function generateDoneMessage (type, link) {
// Returns a promise. // Returns a promise.
exports.update = function (projectPath, options, events) { exports.update = function (projectPath, options, events) {
var errorString = var errorString =
'An in-place platform update is not supported. \n' + 'An in-place platform update is not supported. \n' +
'The `platforms` folder is always treated as a build artifact in the CLI workflow.\n' + 'The `platforms` folder is always treated as a build artifact in the CLI workflow.\n' +

View File

@ -31,13 +31,13 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(args[2]) >= 0) {
// Do some basic argument parsing // Do some basic argument parsing
var buildOpts = nopt({ var buildOpts = nopt({
'verbose': Boolean, verbose: Boolean,
'silent': Boolean, silent: Boolean,
'debug': Boolean, debug: Boolean,
'release': Boolean, release: Boolean,
'nobuild': Boolean, nobuild: Boolean,
'buildConfig': path buildConfig: path
}, { 'd': '--verbose' }); }, { d: '--verbose' });
// Make buildOptions compatible with PlatformApi build method spec // Make buildOptions compatible with PlatformApi build method spec
buildOpts.argv = buildOpts.argv.original; buildOpts.argv = buildOpts.argv.original;

View File

@ -32,9 +32,9 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=
// Do some basic argument parsing // Do some basic argument parsing
var opts = nopt({ var opts = nopt({
'verbose': Boolean, verbose: Boolean,
'silent': Boolean silent: Boolean
}, { 'd': '--verbose' }); }, { d: '--verbose' });
// Make buildOptions compatible with PlatformApi clean method spec // Make buildOptions compatible with PlatformApi clean method spec
opts.argv = opts.argv.original; opts.argv = opts.argv.original;

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 = { module.exports.version_string_to_api_level = {
'4.0': 14, '4.0': 14,
'4.0.3': 15, '4.0.3': 15,
@ -64,6 +66,7 @@ module.exports.version_string_to_api_level = {
'7.1.1': 25, '7.1.1': 25,
'8.0': 26 '8.0': 26
}; };
/* eslint-enable quote-props */
function parse_targets (output) { function parse_targets (output) {
var target_out = output.split('\n'); var target_out = output.split('\n');

View File

@ -113,7 +113,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {
let shouldWarn = false; let shouldWarn = false;
const signingKeys = ['keystore', 'alias', 'storePassword', 'password', 'keystoreType']; const signingKeys = ['keystore', 'alias', 'storePassword', 'password', 'keystoreType'];
for (let key in packageArgs) { for (const key in packageArgs) {
if (!shouldWarn && signingKeys.indexOf(key) > -1) { if (!shouldWarn && signingKeys.indexOf(key) > -1) {
// If we enter this condition, we have a key used for signing a build, // If we enter this condition, we have a key used for signing a build,
// but we are missing some required signing properties // but we are missing some required signing properties

View File

@ -82,7 +82,7 @@ function findOutputFilesHelper (dir, build_type, arch, extension) {
if (files.length === 0) return files; if (files.length === 0) return files;
// Assume arch-specific build if newest apk has -x86 or -arm. // 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) // And show only arch-specific ones (or non-arch-specific)
files = files.filter(p => !!/-x86|-arm/.exec(path.basename(p)) === archSpecific); files = files.filter(p => !!/-x86|-arm/.exec(path.basename(p)) === archSpecific);

View File

@ -31,7 +31,7 @@ var android_sdk = require('./android_sdk');
const { createEditor } = require('properties-parser'); const { createEditor } = require('properties-parser');
function forgivingWhichSync (cmd) { 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 // On null, returns empty string to maintain backwards compatibility
// realpathSync follows symlinks // realpathSync follows symlinks
@ -39,11 +39,11 @@ function forgivingWhichSync (cmd) {
} }
function getJDKDirectory (directory) { function getJDKDirectory (directory) {
let p = path.resolve(directory, 'java'); const p = path.resolve(directory, 'java');
if (fs.existsSync(p)) { if (fs.existsSync(p)) {
let directories = fs.readdirSync(p); const directories = fs.readdirSync(p);
for (let i = 0; i < directories.length; i++) { for (let i = 0; i < directories.length; i++) {
let dir = directories[i]; const dir = directories[i];
if (/^(jdk)+./.test(dir)) { if (/^(jdk)+./.test(dir)) {
return path.resolve(directory, 'java', dir); return path.resolve(directory, 'java', dir);
} }
@ -119,7 +119,6 @@ module.exports.get_gradle_wrapper = function () {
var program_dir; var program_dir;
// OK, This hack only works on Windows, not on Mac OS or Linux. We will be deleting this eventually! // OK, This hack only works on Windows, not on Mac OS or Linux. We will be deleting this eventually!
if (module.exports.isWindows()) { if (module.exports.isWindows()) {
var result = execa.sync(path.join(__dirname, 'getASPath.bat')); var result = execa.sync(path.join(__dirname, 'getASPath.bat'));
// console.log('result.stdout =' + result.stdout.toString()); // console.log('result.stdout =' + result.stdout.toString());
// console.log('result.stderr =' + result.stderr.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. * @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.
*/ */
module.exports.check_all = function () { module.exports.check_all = function () {
var requirements = [ var requirements = [
new Requirement('java', 'Java JDK'), new Requirement('java', 'Java JDK'),
new Requirement('androidSdk', 'Android SDK'), new Requirement('androidSdk', 'Android SDK'),

View File

@ -17,10 +17,10 @@
under the License. under the License.
*/ */
let fs = require('fs'); const fs = require('fs');
let path = require('path'); const path = require('path');
let propertiesParser = require('properties-parser'); const propertiesParser = require('properties-parser');
let events = require('cordova-common').events; const events = require('cordova-common').events;
class GradlePropertiesParser { class GradlePropertiesParser {
/** /**
@ -82,7 +82,7 @@ class GradlePropertiesParser {
_configureProperties (properties) { _configureProperties (properties) {
// Iterate though the properties and set only if missing. // Iterate though the properties and set only if missing.
Object.keys(properties).forEach(key => { Object.keys(properties).forEach(key => {
let value = this.gradleFile.get(key); const value = this.gradleFile.get(key);
if (!value) { if (!value) {
// Handles the case of adding missing defaults or new properties that are missing. // Handles the case of adding missing defaults or new properties that are missing.

View File

@ -43,7 +43,7 @@ const CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds
const EXEC_KILL_SIGNAL = 'SIGKILL'; const EXEC_KILL_SIGNAL = 'SIGKILL';
function forgivingWhichSync (cmd) { 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 // On null, returns empty string to maintain backwards compatibility
// realpathSync follows symlinks // realpathSync follows symlinks
@ -104,7 +104,6 @@ module.exports.list_images_using_avdmanager = function () {
if (response[i].match(/Name:\s/)) { if (response[i].match(/Name:\s/)) {
emulator_list.push(response[i].split('Name: ')[1].replace('\r', ''); emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
} */ } */
} }
return emulator_list; return emulator_list;
}); });
@ -147,7 +146,6 @@ module.exports.list_images_using_android = function () {
if (response[i].match(/Name:\s/)) { if (response[i].match(/Name:\s/)) {
emulator_list.push(response[i].split('Name: ')[1].replace('\r', ''); emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');
} */ } */
} }
return emulator_list; return emulator_list;
}); });
@ -429,7 +427,6 @@ module.exports.resolveTarget = function (target) {
* Returns a promise. * Returns a promise.
*/ */
module.exports.install = function (givenTarget, buildResults) { module.exports.install = function (givenTarget, buildResults) {
var target; var target;
// We need to find the proper path to the Android Manifest // We need to find the proper path to the Android Manifest
const manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml'); 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 // 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. // or the app doesn't installed at all, so no error catching needed.
return Promise.resolve().then(function () { return Promise.resolve().then(function () {
var apk_path = build.findBestApkForArchitecture(buildResults, target.arch); var apk_path = build.findBestApkForArchitecture(buildResults, target.arch);
var execOptions = { var execOptions = {
cwd: os.tmpdir(), cwd: os.tmpdir(),
@ -512,7 +508,6 @@ module.exports.install = function (givenTarget, buildResults) {
}); });
// unlock screen // unlock screen
}).then(function () { }).then(function () {
events.emit('verbose', 'Unlocking screen...'); events.emit('verbose', 'Unlocking screen...');
return Adb.shell(target.target, 'input keyevent 82'); return Adb.shell(target.target, 'input keyevent 82');
}).then(function () { }).then(function () {

View File

@ -65,7 +65,7 @@ var handlers = {
removeFile(path.resolve(project.projectDir, dest)); removeFile(path.resolve(project.projectDir, dest));
} }
}, },
'framework': { framework: {
install: function (obj, plugin, project, options) { install: function (obj, plugin, project, options) {
var src = obj.src; var src = obj.src;
if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id)); if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));

View File

@ -29,7 +29,7 @@ var FileUpdater = require('cordova-common').FileUpdater;
var PlatformJson = require('cordova-common').PlatformJson; var PlatformJson = require('cordova-common').PlatformJson;
var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger; var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;
var PluginInfoProvider = require('cordova-common').PluginInfoProvider; var PluginInfoProvider = require('cordova-common').PluginInfoProvider;
let utils = require('./utils'); const utils = require('./utils');
const GradlePropertiesParser = require('./config/GradlePropertiesParser'); const GradlePropertiesParser = require('./config/GradlePropertiesParser');
@ -49,7 +49,7 @@ module.exports.prepare = function (cordovaProject, options) {
const isGradlePluginKotlinEnabled = this._config.getPreference('GradlePluginKotlinEnabled', 'android'); const isGradlePluginKotlinEnabled = this._config.getPreference('GradlePluginKotlinEnabled', 'android');
const gradlePluginKotlinCodeStyle = this._config.getPreference('GradlePluginKotlinCodeStyle', 'android'); const gradlePluginKotlinCodeStyle = this._config.getPreference('GradlePluginKotlinCodeStyle', 'android');
let gradlePropertiesUserConfig = {}; const gradlePropertiesUserConfig = {};
if (minSdkVersion) gradlePropertiesUserConfig.cdvMinSdkVersion = minSdkVersion; if (minSdkVersion) gradlePropertiesUserConfig.cdvMinSdkVersion = minSdkVersion;
if (maxSdkVersion) gradlePropertiesUserConfig.cdvMaxSdkVersion = maxSdkVersion; if (maxSdkVersion) gradlePropertiesUserConfig.cdvMaxSdkVersion = maxSdkVersion;
if (targetSdkVersion) gradlePropertiesUserConfig.cdvTargetSdkVersion = targetSdkVersion; if (targetSdkVersion) gradlePropertiesUserConfig.cdvTargetSdkVersion = targetSdkVersion;
@ -63,7 +63,7 @@ module.exports.prepare = function (cordovaProject, options) {
gradlePropertiesUserConfig['android.enableJetifier'] = androidXEnabled; gradlePropertiesUserConfig['android.enableJetifier'] = androidXEnabled;
} }
let gradlePropertiesParser = new GradlePropertiesParser(this.locations.root); const gradlePropertiesParser = new GradlePropertiesParser(this.locations.root);
gradlePropertiesParser.configure(gradlePropertiesUserConfig); gradlePropertiesParser.configure(gradlePropertiesUserConfig);
// Update own www dir with project's www assets and plugins' assets and js-files // Update own www dir with project's www assets and plugins' assets and js-files
@ -222,9 +222,9 @@ function updateProjectAccordingTo (platformConfig, locations) {
.write(); .write();
// Java file paths shouldn't be hard coded // Java file paths shouldn't be hard coded
let javaDirectory = path.join(locations.javaSrc, manifestId.replace(/\./g, '/')); const javaDirectory = path.join(locations.javaSrc, manifestId.replace(/\./g, '/'));
let javaPattern = /\.java$/; const javaPattern = /\.java$/;
let java_files = utils.scanDirectory(javaDirectory, javaPattern, true).filter(function (f) { const java_files = utils.scanDirectory(javaDirectory, javaPattern, true).filter(function (f) {
return utils.grep(f, /extends\s+CordovaActivity/g) !== null; 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]); 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])); // var destFile = path.join(locations.root, 'app', 'src', 'main', 'java', androidPkgName.replace(/\./g, '/'), path.basename(java_files[0]));
// fs.ensureDirSync(path.dirname(destFile)); // fs.ensureDirSync(path.dirname(destFile));
@ -245,9 +245,9 @@ function updateProjectAccordingTo (platformConfig, locations) {
utils.replaceFileContents(destFile, /package [\w.]*;/, 'package ' + androidPkgName + ';'); utils.replaceFileContents(destFile, /package [\w.]*;/, 'package ' + androidPkgName + ';');
events.emit('verbose', 'Wrote out Android package name "' + androidPkgName + '" to ' + destFile); events.emit('verbose', 'Wrote out Android package name "' + androidPkgName + '" to ' + destFile);
var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin() ? var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin()
manifestId.toUpperCase() !== androidPkgName.toUpperCase() : ? manifestId.toUpperCase() !== androidPkgName.toUpperCase()
manifestId !== androidPkgName; : manifestId !== androidPkgName;
if (removeOrigPkg) { if (removeOrigPkg) {
// If package was name changed we need to remove old java with main activity // 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) { 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 // Skip if there are no app defined icons in config.xml
if (icons.length === 0) { if (icons.length === 0) {
@ -361,14 +361,14 @@ function updateIcons (cordovaProject, platformResourcesDir) {
// 1. loop icons determin if there is an error in the setup. // 1. loop icons determin if there is an error in the setup.
// 2. during initial loop, also setup for legacy support. // 2. during initial loop, also setup for legacy support.
let errorMissingAttributes = []; const errorMissingAttributes = [];
let errorLegacyIconNeeded = []; const errorLegacyIconNeeded = [];
let hasAdaptive = false; let hasAdaptive = false;
icons.forEach((icon, key) => { icons.forEach((icon, key) => {
if ( if (
(icon.background && !icon.foreground) (icon.background && !icon.foreground) ||
|| (!icon.background && icon.foreground) (!icon.background && icon.foreground) ||
|| (!icon.background && !icon.foreground && !icon.src) (!icon.background && !icon.foreground && !icon.src)
) { ) {
errorMissingAttributes.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width)); errorMissingAttributes.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));
} }
@ -377,10 +377,10 @@ function updateIcons (cordovaProject, platformResourcesDir) {
hasAdaptive = true; hasAdaptive = true;
if ( if (
!icon.src !icon.src &&
&& ( (
icon.foreground.startsWith('@color') icon.foreground.startsWith('@color') ||
|| path.extname(path.basename(icon.foreground)) === '.xml' path.extname(path.basename(icon.foreground)) === '.xml'
) )
) { ) {
errorLegacyIconNeeded.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width)); 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) { 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.'); 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') mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher.xml')
); );
let preparedIcons = prepareIcons(icons); const preparedIcons = prepareIcons(icons);
if (hasAdaptive) { if (hasAdaptive) {
resourceMap = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir); resourceMap = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir);
@ -426,8 +426,8 @@ function updateIcons (cordovaProject, platformResourcesDir) {
} }
function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformResourcesDir) { function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformResourcesDir) {
let android_icons = preparedIcons.android_icons; const android_icons = preparedIcons.android_icons;
let default_icon = preparedIcons.default_icon; const default_icon = preparedIcons.default_icon;
// The source paths for icons and splashes are relative to // The source paths for icons and splashes are relative to
// project's config.xml location, so we use it as base path. // project's config.xml location, so we use it as base path.
@ -436,7 +436,7 @@ function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformReso
let targetPathBackground; let targetPathBackground;
let targetPathForeground; let targetPathForeground;
for (let density in android_icons) { for (const density in android_icons) {
let backgroundVal = '@mipmap/ic_launcher_background'; let backgroundVal = '@mipmap/ic_launcher_background';
let foregroundVal = '@mipmap/ic_launcher_foreground'; let foregroundVal = '@mipmap/ic_launcher_foreground';
@ -476,7 +476,7 @@ function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformReso
<foreground android:drawable="` + foregroundVal + `" /> <foreground android:drawable="` + foregroundVal + `" />
</adaptive-icon>`; </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. // Remove the XML from the resourceMap so the file does not get removed.
delete resourceMap[launcherXmlPath]; delete resourceMap[launcherXmlPath];
@ -520,8 +520,8 @@ function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformReso
} }
function updateIconResourceForLegacy (preparedIcons, resourceMap, platformResourcesDir) { function updateIconResourceForLegacy (preparedIcons, resourceMap, platformResourcesDir) {
let android_icons = preparedIcons.android_icons; const android_icons = preparedIcons.android_icons;
let default_icon = preparedIcons.default_icon; const default_icon = preparedIcons.default_icon;
// The source paths for icons and splashes are relative to // The source paths for icons and splashes are relative to
// project's config.xml location, so we use it as base path. // project's config.xml location, so we use it as base path.
@ -550,7 +550,7 @@ function prepareIcons (icons) {
192: 'xxxhdpi' 192: 'xxxhdpi'
}; };
let android_icons = {}; const android_icons = {};
let default_icon; let default_icon;
// find the best matching icon for a given density or size // find the best matching icon for a given density or size
@ -580,8 +580,8 @@ function prepareIcons (icons) {
if (!size && !icon.density) { if (!size && !icon.density) {
if (default_icon) { if (default_icon) {
let found = {}; const found = {};
let favor = {}; const favor = {};
// populating found icon. // populating found icon.
if (icon.background && icon.foreground) { if (icon.background && icon.foreground) {
@ -624,7 +624,7 @@ function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {
return; return;
} }
let resourceMap = Object.assign( const resourceMap = Object.assign(
{}, {},
mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.png'), mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.png'),
mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.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. * Gets a map containing resources of a specified name from all drawable folders in a directory.
*/ */
function mapImageResources (rootDir, subDir, type, resourceName) { function mapImageResources (rootDir, subDir, type, resourceName) {
let pathMap = {}; const pathMap = {};
let pattern = new RegExp(type + '+-.+'); const pattern = new RegExp(type + '+-.+');
utils.scanDirectory(path.join(rootDir, subDir), pattern).forEach(function (drawableFolder) { 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; pathMap[imagePath] = null;
}); });
return pathMap; return pathMap;

View File

@ -34,7 +34,6 @@ var events = require('cordova-common').events;
* @returns {Promise} * @returns {Promise}
*/ */
module.exports.retryPromise = function (attemptsLeft, promiseFunction) { module.exports.retryPromise = function (attemptsLeft, promiseFunction) {
// NOTE: // NOTE:
// get all trailing arguments, by skipping the first two (attemptsLeft and // get all trailing arguments, by skipping the first two (attemptsLeft and
// promiseFunction) because they shouldn't get passed to promiseFunction // promiseFunction) because they shouldn't get passed to promiseFunction

View File

@ -49,9 +49,9 @@ exports.replaceFileContents = function (file, searchRegex, replacementString) {
* @returns string|null * @returns string|null
*/ */
exports.grep = function (file, regex) { 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++) { for (let i = 0; i < contents.length; i++) {
let line = contents[i]; const line = contents[i];
if (regex.test(line)) { if (regex.test(line)) {
return line; return line;
} }
@ -71,12 +71,12 @@ exports.scanDirectory = function (directory, regex, recursive) {
let output = []; let output = [];
if (fs.existsSync(directory)) { if (fs.existsSync(directory)) {
let items = fs.readdirSync(directory); const items = fs.readdirSync(directory);
for (let i = 0; i < items.length; i++) { for (let i = 0; i < items.length; i++) {
let item = items[i]; const item = items[i];
let itemPath = path.join(directory, item); const itemPath = path.join(directory, item);
let stats = fs.statSync(itemPath); const stats = fs.statSync(itemPath);
if (regex.test(itemPath)) { if (regex.test(itemPath)) {
output.push(itemPath); output.push(itemPath);

View File

@ -30,17 +30,17 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=
// Do some basic argument parsing // Do some basic argument parsing
var runOpts = nopt({ var runOpts = nopt({
'verbose': Boolean, verbose: Boolean,
'silent': Boolean, silent: Boolean,
'debug': Boolean, debug: Boolean,
'release': Boolean, release: Boolean,
'nobuild': Boolean, nobuild: Boolean,
'buildConfig': path, buildConfig: path,
'archs': String, archs: String,
'device': Boolean, device: Boolean,
'emulator': Boolean, emulator: Boolean,
'target': String target: String
}, { 'd': '--verbose' }); }, { d: '--verbose' });
// Make runOptions compatible with PlatformApi run method spec // Make runOptions compatible with PlatformApi run method spec
runOpts.argv = runOpts.argv.remain; runOpts.argv = runOpts.argv.remain;

View File

@ -21,10 +21,10 @@
var path = require('path'); var path = require('path');
var Api = require('./templates/cordova/Api'); var Api = require('./templates/cordova/Api');
var args = require('nopt')({ var args = require('nopt')({
'link': Boolean, link: Boolean,
'shared': Boolean, shared: Boolean,
'help': Boolean help: Boolean
}, { 'd': '--verbose' }); }, { d: '--verbose' });
if (args.help || args.argv.remain.length === 0) { if (args.help || args.argv.remain.length === 0) {
console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'update')) + ' <path_to_project> [--link]'); console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'update')) + ' <path_to_project> [--link]');

View File

@ -1,4 +0,0 @@
env:
node: false
commonjs: true
browser: true

View File

@ -19,12 +19,12 @@
"apache" "apache"
], ],
"scripts": { "scripts": {
"test": "npm run eslint && npm run cover && npm run java-unit-tests", "test": "npm run lint && npm run cover && npm run java-unit-tests",
"unit-tests": "jasmine --config=spec/unit/jasmine.json", "unit-tests": "jasmine --config=spec/unit/jasmine.json",
"cover": "nyc jasmine --config=spec/coverage.json", "cover": "nyc jasmine --config=spec/coverage.json",
"e2e-tests": "jasmine --config=spec/e2e/jasmine.json", "e2e-tests": "jasmine --config=spec/e2e/jasmine.json",
"java-unit-tests": "node test/run_java_unit_tests.js", "java-unit-tests": "node test/run_java_unit_tests.js",
"eslint": "eslint . \"bin/**/!(*.*|gitignore)\"", "lint": "eslint . \"bin/**/!(*.*|gitignore)\"",
"clean-tests": "node bin/clean_test.js" "clean-tests": "node bin/clean_test.js"
}, },
"author": "Apache Software Foundation", "author": "Apache Software Foundation",
@ -40,13 +40,7 @@
"which": "^1.3.1" "which": "^1.3.1"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^5.12.0", "@cordova/eslint-config": "^2.0.0",
"eslint-config-semistandard": "^13.0.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"jasmine": "^3.5.0", "jasmine": "^3.5.0",
"jasmine-spec-reporter": "^4.2.1", "jasmine-spec-reporter": "^4.2.1",
"nyc": "^14.1.1", "nyc": "^14.1.1",

View File

@ -1,4 +0,0 @@
env:
jasmine: true
rules:
prefer-promise-reject-errors: off

View File

@ -18,7 +18,7 @@
*/ */
var PluginInfoProvider = require('cordova-common').PluginInfoProvider; var PluginInfoProvider = require('cordova-common').PluginInfoProvider;
let fs = require('fs-extra'); const fs = require('fs-extra');
var cp = require('child_process'); var cp = require('child_process');
var path = require('path'); var path = require('path');
var util = require('util'); var util = require('util');
@ -77,7 +77,6 @@ module.exports.updateProject = function (projectid, platformpath, callback) {
} }
callback(error); callback(error);
}); });
}; };
/** /**

View File

@ -225,5 +225,4 @@ emulator-5554\tdevice
); );
}); });
}); });
}); });

View File

@ -238,5 +238,4 @@ describe('AndroidManifest', () => {
expect(fsSpy.writeFileSync).toHaveBeenCalledWith(jasmine.any(String), newXml, 'utf-8'); expect(fsSpy.writeFileSync).toHaveBeenCalledWith(jasmine.any(String), newXml, 'utf-8');
}); });
}); });
}); });

View File

@ -71,7 +71,7 @@ describe('android_sdk', () => {
execaSpy.and.returnValue(Promise.resolve({ stdout: testTargets })); execaSpy.and.returnValue(Promise.resolve({ stdout: testTargets }));
return android_sdk.list_targets_with_android().then(list => { return android_sdk.list_targets_with_android().then(list => {
[ 'Google Inc.:Google APIs:23', ['Google Inc.:Google APIs:23',
'Google Inc.:Google APIs:22', 'Google Inc.:Google APIs:22',
'Google Inc.:Google APIs:21', 'Google Inc.:Google APIs:21',
'android-25', 'android-25',
@ -81,7 +81,7 @@ describe('android_sdk', () => {
'android-MNC', 'android-MNC',
'android-22', 'android-22',
'android-21', 'android-21',
'android-20' ].forEach((target) => expect(list).toContain(target)); 'android-20'].forEach((target) => expect(list).toContain(target));
}); });
}); });
}); });

View File

@ -18,7 +18,7 @@
*/ */
const rewire = require('rewire'); const rewire = require('rewire');
let GradlePropertiesParser = rewire('../../../bin/templates/cordova/lib/config/GradlePropertiesParser'); const GradlePropertiesParser = rewire('../../../bin/templates/cordova/lib/config/GradlePropertiesParser');
describe('Gradle Builder', () => { describe('Gradle Builder', () => {
describe('_initializeEditor method', () => { describe('_initializeEditor method', () => {
@ -91,8 +91,8 @@ describe('Gradle Builder', () => {
}); });
it('should detect missing default property and sets the property.', () => { it('should detect missing default property and sets the property.', () => {
let setSpy = jasmine.createSpy('set'); const setSpy = jasmine.createSpy('set');
let getSpy = jasmine.createSpy('get').and.returnValue(false); const getSpy = jasmine.createSpy('get').and.returnValue(false);
parser.gradleFile = { parser.gradleFile = {
set: setSpy, set: setSpy,
@ -107,8 +107,8 @@ describe('Gradle Builder', () => {
}); });
it('should not detect missing defaults and call set.', () => { it('should not detect missing defaults and call set.', () => {
let setSpy = jasmine.createSpy('set'); const setSpy = jasmine.createSpy('set');
let getSpy = jasmine.createSpy('get').and.returnValue(true); const getSpy = jasmine.createSpy('get').and.returnValue(true);
parser.gradleFile = { parser.gradleFile = {
set: setSpy, set: setSpy,
@ -122,8 +122,8 @@ describe('Gradle Builder', () => {
}); });
it('should detect default with changed value to match default and set.', () => { it('should detect default with changed value to match default and set.', () => {
let setSpy = jasmine.createSpy('set'); const setSpy = jasmine.createSpy('set');
let getSpy = jasmine.createSpy('get').and.returnValue('-Xmx512m'); const getSpy = jasmine.createSpy('get').and.returnValue('-Xmx512m');
parser.gradleFile = { parser.gradleFile = {
set: setSpy, set: setSpy,
@ -138,8 +138,8 @@ describe('Gradle Builder', () => {
}); });
it('should detect default with changed value different from default and set.', () => { it('should detect default with changed value different from default and set.', () => {
let setSpy = jasmine.createSpy('set'); const setSpy = jasmine.createSpy('set');
let getSpy = jasmine.createSpy('get').and.returnValue('-Xmx2048m'); const getSpy = jasmine.createSpy('get').and.returnValue('-Xmx2048m');
parser.gradleFile = { parser.gradleFile = {
set: setSpy, set: setSpy,

View File

@ -224,7 +224,6 @@ describe('create', function () {
}, err => { }, err => {
expect(err).toBe(fakeError); expect(err).toBe(fakeError);
}); });
}); });
}); });

View File

@ -37,7 +37,7 @@ describe('emulator', () => {
it('should properly parse details of SDK Tools 25.3.1 `avdmanager` output', () => { it('should properly parse details of SDK Tools 25.3.1 `avdmanager` output', () => {
const avdList = fs.readFileSync(path.join('spec', 'fixtures', 'sdk25.3-avdmanager_list_avd.txt'), 'utf-8'); const avdList = fs.readFileSync(path.join('spec', 'fixtures', 'sdk25.3-avdmanager_list_avd.txt'), 'utf-8');
let execaSpy = jasmine.createSpy('execa').and.returnValue(Promise.resolve({ stdout: avdList })); const execaSpy = jasmine.createSpy('execa').and.returnValue(Promise.resolve({ stdout: avdList }));
emu.__set__('execa', execaSpy); emu.__set__('execa', execaSpy);
return emu.list_images_using_avdmanager().then(list => { return emu.list_images_using_avdmanager().then(list => {
@ -52,7 +52,7 @@ describe('emulator', () => {
describe('list_images_using_android', () => { describe('list_images_using_android', () => {
it('should invoke `android` with the `list avd` command and _not_ the `list avds` command, as the plural form is not supported in some Android SDK Tools versions', () => { it('should invoke `android` with the `list avd` command and _not_ the `list avds` command, as the plural form is not supported in some Android SDK Tools versions', () => {
let execaSpy = jasmine.createSpy('execa').and.returnValue(Promise.resolve({ stdout: '' })); const execaSpy = jasmine.createSpy('execa').and.returnValue(Promise.resolve({ stdout: '' }));
emu.__set__('execa', execaSpy); emu.__set__('execa', execaSpy);
emu.list_images_using_android(); emu.list_images_using_android();
@ -62,7 +62,7 @@ describe('emulator', () => {
it('should properly parse details of SDK Tools pre-25.3.1 `android list avd` output', () => { it('should properly parse details of SDK Tools pre-25.3.1 `android list avd` output', () => {
const avdList = fs.readFileSync(path.join('spec', 'fixtures', 'sdk25.2-android_list_avd.txt'), 'utf-8'); const avdList = fs.readFileSync(path.join('spec', 'fixtures', 'sdk25.2-android_list_avd.txt'), 'utf-8');
let execaSpy = jasmine.createSpy('execa').and.returnValue(Promise.resolve({ stdout: avdList })); const execaSpy = jasmine.createSpy('execa').and.returnValue(Promise.resolve({ stdout: avdList }));
emu.__set__('execa', execaSpy); emu.__set__('execa', execaSpy);
return emu.list_images_using_android().then(list => { return emu.list_images_using_android().then(list => {

View File

@ -35,7 +35,6 @@ var deleteJava = common.__get__('deleteJava');
var copyNewFile = common.__get__('copyNewFile'); var copyNewFile = common.__get__('copyNewFile');
describe('common platform handler', function () { describe('common platform handler', function () {
describe('copyFile', function () { describe('copyFile', function () {
it('Test#001 : should throw if source path not found', function () { it('Test#001 : should throw if source path not found', function () {
fs.removeSync(src); fs.removeSync(src);

View File

@ -177,7 +177,6 @@ describe('android project handler', function () {
}); });
describe('of <framework> elements', function () { describe('of <framework> elements', function () {
var someString = jasmine.any(String); var someString = jasmine.any(String);
var copyNewFileOrig = common.__get__('copyNewFile'); var copyNewFileOrig = common.__get__('copyNewFile');
@ -280,9 +279,8 @@ describe('android project handler', function () {
}); });
describe('uninstallation', function () { describe('uninstallation', function () {
var deleteJavaOrig = common.__get__('deleteJava'); var deleteJavaOrig = common.__get__('deleteJava');
let originalRemoveSync = fs.removeSync; const originalRemoveSync = fs.removeSync;
var deleteJavaSpy = jasmine.createSpy('deleteJava'); var deleteJavaSpy = jasmine.createSpy('deleteJava');
var dummyProject; var dummyProject;
let removeSyncSpy; let removeSyncSpy;
@ -387,7 +385,6 @@ describe('android project handler', function () {
}); });
describe('of <framework> elements', function () { describe('of <framework> elements', function () {
var someString = jasmine.any(String); var someString = jasmine.any(String);
beforeEach(function () { beforeEach(function () {

View File

@ -29,7 +29,7 @@ const PATH_RESOURCE = path.join('platforms', 'android', 'app', 'src', 'main', 'r
* @param {String} target specific resource item * @param {String} target specific resource item
*/ */
function createResourceMap (target) { function createResourceMap (target) {
let resources = {}; const resources = {};
[ [
'mipmap-ldpi', 'mipmap-ldpi',
@ -152,8 +152,8 @@ describe('updateIcons method', function () {
expect(emitSpy).toHaveBeenCalled(); expect(emitSpy).toHaveBeenCalled();
// The emit message was. // The emit message was.
let actual = emitSpy.calls.argsFor(0)[1]; const actual = emitSpy.calls.argsFor(0)[1];
let expected = 'This app does not have launcher icons defined'; const expected = 'This app does not have launcher icons defined';
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}); });
@ -340,11 +340,11 @@ describe('updateIcons method', function () {
}; };
// Creating Spies // Creating Spies
let resourceMap = createResourceMap(); const resourceMap = createResourceMap();
let phaseOneModification = {}; const phaseOneModification = {};
phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_foreground.png')] = 'res/icon/android/mdpi-foreground.png'; phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_foreground.png')] = 'res/icon/android/mdpi-foreground.png';
phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png'; phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png';
let phaseOneUpdatedIconsForAdaptive = Object.assign({}, resourceMap, phaseOneModification); const phaseOneUpdatedIconsForAdaptive = Object.assign({}, resourceMap, phaseOneModification);
updateIconResourceForAdaptiveSpy = jasmine.createSpy('updateIconResourceForAdaptiveSpy'); updateIconResourceForAdaptiveSpy = jasmine.createSpy('updateIconResourceForAdaptiveSpy');
prepare.__set__('updateIconResourceForAdaptive', function (preparedIcons, resourceMap, platformResourcesDir) { prepare.__set__('updateIconResourceForAdaptive', function (preparedIcons, resourceMap, platformResourcesDir) {
@ -352,10 +352,10 @@ describe('updateIcons method', function () {
return phaseOneUpdatedIconsForAdaptive; return phaseOneUpdatedIconsForAdaptive;
}); });
let phaseTwoModification = {}; const phaseTwoModification = {};
phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-foreground.png'; phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-foreground.png';
phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png'; phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png';
let phaseTwoUpdatedIconsForLegacy = Object.assign({}, phaseOneUpdatedIconsForAdaptive, phaseTwoModification); const phaseTwoUpdatedIconsForLegacy = Object.assign({}, phaseOneUpdatedIconsForAdaptive, phaseTwoModification);
updateIconResourceForLegacySpy = jasmine.createSpy('updateIconResourceForLegacySpy'); updateIconResourceForLegacySpy = jasmine.createSpy('updateIconResourceForLegacySpy');
prepare.__set__('updateIconResourceForLegacy', function (preparedIcons, resourceMap, platformResourcesDir) { prepare.__set__('updateIconResourceForLegacy', function (preparedIcons, resourceMap, platformResourcesDir) {
@ -369,8 +369,8 @@ describe('updateIcons method', function () {
expect(emitSpy).toHaveBeenCalled(); expect(emitSpy).toHaveBeenCalled();
// The emit message was. // The emit message was.
let actual = emitSpy.calls.argsFor(0)[1]; const actual = emitSpy.calls.argsFor(0)[1];
let expected = 'Updating icons at ' + PATH_RESOURCE; const expected = 'Updating icons at ' + PATH_RESOURCE;
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
// Expected to be called. // Expected to be called.
@ -378,8 +378,8 @@ describe('updateIcons method', function () {
expect(updateIconResourceForAdaptiveSpy).toHaveBeenCalled(); expect(updateIconResourceForAdaptiveSpy).toHaveBeenCalled();
expect(updateIconResourceForLegacySpy).toHaveBeenCalled(); expect(updateIconResourceForLegacySpy).toHaveBeenCalled();
let actualResourceMap = updatePathsSpy.calls.argsFor(0)[0]; const actualResourceMap = updatePathsSpy.calls.argsFor(0)[0];
let expectedResourceMap = phaseTwoUpdatedIconsForLegacy; const expectedResourceMap = phaseTwoUpdatedIconsForLegacy;
expect(actualResourceMap).toEqual(expectedResourceMap); expect(actualResourceMap).toEqual(expectedResourceMap);
}); });
@ -397,11 +397,11 @@ describe('updateIcons method', function () {
}; };
// Creating Spies // Creating Spies
let resourceMap = createResourceMap(); const resourceMap = createResourceMap();
let phaseOneModification = {}; const phaseOneModification = {};
phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_foreground.png')] = 'res/icon/android/mdpi-foreground.png'; phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_foreground.png')] = 'res/icon/android/mdpi-foreground.png';
phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png'; phaseOneModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png';
let phaseOneUpdatedIconsForAdaptive = Object.assign({}, resourceMap, phaseOneModification); const phaseOneUpdatedIconsForAdaptive = Object.assign({}, resourceMap, phaseOneModification);
updateIconResourceForAdaptiveSpy = jasmine.createSpy('updateIconResourceForAdaptiveSpy'); updateIconResourceForAdaptiveSpy = jasmine.createSpy('updateIconResourceForAdaptiveSpy');
prepare.__set__('updateIconResourceForAdaptive', function (preparedIcons, resourceMap, platformResourcesDir) { prepare.__set__('updateIconResourceForAdaptive', function (preparedIcons, resourceMap, platformResourcesDir) {
@ -409,10 +409,10 @@ describe('updateIcons method', function () {
return phaseOneUpdatedIconsForAdaptive; return phaseOneUpdatedIconsForAdaptive;
}); });
let phaseTwoModification = {}; const phaseTwoModification = {};
phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-foreground.png'; phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-foreground.png';
phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png'; phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png';
let phaseTwoUpdatedIconsForLegacy = Object.assign({}, phaseOneUpdatedIconsForAdaptive, phaseTwoModification); const phaseTwoUpdatedIconsForLegacy = Object.assign({}, phaseOneUpdatedIconsForAdaptive, phaseTwoModification);
updateIconResourceForLegacySpy = jasmine.createSpy('updateIconResourceForLegacySpy'); updateIconResourceForLegacySpy = jasmine.createSpy('updateIconResourceForLegacySpy');
prepare.__set__('updateIconResourceForLegacy', function (preparedIcons, resourceMap, platformResourcesDir) { prepare.__set__('updateIconResourceForLegacy', function (preparedIcons, resourceMap, platformResourcesDir) {
@ -426,8 +426,8 @@ describe('updateIcons method', function () {
expect(emitSpy).toHaveBeenCalled(); expect(emitSpy).toHaveBeenCalled();
// The emit message was. // The emit message was.
let actual = emitSpy.calls.argsFor(0)[1]; const actual = emitSpy.calls.argsFor(0)[1];
let expected = 'Updating icons at ' + PATH_RESOURCE; const expected = 'Updating icons at ' + PATH_RESOURCE;
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
// Expected to be called. // Expected to be called.
@ -435,8 +435,8 @@ describe('updateIcons method', function () {
expect(updateIconResourceForAdaptiveSpy).toHaveBeenCalled(); expect(updateIconResourceForAdaptiveSpy).toHaveBeenCalled();
expect(updateIconResourceForLegacySpy).toHaveBeenCalled(); expect(updateIconResourceForLegacySpy).toHaveBeenCalled();
let actualResourceMap = updatePathsSpy.calls.argsFor(0)[0]; const actualResourceMap = updatePathsSpy.calls.argsFor(0)[0];
let expectedResourceMap = phaseTwoUpdatedIconsForLegacy; const expectedResourceMap = phaseTwoUpdatedIconsForLegacy;
expect(actualResourceMap).toEqual(expectedResourceMap); expect(actualResourceMap).toEqual(expectedResourceMap);
}); });
@ -452,7 +452,7 @@ describe('updateIcons method', function () {
}; };
// Creating Spies // Creating Spies
let phaseOneUpdatedIconsForAdaptive = createResourceMap(); const phaseOneUpdatedIconsForAdaptive = createResourceMap();
updateIconResourceForAdaptiveSpy = jasmine.createSpy('updateIconResourceForAdaptiveSpy'); updateIconResourceForAdaptiveSpy = jasmine.createSpy('updateIconResourceForAdaptiveSpy');
prepare.__set__('updateIconResourceForAdaptive', function (preparedIcons, resourceMap, platformResourcesDir) { prepare.__set__('updateIconResourceForAdaptive', function (preparedIcons, resourceMap, platformResourcesDir) {
@ -460,9 +460,9 @@ describe('updateIcons method', function () {
return phaseOneUpdatedIconsForAdaptive; return phaseOneUpdatedIconsForAdaptive;
}); });
let phaseTwoModification = {}; const phaseTwoModification = {};
phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-icon.png'; phaseTwoModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-icon.png';
let phaseTwoUpdatedIconsForLegacy = Object.assign({}, phaseOneUpdatedIconsForAdaptive, phaseTwoModification); const phaseTwoUpdatedIconsForLegacy = Object.assign({}, phaseOneUpdatedIconsForAdaptive, phaseTwoModification);
updateIconResourceForLegacySpy = jasmine.createSpy('updateIconResourceForLegacySpy'); updateIconResourceForLegacySpy = jasmine.createSpy('updateIconResourceForLegacySpy');
prepare.__set__('updateIconResourceForLegacy', function (preparedIcons, resourceMap, platformResourcesDir) { prepare.__set__('updateIconResourceForLegacy', function (preparedIcons, resourceMap, platformResourcesDir) {
@ -476,8 +476,8 @@ describe('updateIcons method', function () {
expect(emitSpy).toHaveBeenCalled(); expect(emitSpy).toHaveBeenCalled();
// The emit message was. // The emit message was.
let actual = emitSpy.calls.argsFor(0)[1]; const actual = emitSpy.calls.argsFor(0)[1];
let expected = 'Updating icons at ' + PATH_RESOURCE; const expected = 'Updating icons at ' + PATH_RESOURCE;
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
// Expected to be called. // Expected to be called.
@ -485,8 +485,8 @@ describe('updateIcons method', function () {
expect(updateIconResourceForAdaptiveSpy).not.toHaveBeenCalled(); expect(updateIconResourceForAdaptiveSpy).not.toHaveBeenCalled();
expect(updateIconResourceForLegacySpy).toHaveBeenCalled(); expect(updateIconResourceForLegacySpy).toHaveBeenCalled();
let actualResourceMap = updatePathsSpy.calls.argsFor(0)[0]; const actualResourceMap = updatePathsSpy.calls.argsFor(0)[0];
let expectedResourceMap = phaseTwoUpdatedIconsForLegacy; const expectedResourceMap = phaseTwoUpdatedIconsForLegacy;
expect(actualResourceMap).toEqual(expectedResourceMap); expect(actualResourceMap).toEqual(expectedResourceMap);
}); });
}); });
@ -510,50 +510,48 @@ describe('prepareIcons method', function () {
it('Test#001 : should emit extra default icon found for adaptive use case.', function () { it('Test#001 : should emit extra default icon found for adaptive use case.', function () {
// mock data. // mock data.
let ldpi = mockGetIconItem({ const ldpi = mockGetIconItem({
density: 'ldpi', density: 'ldpi',
background: 'res/icon/android/ldpi-background.png', background: 'res/icon/android/ldpi-background.png',
foreground: 'res/icon/android/ldpi-foreground.png' foreground: 'res/icon/android/ldpi-foreground.png'
}); });
let mdpi = mockGetIconItem({ const mdpi = mockGetIconItem({
density: 'mdpi', density: 'mdpi',
background: 'res/icon/android/mdpi-background.png', background: 'res/icon/android/mdpi-background.png',
foreground: 'res/icon/android/mdpi-foreground.png' foreground: 'res/icon/android/mdpi-foreground.png'
}); });
let icons = [ldpi, mdpi]; const icons = [ldpi, mdpi];
let actual = prepareIcons(icons); const actual = prepareIcons(icons);
let expected = { const expected = {
android_icons: { ldpi, mdpi }, android_icons: { ldpi, mdpi },
default_icon: undefined default_icon: undefined
}; };
expect(expected).toEqual(actual); expect(expected).toEqual(actual);
}); });
it('Test#002 : should emit extra default icon found for legacy use case.', function () { it('Test#002 : should emit extra default icon found for legacy use case.', function () {
// mock data. // mock data.
let ldpi = mockGetIconItem({ const ldpi = mockGetIconItem({
src: 'res/icon/android/ldpi-icon.png', src: 'res/icon/android/ldpi-icon.png',
density: 'ldpi' density: 'ldpi'
}); });
let mdpi = mockGetIconItem({ const mdpi = mockGetIconItem({
src: 'res/icon/android/mdpi-icon.png', src: 'res/icon/android/mdpi-icon.png',
density: 'mdpi' density: 'mdpi'
}); });
let icons = [ldpi, mdpi]; const icons = [ldpi, mdpi];
let actual = prepareIcons(icons); const actual = prepareIcons(icons);
let expected = { const expected = {
android_icons: { ldpi, mdpi }, android_icons: { ldpi, mdpi },
default_icon: undefined default_icon: undefined
}; };
expect(expected).toEqual(actual); expect(expected).toEqual(actual);
}); });
}); });
@ -596,13 +594,12 @@ describe('updateIconResourceForLegacy method', function () {
const updateIconResourceForLegacy = prepare.__get__('updateIconResourceForLegacy'); const updateIconResourceForLegacy = prepare.__get__('updateIconResourceForLegacy');
// Run Test // Run Test
let expectedModification = {}; const expectedModification = {};
expectedModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-icon.png'; expectedModification[path.join(PATH_RESOURCE, 'mipmap-mdpi', 'ic_launcher.png')] = 'res/icon/android/mdpi-icon.png';
let expected = Object.assign({}, resourceMap, expectedModification); const expected = Object.assign({}, resourceMap, expectedModification);
let actual = updateIconResourceForLegacy(preparedIcons, resourceMap, platformResourcesDir); const actual = updateIconResourceForLegacy(preparedIcons, resourceMap, platformResourcesDir);
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}); });
}); });
@ -646,15 +643,14 @@ describe('updateIconResourceForAdaptive method', function () {
const updateIconResourceForAdaptive = prepare.__get__('updateIconResourceForAdaptive'); const updateIconResourceForAdaptive = prepare.__get__('updateIconResourceForAdaptive');
// Run Test // Run Test
let expectedModification = {}; const expectedModification = {};
expectedModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png'; expectedModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_background.png')] = 'res/icon/android/mdpi-background.png';
expectedModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_foreground.png')] = 'res/icon/android/mdpi-foreground.png'; expectedModification[path.join(PATH_RESOURCE, 'mipmap-mdpi-v26', 'ic_launcher_foreground.png')] = 'res/icon/android/mdpi-foreground.png';
let expected = Object.assign({}, resourceMap, expectedModification); const expected = Object.assign({}, resourceMap, expectedModification);
let actual = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir); const actual = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir);
expect(actual).toEqual(expected); expect(actual).toEqual(expected);
}); });
}); });
@ -679,36 +675,36 @@ describe('cleanIcons method', function () {
it('Test#001 : should detect that the app does not have defined icons.', function () { it('Test#001 : should detect that the app does not have defined icons.', function () {
// Mock // Mock
let icons = []; const icons = [];
let projectRoot = '/mock'; const projectRoot = '/mock';
let projectConfig = { const projectConfig = {
getIcons: function () { return icons; }, getIcons: function () { return icons; },
path: '/mock/config.xml', path: '/mock/config.xml',
cdvNamespacePrefix: 'cdv' cdvNamespacePrefix: 'cdv'
}; };
let platformResourcesDir = PATH_RESOURCE; const platformResourcesDir = PATH_RESOURCE;
const cleanIcons = prepare.__get__('cleanIcons'); const cleanIcons = prepare.__get__('cleanIcons');
cleanIcons(projectRoot, projectConfig, platformResourcesDir); cleanIcons(projectRoot, projectConfig, platformResourcesDir);
let actualEmitMessage = emitSpy.calls.argsFor(0)[1]; const actualEmitMessage = emitSpy.calls.argsFor(0)[1];
expect(actualEmitMessage).toContain('This app does not have launcher icons defined'); expect(actualEmitMessage).toContain('This app does not have launcher icons defined');
}); });
it('Test#002 : Should clean paths for adaptive icons.', function () { it('Test#002 : Should clean paths for adaptive icons.', function () {
// Mock // Mock
let icons = [mockGetIconItem({ const icons = [mockGetIconItem({
density: 'mdpi', density: 'mdpi',
background: 'res/icon/android/mdpi-background.png', background: 'res/icon/android/mdpi-background.png',
foreground: 'res/icon/android/mdpi-foreground.png' foreground: 'res/icon/android/mdpi-foreground.png'
})]; })];
let projectRoot = '/mock'; const projectRoot = '/mock';
let projectConfig = { const projectConfig = {
getIcons: function () { return icons; }, getIcons: function () { return icons; },
path: '/mock/config.xml', path: '/mock/config.xml',
cdvNamespacePrefix: 'cdv' cdvNamespacePrefix: 'cdv'
}; };
let platformResourcesDir = PATH_RESOURCE; const platformResourcesDir = PATH_RESOURCE;
var expectedResourceMapBackground = createResourceMap('ic_launcher_background.png'); var expectedResourceMapBackground = createResourceMap('ic_launcher_background.png');
@ -722,24 +718,24 @@ describe('cleanIcons method', function () {
const cleanIcons = prepare.__get__('cleanIcons'); const cleanIcons = prepare.__get__('cleanIcons');
cleanIcons(projectRoot, projectConfig, platformResourcesDir); cleanIcons(projectRoot, projectConfig, platformResourcesDir);
let actualResourceMapBackground = updatePathsSpy.calls.argsFor(0)[0]; const actualResourceMapBackground = updatePathsSpy.calls.argsFor(0)[0];
expect(actualResourceMapBackground).toEqual(expectedResourceMapBackground); expect(actualResourceMapBackground).toEqual(expectedResourceMapBackground);
}); });
it('Test#003 : Should clean paths for legacy icons.', function () { it('Test#003 : Should clean paths for legacy icons.', function () {
// Mock // Mock
let icons = [mockGetIconItem({ const icons = [mockGetIconItem({
src: 'res/icon/android/mdpi.png', src: 'res/icon/android/mdpi.png',
density: 'mdpi' density: 'mdpi'
})]; })];
let projectRoot = '/mock'; const projectRoot = '/mock';
let projectConfig = { const projectConfig = {
getIcons: function () { return icons; }, getIcons: function () { return icons; },
path: '/mock/config.xml', path: '/mock/config.xml',
cdvNamespacePrefix: 'cdv' cdvNamespacePrefix: 'cdv'
}; };
let platformResourcesDir = PATH_RESOURCE; const platformResourcesDir = PATH_RESOURCE;
var expectedResourceMap = createResourceMap(); var expectedResourceMap = createResourceMap();
@ -751,7 +747,7 @@ describe('cleanIcons method', function () {
const cleanIcons = prepare.__get__('cleanIcons'); const cleanIcons = prepare.__get__('cleanIcons');
cleanIcons(projectRoot, projectConfig, platformResourcesDir); cleanIcons(projectRoot, projectConfig, platformResourcesDir);
let actualResourceMap = updatePathsSpy.calls.argsFor(0)[0]; const actualResourceMap = updatePathsSpy.calls.argsFor(0)[0];
expect(actualResourceMap).toEqual(expectedResourceMap); expect(actualResourceMap).toEqual(expectedResourceMap);
}); });
}); });