chore(npm): bump @cordova/eslint-config@^4.0.0 (#1421)

* chore(npm): bump @cordova/eslint-config@^4.0.0
* style(lint): apply auto corrections
* style(lint): convert hasAndroidHome var to let and hoisted
This commit is contained in:
エリス 2022-04-18 10:39:54 +09:00 committed by GitHub
parent 62ed71c539
commit a2bb7f1173
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 1091 additions and 2686 deletions

View File

@ -17,12 +17,12 @@
under the License. under the License.
*/ */
var os = require('os'); const os = require('os');
var execa = require('execa'); const execa = require('execa');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
var Adb = {}; const Adb = {};
/** /**
* Lists available/connected devices and emulators * Lists available/connected devices and emulators
@ -50,7 +50,7 @@ Adb.devices = async function () {
Adb.install = function (target, packagePath, { replace = false, execOptions = {} } = {}) { Adb.install = function (target, packagePath, { replace = false, execOptions = {} } = {}) {
events.emit('verbose', 'Installing apk ' + packagePath + ' on target ' + target + '...'); events.emit('verbose', 'Installing apk ' + packagePath + ' on target ' + target + '...');
var args = ['-s', target, 'install']; const args = ['-s', target, 'install'];
if (replace) args.push('-r'); if (replace) args.push('-r');
const opts = { cwd: os.tmpdir(), ...execOptions }; const opts = { cwd: os.tmpdir(), ...execOptions };
@ -79,7 +79,7 @@ Adb.uninstall = function (target, packageId) {
Adb.shell = function (target, shellCommand) { Adb.shell = function (target, shellCommand) {
events.emit('verbose', 'Running adb shell command "' + shellCommand + '" on target ' + target + '...'); events.emit('verbose', 'Running adb shell command "' + shellCommand + '" on target ' + target + '...');
var args = ['-s', target, 'shell']; const args = ['-s', target, 'shell'];
shellCommand = shellCommand.split(/\s+/); shellCommand = shellCommand.split(/\s+/);
return execa('adb', args.concat(shellCommand), { cwd: os.tmpdir() }) return execa('adb', args.concat(shellCommand), { cwd: os.tmpdir() })
.then(({ stdout }) => stdout) .then(({ stdout }) => stdout)

View File

@ -17,10 +17,10 @@
under the License. under the License.
*/ */
var fs = require('fs'); const fs = require('fs');
var xml = require('cordova-common').xmlHelpers; const xml = require('cordova-common').xmlHelpers;
var DEFAULT_ORIENTATION = 'default'; const DEFAULT_ORIENTATION = 'default';
/** Wraps an AndroidManifest file */ /** Wraps an AndroidManifest file */
class AndroidManifest { class AndroidManifest {
@ -60,7 +60,7 @@ class AndroidManifest {
} }
getActivity () { getActivity () {
var activity = this.doc.getroot().find('./application/activity'); const activity = this.doc.getroot().find('./application/activity');
return { return {
getName: function () { getName: function () {
return activity.attrib['android:name']; return activity.attrib['android:name'];
@ -103,7 +103,7 @@ class AndroidManifest {
} }
setDebuggable (value) { setDebuggable (value) {
var application = this.doc.getroot().find('./application'); const application = this.doc.getroot().find('./application');
if (value) { if (value) {
application.attrib['android:debuggable'] = 'true'; application.attrib['android:debuggable'] = 'true';
} else { } else {

View File

@ -17,16 +17,16 @@
under the License. under the License.
*/ */
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var properties_parser = require('properties-parser'); const properties_parser = require('properties-parser');
var AndroidManifest = require('./AndroidManifest'); const AndroidManifest = require('./AndroidManifest');
var pluginHandlers = require('./pluginHandlers'); const pluginHandlers = require('./pluginHandlers');
var projectFileCache = {}; let projectFileCache = {};
function addToPropertyList (projectProperties, key, value) { function addToPropertyList (projectProperties, key, value) {
var i = 1; let i = 1;
while (projectProperties.get(key + '.' + i)) { i++; } while (projectProperties.get(key + '.' + i)) { i++; }
projectProperties.set(key + '.' + i, value); projectProperties.set(key + '.' + i, value);
@ -34,8 +34,8 @@ function addToPropertyList (projectProperties, key, value) {
} }
function removeFromPropertyList (projectProperties, key, value) { function removeFromPropertyList (projectProperties, key, value) {
var i = 1; let i = 1;
var currentValue; let currentValue;
while ((currentValue = projectProperties.get(key + '.' + i))) { while ((currentValue = projectProperties.get(key + '.' + i))) {
if (currentValue === value) { if (currentValue === value) {
while ((currentValue = projectProperties.get(key + '.' + (i + 1)))) { while ((currentValue = projectProperties.get(key + '.' + (i + 1)))) {
@ -51,7 +51,7 @@ function removeFromPropertyList (projectProperties, key, value) {
} }
function getRelativeLibraryPath (parentDir, subDir) { function getRelativeLibraryPath (parentDir, subDir) {
var libraryPath = path.relative(parentDir, subDir); const libraryPath = path.relative(parentDir, subDir);
return (path.sep === '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath; return (path.sep === '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;
} }
@ -72,27 +72,27 @@ class AndroidProject {
* @return {String} The name of the package * @return {String} The name of the package
*/ */
getPackageName () { getPackageName () {
var manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml'); const manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');
return new AndroidManifest(manifestPath).getPackageId(); return new AndroidManifest(manifestPath).getPackageId();
} }
getCustomSubprojectRelativeDir (plugin_id, src) { getCustomSubprojectRelativeDir (plugin_id, src) {
// All custom subprojects are prefixed with the last portion of the package id. // All custom subprojects are prefixed with the last portion of the package id.
// This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name. // This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.
var packageName = this.getPackageName(); const packageName = this.getPackageName();
var lastDotIndex = packageName.lastIndexOf('.'); const lastDotIndex = packageName.lastIndexOf('.');
var prefix = packageName.substring(lastDotIndex + 1); const prefix = packageName.substring(lastDotIndex + 1);
var subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src)); const subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src));
return subRelativeDir; return subRelativeDir;
} }
addSubProject (parentDir, subDir) { addSubProject (parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties'); const parentProjectFile = path.resolve(parentDir, 'project.properties');
var subProjectFile = path.resolve(subDir, 'project.properties'); const subProjectFile = path.resolve(subDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile); const parentProperties = this._getPropertiesFile(parentProjectFile);
// TODO: Setting the target needs to happen only for pre-3.7.0 projects // TODO: Setting the target needs to happen only for pre-3.7.0 projects
if (fs.existsSync(subProjectFile)) { if (fs.existsSync(subProjectFile)) {
var subProperties = this._getPropertiesFile(subProjectFile); const subProperties = this._getPropertiesFile(subProjectFile);
subProperties.set('target', parentProperties.get('target')); subProperties.set('target', parentProperties.get('target'));
subProperties.dirty = true; subProperties.dirty = true;
this._subProjectDirs[subDir] = true; this._subProjectDirs[subDir] = true;
@ -103,37 +103,37 @@ class AndroidProject {
} }
removeSubProject (parentDir, subDir) { removeSubProject (parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties'); const parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile); const parentProperties = this._getPropertiesFile(parentProjectFile);
removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir)); removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));
delete this._subProjectDirs[subDir]; delete this._subProjectDirs[subDir];
this._dirty = true; this._dirty = true;
} }
addGradleReference (parentDir, subDir) { addGradleReference (parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties'); const parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile); const parentProperties = this._getPropertiesFile(parentProjectFile);
addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir)); addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
this._dirty = true; this._dirty = true;
} }
removeGradleReference (parentDir, subDir) { removeGradleReference (parentDir, subDir) {
var parentProjectFile = path.resolve(parentDir, 'project.properties'); const parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile); const parentProperties = this._getPropertiesFile(parentProjectFile);
removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir)); removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));
this._dirty = true; this._dirty = true;
} }
addSystemLibrary (parentDir, value) { addSystemLibrary (parentDir, value) {
var parentProjectFile = path.resolve(parentDir, 'project.properties'); const parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile); const parentProperties = this._getPropertiesFile(parentProjectFile);
addToPropertyList(parentProperties, 'cordova.system.library', value); addToPropertyList(parentProperties, 'cordova.system.library', value);
this._dirty = true; this._dirty = true;
} }
removeSystemLibrary (parentDir, value) { removeSystemLibrary (parentDir, value) {
var parentProjectFile = path.resolve(parentDir, 'project.properties'); const parentProjectFile = path.resolve(parentDir, 'project.properties');
var parentProperties = this._getPropertiesFile(parentProjectFile); const parentProperties = this._getPropertiesFile(parentProjectFile);
removeFromPropertyList(parentProperties, 'cordova.system.library', value); removeFromPropertyList(parentProperties, 'cordova.system.library', value);
this._dirty = true; this._dirty = true;
} }
@ -144,8 +144,8 @@ class AndroidProject {
} }
this._dirty = false; this._dirty = false;
for (var filename in this._propertiesEditors) { for (const filename in this._propertiesEditors) {
var editor = this._propertiesEditors[filename]; const editor = this._propertiesEditors[filename];
if (editor.dirty) { if (editor.dirty) {
fs.writeFileSync(filename, editor.toString()); fs.writeFileSync(filename, editor.toString());
editor.dirty = false; editor.dirty = false;
@ -165,7 +165,7 @@ class AndroidProject {
* This checks if an Android project is clean or has old build artifacts * This checks if an Android project is clean or has old build artifacts
*/ */
isClean () { isClean () {
var build_path = path.join(this.projectDir, 'build'); const build_path = path.join(this.projectDir, 'build');
// If the build directory doesn't exist, it's clean // If the build directory doesn't exist, it's clean
return !(fs.existsSync(build_path)); return !(fs.existsSync(build_path));
} }

View File

@ -17,17 +17,17 @@
under the License. under the License.
*/ */
var path = require('path'); const path = require('path');
var AndroidProject = require('./AndroidProject'); const AndroidProject = require('./AndroidProject');
var PluginManager = require('cordova-common').PluginManager; const PluginManager = require('cordova-common').PluginManager;
var CordovaLogger = require('cordova-common').CordovaLogger; const CordovaLogger = require('cordova-common').CordovaLogger;
var selfEvents = require('cordova-common').events; const selfEvents = require('cordova-common').events;
var ConfigParser = require('cordova-common').ConfigParser; const ConfigParser = require('cordova-common').ConfigParser;
const prepare = require('./prepare').prepare; const prepare = require('./prepare').prepare;
var PLATFORM = 'android'; const PLATFORM = 'android';
const VERSION = require('../package').version; const VERSION = require('../package').version;
function setupEvents (externalEventEmitter) { function setupEvents (externalEventEmitter) {
@ -88,7 +88,7 @@ class Api {
* platform's file structure and other properties of platform. * platform's file structure and other properties of platform.
*/ */
getPlatformInfo () { getPlatformInfo () {
var result = {}; const result = {};
result.locations = this.locations; result.locations = this.locations;
result.root = this.root; result.root = this.root;
result.name = this.platform; result.name = this.platform;
@ -139,8 +139,8 @@ class Api {
* CordovaError instance. * CordovaError instance.
*/ */
addPlugin (plugin, installOptions) { addPlugin (plugin, installOptions) {
var project = AndroidProject.getProjectFile(this.root); const project = AndroidProject.getProjectFile(this.root);
var self = this; const self = this;
installOptions = installOptions || {}; installOptions = installOptions || {};
installOptions.variables = installOptions.variables || {}; installOptions.variables = installOptions.variables || {};
@ -175,7 +175,7 @@ class Api {
* CordovaError instance. * CordovaError instance.
*/ */
removePlugin (plugin, uninstallOptions) { removePlugin (plugin, uninstallOptions) {
var project = AndroidProject.getProjectFile(this.root); const project = AndroidProject.getProjectFile(this.root);
if (uninstallOptions && uninstallOptions.usePlatformWww === true) { if (uninstallOptions && uninstallOptions.usePlatformWww === true) {
uninstallOptions.usePlatformWww = false; uninstallOptions.usePlatformWww = false;
@ -239,7 +239,7 @@ class Api {
* arhcitectures is specified. * arhcitectures is specified.
*/ */
build (buildOptions) { build (buildOptions) {
var self = this; const self = this;
return require('./check_reqs').run().then(function () { return require('./check_reqs').run().then(function () {
return require('./build').run.call(self, buildOptions); return require('./build').run.call(self, buildOptions);
@ -269,7 +269,7 @@ class Api {
* successfully, or rejected with CordovaError. * successfully, or rejected with CordovaError.
*/ */
run (runOptions) { run (runOptions) {
var self = this; const self = this;
return require('./check_reqs').run().then(function () { return require('./check_reqs').run().then(function () {
return require('./run').run.call(self, runOptions); return require('./run').run.call(self, runOptions);
}); });
@ -283,7 +283,7 @@ class Api {
* CordovaError. * CordovaError.
*/ */
clean (cleanOptions) { clean (cleanOptions) {
var self = this; const self = this;
// This will lint, checking for null won't // This will lint, checking for null won't
if (typeof cleanOptions === 'undefined') { if (typeof cleanOptions === 'undefined') {
cleanOptions = {}; cleanOptions = {};
@ -328,7 +328,7 @@ class Api {
*/ */
static createPlatform (destination, config, options, events) { static createPlatform (destination, config, options, events) {
events = setupEvents(events); events = setupEvents(events);
var result; let result;
try { try {
result = require('./create').create(destination, config, options, events).then(function (destination) { result = require('./create').create(destination, config, options, events).then(function (destination) {
return new Api(PLATFORM, destination, events); return new Api(PLATFORM, destination, events);
@ -358,7 +358,7 @@ class Api {
*/ */
static updatePlatform (destination, options, events) { static updatePlatform (destination, options, events) {
events = setupEvents(events); events = setupEvents(events);
var result; let result;
try { try {
result = require('../../lib/create').update(destination, options, events).then(function (destination) { result = require('../../lib/create').update(destination, options, events).then(function (destination) {
return new Api(PLATFORM, destination, events); return new Api(PLATFORM, destination, events);

View File

@ -19,7 +19,7 @@
const execa = require('execa'); const execa = require('execa');
var suffix_number_regex = /(\d+)$/; const suffix_number_regex = /(\d+)$/;
// Used for sorting Android targets, example strings to sort: // Used for sorting Android targets, example strings to sort:
// android-19 // android-19
// android-L // android-L
@ -66,9 +66,9 @@ module.exports.version_string_to_api_level = {
/* eslint-enable quote-props */ /* eslint-enable quote-props */
function parse_targets (output) { function parse_targets (output) {
var target_out = output.split('\n'); const target_out = output.split('\n');
var targets = []; const targets = [];
for (var i = target_out.length - 1; i >= 0; i--) { for (let i = target_out.length - 1; i >= 0; i--) {
if (target_out[i].match(/id:/)) { // if "id:" is in the line... if (target_out[i].match(/id:/)) { // if "id:" is in the line...
targets.push(target_out[i].match(/"(.+)"/)[1]); // .. match whatever is in quotes. targets.push(target_out[i].match(/"(.+)"/)[1]); // .. match whatever is in quotes.
} }

View File

@ -17,15 +17,15 @@
under the License. under the License.
*/ */
var path = require('path'); const path = require('path');
var fs = require('fs'); const fs = require('fs');
var nopt = require('nopt'); const nopt = require('nopt');
const untildify = require('untildify'); const untildify = require('untildify');
var Adb = require('./Adb'); const Adb = require('./Adb');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var PackageType = require('./PackageType'); const PackageType = require('./PackageType');
module.exports.parseBuildOptions = parseOpts; module.exports.parseBuildOptions = parseOpts;
function parseOpts (options, resolvedTarget, projectRoot) { function parseOpts (options, resolvedTarget, projectRoot) {
@ -46,7 +46,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {
}, {}, options.argv, 0); }, {}, options.argv, 0);
// Android Studio Build method is the default // Android Studio Build method is the default
var ret = { const ret = {
buildType: options.release ? 'release' : 'debug', buildType: options.release ? 'release' : 'debug',
prepEnv: options.argv.prepenv, prepEnv: options.argv.prepenv,
arch: resolvedTarget && resolvedTarget.arch, arch: resolvedTarget && resolvedTarget.arch,
@ -61,7 +61,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {
ret.extraArgs = ret.extraArgs.concat(options.argv.gradleArg); ret.extraArgs = ret.extraArgs.concat(options.argv.gradleArg);
} }
var packageArgs = {}; const packageArgs = {};
if (options.argv.keystore) { packageArgs.keystore = path.relative(projectRoot, path.resolve(options.argv.keystore)); } if (options.argv.keystore) { packageArgs.keystore = path.relative(projectRoot, path.resolve(options.argv.keystore)); }
@ -69,7 +69,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {
if (options.argv[flagName]) { packageArgs[flagName] = options.argv[flagName]; } if (options.argv[flagName]) { packageArgs[flagName] = options.argv[flagName]; }
}); });
var buildConfig = options.buildConfig; const buildConfig = options.buildConfig;
// If some values are not specified as command line arguments - use build config to supplement them. // If some values are not specified as command line arguments - use build config to supplement them.
// Command line arguments have precedence over build config. // Command line arguments have precedence over build config.
@ -78,10 +78,10 @@ function parseOpts (options, resolvedTarget, projectRoot) {
throw new Error('Specified build config file does not exist: ' + buildConfig); throw new Error('Specified build config file does not exist: ' + buildConfig);
} }
events.emit('log', 'Reading build config file: ' + path.resolve(buildConfig)); events.emit('log', 'Reading build config file: ' + path.resolve(buildConfig));
var buildjson = fs.readFileSync(buildConfig, 'utf8'); const buildjson = fs.readFileSync(buildConfig, 'utf8');
var config = JSON.parse(buildjson.replace(/^\ufeff/, '')); // Remove BOM const config = JSON.parse(buildjson.replace(/^\ufeff/, '')); // Remove BOM
if (config.android && config.android[ret.buildType]) { if (config.android && config.android[ret.buildType]) {
var androidInfo = config.android[ret.buildType]; const androidInfo = config.android[ret.buildType];
if (androidInfo.keystore && !packageArgs.keystore) { if (androidInfo.keystore && !packageArgs.keystore) {
androidInfo.keystore = untildify(androidInfo.keystore); androidInfo.keystore = untildify(androidInfo.keystore);
packageArgs.keystore = path.resolve(path.dirname(buildConfig), androidInfo.keystore); packageArgs.keystore = path.resolve(path.dirname(buildConfig), androidInfo.keystore);
@ -144,8 +144,8 @@ function parseOpts (options, resolvedTarget, projectRoot) {
* Returns a promise. * Returns a promise.
*/ */
module.exports.runClean = function (options) { module.exports.runClean = function (options) {
var opts = parseOpts(options, null, this.root); const opts = parseOpts(options, null, this.root);
var builder = this._builder; const builder = this._builder;
return builder.prepEnv(opts).then(function () { return builder.prepEnv(opts).then(function () {
return builder.clean(opts); return builder.clean(opts);
@ -165,8 +165,8 @@ module.exports.runClean = function (options) {
* information. * information.
*/ */
module.exports.run = function (options, optResolvedTarget) { module.exports.run = function (options, optResolvedTarget) {
var opts = parseOpts(options, optResolvedTarget, this.root); const opts = parseOpts(options, optResolvedTarget, this.root);
var builder = this._builder; const builder = this._builder;
return builder.prepEnv(opts).then(function () { return builder.prepEnv(opts).then(function () {
if (opts.prepEnv) { if (opts.prepEnv) {
@ -174,7 +174,7 @@ module.exports.run = function (options, optResolvedTarget) {
return; return;
} }
return builder.build(opts).then(function () { return builder.build(opts).then(function () {
var paths; let paths;
if (opts.packageType === PackageType.BUNDLE) { if (opts.packageType === PackageType.BUNDLE) {
paths = builder.findOutputBundles(opts.buildType); paths = builder.findOutputBundles(opts.buildType);
events.emit('log', 'Built the following bundle(s): \n\t' + paths.join('\n\t')); events.emit('log', 'Built the following bundle(s): \n\t' + paths.join('\n\t'));
@ -202,17 +202,17 @@ module.exports.detectArchitecture = function (target) {
}; };
module.exports.findBestApkForArchitecture = function (buildResults, arch) { module.exports.findBestApkForArchitecture = function (buildResults, arch) {
var paths = buildResults.apkPaths.filter(function (p) { const paths = buildResults.apkPaths.filter(function (p) {
var apkName = path.basename(p); const apkName = path.basename(p);
if (buildResults.buildType === 'debug') { if (buildResults.buildType === 'debug') {
return /-debug/.exec(apkName); return /-debug/.exec(apkName);
} }
return !/-debug/.exec(apkName); return !/-debug/.exec(apkName);
}); });
var archPattern = new RegExp('-' + arch); const archPattern = new RegExp('-' + arch);
var hasArchPattern = /-x86|-arm/; const hasArchPattern = /-x86|-arm/;
for (var i = 0; i < paths.length; ++i) { for (let i = 0; i < paths.length; ++i) {
var apkName = path.basename(paths[i]); const apkName = path.basename(paths[i]);
if (hasArchPattern.exec(apkName)) { if (hasArchPattern.exec(apkName)) {
if (archPattern.exec(apkName)) { if (archPattern.exec(apkName)) {
return paths[i]; return paths[i];

View File

@ -17,14 +17,14 @@
under the License. under the License.
*/ */
var fs = require('fs-extra'); const fs = require('fs-extra');
var path = require('path'); const path = require('path');
const execa = require('execa'); const execa = require('execa');
const glob = require('fast-glob'); const glob = require('fast-glob');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
var check_reqs = require('../check_reqs'); const check_reqs = require('../check_reqs');
var PackageType = require('../PackageType'); const PackageType = require('../PackageType');
const { compareByAll } = require('../utils'); const { compareByAll } = require('../utils');
const { createEditor } = require('properties-parser'); const { createEditor } = require('properties-parser');
@ -117,8 +117,8 @@ class ProjectBuilder {
* This returns a promise * This returns a promise
*/ */
runGradleWrapper (gradle_cmd) { runGradleWrapper (gradle_cmd) {
var gradlePath = path.join(this.root, 'gradlew'); const gradlePath = path.join(this.root, 'gradlew');
var wrapperGradle = path.join(this.root, 'wrapper.gradle'); const wrapperGradle = path.join(this.root, 'wrapper.gradle');
if (fs.existsSync(gradlePath)) { if (fs.existsSync(gradlePath)) {
// Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows
} else { } else {
@ -128,15 +128,15 @@ class ProjectBuilder {
readProjectProperties () { readProjectProperties () {
function findAllUniq (data, r) { function findAllUniq (data, r) {
var s = {}; const s = {};
var m; let m;
while ((m = r.exec(data))) { while ((m = r.exec(data))) {
s[m[1]] = 1; s[m[1]] = 1;
} }
return Object.keys(s); return Object.keys(s);
} }
var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8'); const data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');
return { return {
libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg), libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),
gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg), gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),
@ -145,30 +145,30 @@ class ProjectBuilder {
} }
extractRealProjectNameFromManifest () { extractRealProjectNameFromManifest () {
var manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml'); const manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml');
var manifestData = fs.readFileSync(manifestPath, 'utf8'); const manifestData = fs.readFileSync(manifestPath, 'utf8');
var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData); const m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);
if (!m) { if (!m) {
throw new CordovaError('Could not find package name in ' + manifestPath); throw new CordovaError('Could not find package name in ' + manifestPath);
} }
var packageName = m[1]; const packageName = m[1];
var lastDotIndex = packageName.lastIndexOf('.'); const lastDotIndex = packageName.lastIndexOf('.');
return packageName.substring(lastDotIndex + 1); return packageName.substring(lastDotIndex + 1);
} }
// Makes the project buildable, minus the gradle wrapper. // Makes the project buildable, minus the gradle wrapper.
prepBuildFiles () { prepBuildFiles () {
// Update the version of build.gradle in each dependent library. // Update the version of build.gradle in each dependent library.
var pluginBuildGradle = path.join(__dirname, 'plugin-build.gradle'); const pluginBuildGradle = path.join(__dirname, 'plugin-build.gradle');
var propertiesObj = this.readProjectProperties(); const propertiesObj = this.readProjectProperties();
var subProjects = propertiesObj.libs; const subProjects = propertiesObj.libs;
// Check and copy the gradle file into the subproject // Check and copy the gradle file into the subproject
// Called by the loop before this function def // Called by the loop before this function def
var checkAndCopy = function (subProject, root) { const checkAndCopy = function (subProject, root) {
var subProjectGradle = path.join(root, subProject, 'build.gradle'); const subProjectGradle = path.join(root, subProject, 'build.gradle');
// This is the future-proof way of checking if a file exists // This is the future-proof way of checking if a file exists
// This must be synchronous to satisfy a Travis test // This must be synchronous to satisfy a Travis test
try { try {
@ -178,17 +178,17 @@ class ProjectBuilder {
} }
}; };
for (var i = 0; i < subProjects.length; ++i) { for (let i = 0; i < subProjects.length; ++i) {
if (subProjects[i] !== 'CordovaLib') { if (subProjects[i] !== 'CordovaLib') {
checkAndCopy(subProjects[i], this.root); checkAndCopy(subProjects[i], this.root);
} }
} }
var projectName = this.extractRealProjectNameFromManifest(); const projectName = this.extractRealProjectNameFromManifest();
// Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149 // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149
var settingsGradlePaths = subProjects.map(function (p) { const settingsGradlePaths = subProjects.map(function (p) {
var realDir = p.replace(/[/\\]/g, ':'); const realDir = p.replace(/[/\\]/g, ':');
var libName = realDir.replace(projectName + '-', ''); const libName = realDir.replace(projectName + '-', '');
var str = 'include ":' + libName + '"\n'; let str = 'include ":' + libName + '"\n';
if (realDir.indexOf(projectName + '-') !== -1) { if (realDir.indexOf(projectName + '-') !== -1) {
str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n'; str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n';
} }
@ -208,12 +208,12 @@ class ProjectBuilder {
} }
// Update dependencies within build.gradle. // Update dependencies within build.gradle.
var buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8'); let buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8');
var depsList = ''; let depsList = '';
var root = this.root; const root = this.root;
var insertExclude = function (p) { const insertExclude = function (p) {
var gradlePath = path.join(root, p, 'build.gradle'); const gradlePath = path.join(root, p, 'build.gradle');
var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8'); const projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');
if (projectGradleFile.indexOf('CordovaLib') !== -1) { if (projectGradleFile.indexOf('CordovaLib') !== -1) {
depsList += '{\n exclude module:("CordovaLib")\n }\n'; depsList += '{\n exclude module:("CordovaLib")\n }\n';
} else { } else {
@ -222,26 +222,26 @@ class ProjectBuilder {
}; };
subProjects.forEach(function (p) { subProjects.forEach(function (p) {
events.emit('log', 'Subproject Path: ' + p); events.emit('log', 'Subproject Path: ' + p);
var libName = p.replace(/[/\\]/g, ':').replace(projectName + '-', ''); const libName = p.replace(/[/\\]/g, ':').replace(projectName + '-', '');
if (libName !== 'app') { if (libName !== 'app') {
depsList += ' implementation(project(path: ":' + libName + '"))'; depsList += ' implementation(project(path: ":' + libName + '"))';
insertExclude(p); insertExclude(p);
} }
}); });
// For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390 // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390
var SYSTEM_LIBRARY_MAPPINGS = [ const SYSTEM_LIBRARY_MAPPINGS = [
[/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'], [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],
[/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+'] [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']
]; ];
propertiesObj.systemLibs.forEach(function (p) { propertiesObj.systemLibs.forEach(function (p) {
var mavenRef; let mavenRef;
// It's already in gradle form if it has two ':'s // It's already in gradle form if it has two ':'s
if (/:.*:/.exec(p)) { if (/:.*:/.exec(p)) {
mavenRef = p; mavenRef = p;
} else { } else {
for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) { for (let i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {
var pair = SYSTEM_LIBRARY_MAPPINGS[i]; const pair = SYSTEM_LIBRARY_MAPPINGS[i];
if (pair[0].exec(p)) { if (pair[0].exec(p)) {
mavenRef = p.replace(pair[0], pair[1]); mavenRef = p.replace(pair[0], pair[1]);
break; break;
@ -255,7 +255,7 @@ class ProjectBuilder {
}); });
buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2'); buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');
var includeList = ''; let includeList = '';
propertiesObj.gradleIncludes.forEach(function (includePath) { propertiesObj.gradleIncludes.forEach(function (includePath) {
includeList += 'apply from: "../' + includePath + '"\n'; includeList += 'apply from: "../' + includePath + '"\n';
@ -266,7 +266,7 @@ class ProjectBuilder {
} }
prepEnv (opts) { prepEnv (opts) {
var self = this; const self = this;
return check_reqs.check_gradle() return check_reqs.check_gradle()
.then(function (gradlePath) { .then(function (gradlePath) {
return self.runGradleWrapper(gradlePath); return self.runGradleWrapper(gradlePath);
@ -309,8 +309,8 @@ class ProjectBuilder {
* Returns a promise. * Returns a promise.
*/ */
async build (opts) { async build (opts) {
var wrapper = path.join(this.root, 'gradlew'); const wrapper = path.join(this.root, 'gradlew');
var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts); const args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);
try { try {
return await execa(wrapper, args, { stdio: 'inherit', cwd: path.resolve(this.root) }); return await execa(wrapper, args, { stdio: 'inherit', cwd: path.resolve(this.root) });

View File

@ -18,12 +18,12 @@
*/ */
const execa = require('execa'); const execa = require('execa');
var path = require('path'); const path = require('path');
var fs = require('fs-extra'); const fs = require('fs-extra');
const { forgivingWhichSync, isWindows, isDarwin } = require('./utils'); const { forgivingWhichSync, isWindows, isDarwin } = require('./utils');
const java = require('./env/java'); const java = require('./env/java');
const { CordovaError, ConfigParser, events } = require('cordova-common'); const { CordovaError, ConfigParser, events } = require('cordova-common');
var android_sdk = require('./android_sdk'); const android_sdk = require('./android_sdk');
const { SDK_VERSION } = require('./gradle-config-defaults'); const { SDK_VERSION } = require('./gradle-config-defaults');
// Re-exporting these for backwards compatibility and for unit testing. // Re-exporting these for backwards compatibility and for unit testing.
@ -62,18 +62,18 @@ function getUserTargetSdkVersion (projectRoot) {
} }
module.exports.get_gradle_wrapper = function () { module.exports.get_gradle_wrapper = function () {
var androidStudioPath; let androidStudioPath;
var i = 0; let i = 0;
var foundStudio = false; let foundStudio = false;
var program_dir; let 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')); const 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());
if (result.stderr.toString().length > 0) { if (result.stderr.toString().length > 0) {
var androidPath = path.join(process.env.ProgramFiles, 'Android') + '/'; const androidPath = path.join(process.env.ProgramFiles, 'Android') + '/';
if (fs.existsSync(androidPath)) { if (fs.existsSync(androidPath)) {
program_dir = fs.readdirSync(androidPath); program_dir = fs.readdirSync(androidPath);
while (i < program_dir.length && !foundStudio) { while (i < program_dir.length && !foundStudio) {
@ -92,7 +92,7 @@ module.exports.get_gradle_wrapper = function () {
} }
if (androidStudioPath !== null && fs.existsSync(androidStudioPath)) { if (androidStudioPath !== null && fs.existsSync(androidStudioPath)) {
var dirs = fs.readdirSync(androidStudioPath); const dirs = fs.readdirSync(androidStudioPath);
if (dirs[0].split('-')[0] === 'gradle') { if (dirs[0].split('-')[0] === 'gradle') {
return path.join(androidStudioPath, dirs[0], 'bin', 'gradle'); return path.join(androidStudioPath, dirs[0], 'bin', 'gradle');
} }
@ -104,13 +104,13 @@ module.exports.get_gradle_wrapper = function () {
// Returns a promise. Called only by build and clean commands. // Returns a promise. Called only by build and clean commands.
module.exports.check_gradle = function () { module.exports.check_gradle = function () {
var sdkDir = process.env.ANDROID_SDK_ROOT || process.env.ANDROID_HOME; const sdkDir = process.env.ANDROID_SDK_ROOT || process.env.ANDROID_HOME;
if (!sdkDir) { if (!sdkDir) {
return Promise.reject(new CordovaError('Could not find gradle wrapper within Android SDK. Could not find Android SDK directory.\n' + return Promise.reject(new CordovaError('Could not find gradle wrapper within Android SDK. Could not find Android SDK directory.\n' +
'Might need to install Android SDK or set up \'ANDROID_SDK_ROOT\' env variable.')); 'Might need to install Android SDK or set up \'ANDROID_SDK_ROOT\' env variable.'));
} }
var gradlePath = module.exports.get_gradle_wrapper(); const gradlePath = module.exports.get_gradle_wrapper();
if (gradlePath.length !== 0) return Promise.resolve(gradlePath); if (gradlePath.length !== 0) return Promise.resolve(gradlePath);
@ -132,6 +132,8 @@ module.exports.check_java = async function () {
// Returns a promise. // Returns a promise.
module.exports.check_android = function () { module.exports.check_android = function () {
return Promise.resolve().then(function () { return Promise.resolve().then(function () {
let hasAndroidHome = false;
function maybeSetAndroidHome (value) { function maybeSetAndroidHome (value) {
if (!hasAndroidHome && fs.existsSync(value)) { if (!hasAndroidHome && fs.existsSync(value)) {
hasAndroidHome = true; hasAndroidHome = true;
@ -139,9 +141,8 @@ module.exports.check_android = function () {
} }
} }
var adbInPath = forgivingWhichSync('adb'); const adbInPath = forgivingWhichSync('adb');
var avdmanagerInPath = forgivingWhichSync('avdmanager'); const avdmanagerInPath = forgivingWhichSync('avdmanager');
var hasAndroidHome = false;
if (process.env.ANDROID_SDK_ROOT) { if (process.env.ANDROID_SDK_ROOT) {
maybeSetAndroidHome(path.resolve(process.env.ANDROID_SDK_ROOT)); maybeSetAndroidHome(path.resolve(process.env.ANDROID_SDK_ROOT));
@ -198,7 +199,7 @@ module.exports.check_android = function () {
if (!hasAndroidHome) { if (!hasAndroidHome) {
// If we dont have ANDROID_SDK_ROOT, but we do have some tools on the PATH, try to infer from the tooling PATH. // If we dont have ANDROID_SDK_ROOT, but we do have some tools on the PATH, try to infer from the tooling PATH.
var parentDir, grandParentDir; let parentDir, grandParentDir;
if (adbInPath) { if (adbInPath) {
parentDir = path.dirname(adbInPath); parentDir = path.dirname(adbInPath);
grandParentDir = path.dirname(parentDir); grandParentDir = path.dirname(parentDir);
@ -247,7 +248,7 @@ module.exports.check_android_target = function (projectRoot) {
// android-L // android-L
// Google Inc.:Google APIs:20 // Google Inc.:Google APIs:20
// Google Inc.:Glass Development Kit Preview:20 // Google Inc.:Glass Development Kit Preview:20
var desired_api_level = module.exports.get_target(projectRoot); const desired_api_level = module.exports.get_target(projectRoot);
return android_sdk.list_targets().then(function (targets) { return android_sdk.list_targets().then(function (targets) {
if (targets.indexOf(desired_api_level) >= 0) { if (targets.indexOf(desired_api_level) >= 0) {
return targets; return targets;
@ -279,7 +280,7 @@ module.exports.run = function () {
* (for example, check_android_target returns an array of android targets installed) * (for example, check_android_target returns an array of android targets installed)
* @param {Boolean} installed Indicates whether the requirement is installed or not * @param {Boolean} installed Indicates whether the requirement is installed or not
*/ */
var Requirement = function (id, name, version, installed) { const Requirement = function (id, name, version, installed) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.installed = installed || false; this.installed = installed || false;
@ -296,14 +297,14 @@ 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 (projectRoot) { module.exports.check_all = function (projectRoot) {
var requirements = [ const requirements = [
new Requirement('java', 'Java JDK'), new Requirement('java', 'Java JDK'),
new Requirement('androidSdk', 'Android SDK'), new Requirement('androidSdk', 'Android SDK'),
new Requirement('androidTarget', 'Android target'), new Requirement('androidTarget', 'Android target'),
new Requirement('gradle', 'Gradle') new Requirement('gradle', 'Gradle')
]; ];
var checkFns = [ const checkFns = [
this.check_java, this.check_java,
this.check_android, this.check_android,
this.check_android_target.bind(this, projectRoot), this.check_android_target.bind(this, projectRoot),
@ -313,7 +314,7 @@ module.exports.check_all = function (projectRoot) {
// Then execute requirement checks one-by-one // Then execute requirement checks one-by-one
return checkFns.reduce(function (promise, checkFn, idx) { return checkFns.reduce(function (promise, checkFn, idx) {
// Update each requirement with results // Update each requirement with results
var requirement = requirements[idx]; const requirement = requirements[idx];
return promise.then(checkFn).then(function (version) { return promise.then(checkFn).then(function (version) {
requirement.installed = true; requirement.installed = true;
requirement.metadata.version = version; requirement.metadata.version = version;

View File

@ -17,15 +17,15 @@
under the License. under the License.
*/ */
var path = require('path'); const path = require('path');
var fs = require('fs-extra'); const fs = require('fs-extra');
var utils = require('./utils'); const utils = require('./utils');
var check_reqs = require('./check_reqs'); const check_reqs = require('./check_reqs');
var ROOT = path.join(__dirname, '..'); const ROOT = path.join(__dirname, '..');
const { createEditor } = require('properties-parser'); const { createEditor } = require('properties-parser');
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
var AndroidManifest = require('./AndroidManifest'); const AndroidManifest = require('./AndroidManifest');
// Export all helper functions, and make sure internally within this module, we // Export all helper functions, and make sure internally within this module, we
// reference these methods via the `exports` object - this helps with testing // reference these methods via the `exports` object - this helps with testing
@ -43,9 +43,9 @@ function getFrameworkDir (projectPath, shared) {
} }
function copyJsAndLibrary (projectPath, shared, projectName, targetAPI) { function copyJsAndLibrary (projectPath, shared, projectName, targetAPI) {
var nestedCordovaLibPath = getFrameworkDir(projectPath, false); const nestedCordovaLibPath = getFrameworkDir(projectPath, false);
var srcCordovaJsPath = path.join(ROOT, 'templates', 'project', 'assets', 'www', 'cordova.js'); const srcCordovaJsPath = path.join(ROOT, 'templates', 'project', 'assets', 'www', 'cordova.js');
var app_path = path.join(projectPath, 'app', 'src', 'main'); const app_path = path.join(projectPath, 'app', 'src', 'main');
const platform_www = path.join(projectPath, 'platform_www'); const platform_www = path.join(projectPath, 'platform_www');
fs.copySync(srcCordovaJsPath, path.join(app_path, 'assets', 'www', 'cordova.js')); fs.copySync(srcCordovaJsPath, path.join(app_path, 'assets', 'www', 'cordova.js'));
@ -56,7 +56,7 @@ function copyJsAndLibrary (projectPath, shared, projectName, targetAPI) {
fs.copySync(srcCordovaJsPath, path.join(platform_www, 'cordova.js')); fs.copySync(srcCordovaJsPath, path.join(platform_www, 'cordova.js'));
if (shared) { if (shared) {
var relativeFrameworkPath = path.relative(projectPath, getFrameworkDir(projectPath, true)); const relativeFrameworkPath = path.relative(projectPath, getFrameworkDir(projectPath, true));
fs.symlinkSync(relativeFrameworkPath, nestedCordovaLibPath, 'dir'); fs.symlinkSync(relativeFrameworkPath, nestedCordovaLibPath, 'dir');
} else { } else {
fs.ensureDirSync(nestedCordovaLibPath); fs.ensureDirSync(nestedCordovaLibPath);
@ -73,9 +73,9 @@ function copyJsAndLibrary (projectPath, shared, projectName, targetAPI) {
} }
function extractSubProjectPaths (data) { function extractSubProjectPaths (data) {
var ret = {}; const ret = {};
var r = /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg; const r = /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg;
var m; let m;
while ((m = r.exec(data))) { while ((m = r.exec(data))) {
ret[m[1]] = 1; ret[m[1]] = 1;
} }
@ -83,13 +83,13 @@ function extractSubProjectPaths (data) {
} }
function writeProjectProperties (projectPath, target_api) { function writeProjectProperties (projectPath, target_api) {
var dstPath = path.join(projectPath, 'project.properties'); const dstPath = path.join(projectPath, 'project.properties');
var templatePath = path.join(ROOT, 'templates', 'project', 'project.properties'); const templatePath = path.join(ROOT, 'templates', 'project', 'project.properties');
var srcPath = fs.existsSync(dstPath) ? dstPath : templatePath; const srcPath = fs.existsSync(dstPath) ? dstPath : templatePath;
var data = fs.readFileSync(srcPath, 'utf8'); let data = fs.readFileSync(srcPath, 'utf8');
data = data.replace(/^target=.*/m, 'target=' + target_api); data = data.replace(/^target=.*/m, 'target=' + target_api);
var subProjects = extractSubProjectPaths(data); let subProjects = extractSubProjectPaths(data);
subProjects = subProjects.filter(function (p) { subProjects = subProjects.filter(function (p) {
return !(/^CordovaLib$/m.exec(p) || return !(/^CordovaLib$/m.exec(p) ||
/[\\/]cordova-android[\\/]framework$/m.exec(p) || /[\\/]cordova-android[\\/]framework$/m.exec(p) ||
@ -100,7 +100,7 @@ function writeProjectProperties (projectPath, target_api) {
if (!/\n$/.exec(data)) { if (!/\n$/.exec(data)) {
data += '\n'; data += '\n';
} }
for (var i = 0; i < subProjects.length; ++i) { for (let i = 0; i < subProjects.length; ++i) {
data += 'android.library.reference.' + (i + 1) + '=' + subProjects[i] + '\n'; data += 'android.library.reference.' + (i + 1) + '=' + subProjects[i] + '\n';
} }
fs.writeFileSync(dstPath, data); fs.writeFileSync(dstPath, data);
@ -108,12 +108,12 @@ function writeProjectProperties (projectPath, target_api) {
// This makes no sense, what if you're building with a different build system? // This makes no sense, what if you're building with a different build system?
function prepBuildFiles (projectPath) { function prepBuildFiles (projectPath) {
var buildModule = require('./builders/builders'); const buildModule = require('./builders/builders');
buildModule.getBuilder(projectPath).prepBuildFiles(); buildModule.getBuilder(projectPath).prepBuildFiles();
} }
function copyBuildRules (projectPath, isLegacy) { function copyBuildRules (projectPath, isLegacy) {
var srcDir = path.join(ROOT, 'templates', 'project'); const srcDir = path.join(ROOT, 'templates', 'project');
if (isLegacy) { if (isLegacy) {
// The project's build.gradle is identical to the earlier build.gradle, so it should still work // The project's build.gradle is identical to the earlier build.gradle, so it should still work
@ -129,8 +129,8 @@ function copyBuildRules (projectPath, isLegacy) {
} }
function copyScripts (projectPath) { function copyScripts (projectPath) {
var srcScriptsDir = path.join(ROOT, 'templates', 'cordova'); const srcScriptsDir = path.join(ROOT, 'templates', 'cordova');
var destScriptsDir = path.join(projectPath, 'cordova'); const destScriptsDir = path.join(projectPath, 'cordova');
// Delete old scripts directory if this is an update. // Delete old scripts directory if this is an update.
fs.removeSync(destScriptsDir); fs.removeSync(destScriptsDir);
// Copy in the new ones. // Copy in the new ones.
@ -146,7 +146,7 @@ function validatePackageName (package_name) {
// Make the package conform to Java package types // Make the package conform to Java package types
// http://developer.android.com/guide/topics/manifest/manifest-element.html#package // http://developer.android.com/guide/topics/manifest/manifest-element.html#package
// Enforce underscore limitation // Enforce underscore limitation
var msg = 'Error validating package name. '; const msg = 'Error validating package name. ';
if (!/^[a-zA-Z][a-zA-Z0-9_]+(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.test(package_name)) { if (!/^[a-zA-Z][a-zA-Z0-9_]+(\.[a-zA-Z][a-zA-Z0-9_]*)+$/.test(package_name)) {
return Promise.reject(new CordovaError(msg + 'Must look like: `com.company.Name`. Currently is: `' + package_name + '`')); return Promise.reject(new CordovaError(msg + 'Must look like: `com.company.Name`. Currently is: `' + package_name + '`'));
@ -166,7 +166,7 @@ function validatePackageName (package_name) {
* otherwise. * otherwise.
*/ */
function validateProjectName (project_name) { function validateProjectName (project_name) {
var msg = 'Error validating project name. '; const msg = 'Error validating project name. ';
// Make sure there's something there // Make sure there's something there
if (project_name === '') { if (project_name === '') {
return Promise.reject(new CordovaError(msg + 'Project name cannot be empty')); return Promise.reject(new CordovaError(msg + 'Project name cannot be empty'));
@ -203,11 +203,11 @@ exports.create = function (project_path, config, options, events) {
return Promise.reject(new CordovaError('Project already exists! Delete and recreate')); return Promise.reject(new CordovaError('Project already exists! Delete and recreate'));
} }
var package_name = config.android_packageName() || config.packageName() || 'io.cordova.helloCordova'; const package_name = config.android_packageName() || config.packageName() || 'io.cordova.helloCordova';
var project_name = config.name() || 'Hello Cordova'; const project_name = config.name() || 'Hello Cordova';
var safe_activity_name = config.android_activityName() || options.activityName || 'MainActivity'; const safe_activity_name = config.android_activityName() || options.activityName || 'MainActivity';
var target_api = check_reqs.get_target(project_path); const target_api = check_reqs.get_target(project_path);
// Make the package conform to Java package types // Make the package conform to Java package types
return exports.validatePackageName(package_name) return exports.validatePackageName(package_name)
@ -224,8 +224,8 @@ exports.create = function (project_path, config, options, events) {
events.emit('verbose', 'Copying android template project to ' + project_path); events.emit('verbose', 'Copying android template project to ' + project_path);
var project_template_dir = options.customTemplate || path.join(ROOT, 'templates', 'project'); const project_template_dir = options.customTemplate || path.join(ROOT, 'templates', 'project');
var app_path = path.join(project_path, 'app', 'src', 'main'); const app_path = path.join(project_path, 'app', 'src', 'main');
// copy project template // copy project template
fs.ensureDirSync(app_path); fs.ensureDirSync(app_path);
@ -240,17 +240,17 @@ exports.create = function (project_path, config, options, events) {
exports.copyJsAndLibrary(project_path, options.link, safe_activity_name, target_api); exports.copyJsAndLibrary(project_path, options.link, safe_activity_name, target_api);
// Set up ther Android Studio paths // Set up ther Android Studio paths
var java_path = path.join(app_path, 'java'); const java_path = path.join(app_path, 'java');
var assets_path = path.join(app_path, 'assets'); const assets_path = path.join(app_path, 'assets');
var resource_path = path.join(app_path, 'res'); const resource_path = path.join(app_path, 'res');
fs.ensureDirSync(java_path); fs.ensureDirSync(java_path);
fs.ensureDirSync(assets_path); fs.ensureDirSync(assets_path);
fs.ensureDirSync(resource_path); fs.ensureDirSync(resource_path);
// interpolate the activity name and package // interpolate the activity name and package
var packagePath = package_name.replace(/\./g, path.sep); const packagePath = package_name.replace(/\./g, path.sep);
var activity_dir = path.join(java_path, packagePath); const activity_dir = path.join(java_path, packagePath);
var activity_path = path.join(activity_dir, safe_activity_name + '.java'); const activity_path = path.join(activity_dir, safe_activity_name + '.java');
fs.ensureDirSync(activity_dir); fs.ensureDirSync(activity_dir);
fs.copySync(path.join(project_template_dir, 'Activity.java'), activity_path); fs.copySync(path.join(project_template_dir, 'Activity.java'), activity_path);
@ -258,11 +258,11 @@ exports.create = function (project_path, config, options, events) {
utils.replaceFileContents(path.join(app_path, 'res', 'values', 'strings.xml'), /__NAME__/, utils.escape(project_name)); utils.replaceFileContents(path.join(app_path, 'res', 'values', 'strings.xml'), /__NAME__/, utils.escape(project_name));
utils.replaceFileContents(activity_path, /__ID__/, package_name); utils.replaceFileContents(activity_path, /__ID__/, package_name);
var manifest = new AndroidManifest(path.join(project_template_dir, 'AndroidManifest.xml')); const manifest = new AndroidManifest(path.join(project_template_dir, 'AndroidManifest.xml'));
manifest.setPackageId(package_name) manifest.setPackageId(package_name)
.getActivity().setName(safe_activity_name); .getActivity().setName(safe_activity_name);
var manifest_path = path.join(app_path, 'AndroidManifest.xml'); const manifest_path = path.join(app_path, 'AndroidManifest.xml');
manifest.write(manifest_path); manifest.write(manifest_path);
exports.copyScripts(project_path); exports.copyScripts(project_path);
@ -276,8 +276,8 @@ exports.create = function (project_path, config, options, events) {
}; };
function generateDoneMessage (type, link) { function generateDoneMessage (type, link) {
var pkg = require('../package'); const pkg = require('../package');
var msg = 'Android project ' + (type === 'update' ? 'updated ' : 'created ') + 'with ' + pkg.name + '@' + pkg.version; let msg = 'Android project ' + (type === 'update' ? 'updated ' : 'created ') + 'with ' + pkg.name + '@' + pkg.version;
if (link) { if (link) {
msg += ' and has a linked CordovaLib'; msg += ' and has a linked CordovaLib';
} }
@ -286,7 +286,7 @@ function generateDoneMessage (type, link) {
// Returns a promise. // Returns a promise.
exports.update = function (projectPath, options, events) { exports.update = function (projectPath, options, events) {
var errorString = const 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' +
'To update your platform, you have to remove, then add your android platform again.\n' + 'To update your platform, you have to remove, then add your android platform again.\n' +

View File

@ -19,13 +19,13 @@
const execa = require('execa'); const execa = require('execa');
const fs = require('fs-extra'); const fs = require('fs-extra');
var android_versions = require('android-versions'); const android_versions = require('android-versions');
var path = require('path'); const path = require('path');
var Adb = require('./Adb'); const Adb = require('./Adb');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
var android_sdk = require('./android_sdk'); const android_sdk = require('./android_sdk');
var which = require('which'); const which = require('which');
// constants // constants
const ONE_SECOND = 1000; // in milliseconds const ONE_SECOND = 1000; // in milliseconds
@ -41,11 +41,11 @@ function forgivingWhichSync (cmd) {
module.exports.list_images_using_avdmanager = function () { module.exports.list_images_using_avdmanager = function () {
return execa('avdmanager', ['list', 'avd']).then(({ stdout: output }) => { return execa('avdmanager', ['list', 'avd']).then(({ stdout: output }) => {
var response = output.split('\n'); const response = output.split('\n');
var emulator_list = []; const emulator_list = [];
for (var i = 1; i < response.length; i++) { for (let i = 1; i < response.length; i++) {
// To return more detailed information use img_obj // To return more detailed information use img_obj
var img_obj = {}; const img_obj = {};
if (response[i].match(/Name:\s/)) { if (response[i].match(/Name:\s/)) {
img_obj.name = response[i].split('Name: ')[1].replace('\r', ''); img_obj.name = response[i].split('Name: ')[1].replace('\r', '');
if (response[i + 1].match(/Device:\s/)) { if (response[i + 1].match(/Device:\s/)) {
@ -74,9 +74,9 @@ module.exports.list_images_using_avdmanager = function () {
img_obj.target = img_obj.target.substr(0, img_obj.target.indexOf('(') - 1).trim(); img_obj.target = img_obj.target.substr(0, img_obj.target.indexOf('(') - 1).trim();
} }
} }
var version_string = img_obj.target.replace(/Android\s+/, ''); const version_string = img_obj.target.replace(/Android\s+/, '');
var api_level = android_sdk.version_string_to_api_level[version_string]; const api_level = android_sdk.version_string_to_api_level[version_string];
if (api_level) { if (api_level) {
img_obj.target += ' (API level ' + api_level + ')'; img_obj.target += ' (API level ' + api_level + ')';
} }
@ -120,9 +120,9 @@ module.exports.list_images = function () {
// In case we're missing the Android OS version string from the target description, add it. // In case we're missing the Android OS version string from the target description, add it.
return avds.map(function (avd) { return avds.map(function (avd) {
if (avd.target && avd.target.indexOf('Android API') > -1 && avd.target.indexOf('API level') < 0) { if (avd.target && avd.target.indexOf('Android API') > -1 && avd.target.indexOf('API level') < 0) {
var api_level = avd.target.match(/\d+/); const api_level = avd.target.match(/\d+/);
if (api_level) { if (api_level) {
var level = android_versions.get(api_level); const level = android_versions.get(api_level);
if (level) { if (level) {
avd.target = 'Android ' + level.semver + ' (API level ' + api_level + ')'; avd.target = 'Android ' + level.semver + ' (API level ' + api_level + ')';
} }
@ -145,12 +145,12 @@ module.exports.best_image = function (project_target) {
// Just return undefined if there is no images // Just return undefined if there is no images
if (images.length === 0) return; if (images.length === 0) return;
var closest = 9999; let closest = 9999;
var best = images[0]; let best = images[0];
for (var i in images) { for (const i in images) {
var target = images[i].target; const target = images[i].target;
if (target && target.indexOf('API level') > -1) { if (target && target.indexOf('API level') > -1) {
var num = parseInt(target.split('(API level ')[1].replace(')', '')); const num = parseInt(target.split('(API level ')[1].replace(')', ''));
if (num === project_target) { if (num === project_target) {
return images[i]; return images[i];
} else if (project_target - num < closest && project_target > num) { } else if (project_target - num < closest && project_target > num) {
@ -173,10 +173,10 @@ exports.list_started = async () => {
* Returns a promise. * Returns a promise.
*/ */
module.exports.get_available_port = function () { module.exports.get_available_port = function () {
var self = this; const self = this;
return self.list_started().then(function (emulators) { return self.list_started().then(function (emulators) {
for (var p = 5584; p >= 5554; p -= 2) { for (let p = 5584; p >= 5554; p -= 2) {
if (emulators.indexOf('emulator-' + p) === -1) { if (emulators.indexOf('emulator-' + p) === -1) {
events.emit('verbose', 'Found available port: ' + p); events.emit('verbose', 'Found available port: ' + p);
return p; return p;
@ -195,7 +195,7 @@ module.exports.get_available_port = function () {
* Returns a promise. * Returns a promise.
*/ */
module.exports.start = function (emulatorId, boot_timeout) { module.exports.start = function (emulatorId, boot_timeout) {
var self = this; const self = this;
return Promise.resolve().then(function () { return Promise.resolve().then(function () {
if (!emulatorId) { if (!emulatorId) {
@ -205,8 +205,8 @@ module.exports.start = function (emulatorId, boot_timeout) {
return self.get_available_port().then(function (port) { return self.get_available_port().then(function (port) {
// Figure out the directory the emulator binary runs in, and set the cwd to that directory. // Figure out the directory the emulator binary runs in, and set the cwd to that directory.
// Workaround for https://code.google.com/p/android/issues/detail?id=235461 // Workaround for https://code.google.com/p/android/issues/detail?id=235461
var emulator_dir = path.dirname(which.sync('emulator')); const emulator_dir = path.dirname(which.sync('emulator'));
var args = ['-avd', emulatorId, '-port', port]; const args = ['-avd', emulatorId, '-port', port];
// Don't wait for it to finish, since the emulator will probably keep running for a long time. // Don't wait for it to finish, since the emulator will probably keep running for a long time.
execa('emulator', args, { stdio: 'inherit', detached: true, cwd: emulator_dir }) execa('emulator', args, { stdio: 'inherit', detached: true, cwd: emulator_dir })
.unref(); .unref();
@ -241,9 +241,9 @@ module.exports.start = function (emulatorId, boot_timeout) {
* Returns this emulator's ID in a promise. * Returns this emulator's ID in a promise.
*/ */
module.exports.wait_for_emulator = function (port) { module.exports.wait_for_emulator = function (port) {
var self = this; const self = this;
return Promise.resolve().then(function () { return Promise.resolve().then(function () {
var emulator_id = 'emulator-' + port; const emulator_id = 'emulator-' + port;
return Adb.shell(emulator_id, 'getprop dev.bootcomplete').then(function (output) { return Adb.shell(emulator_id, 'getprop dev.bootcomplete').then(function (output) {
if (output.indexOf('1') >= 0) { if (output.indexOf('1') >= 0) {
return emulator_id; return emulator_id;
@ -271,7 +271,7 @@ module.exports.wait_for_emulator = function (port) {
* time_remaining or passing a negative value will cause it to wait forever * time_remaining or passing a negative value will cause it to wait forever
*/ */
module.exports.wait_for_boot = function (emulator_id, time_remaining) { module.exports.wait_for_boot = function (emulator_id, time_remaining) {
var self = this; const self = this;
return Adb.shell(emulator_id, 'getprop sys.boot_completed').then(function (output) { return Adb.shell(emulator_id, 'getprop sys.boot_completed').then(function (output) {
if (output.match(/1/)) { if (output.match(/1/)) {
return true; return true;

2
lib/env/java.js vendored
View File

@ -98,7 +98,7 @@ const java = {
} }
} else { } else {
// See if we can derive it from javac's location. // See if we can derive it from javac's location.
var maybeJavaHome = path.dirname(path.dirname(javacPath)); const maybeJavaHome = path.dirname(path.dirname(javacPath));
if (fs.existsSync(path.join(maybeJavaHome, 'bin', 'java')) || if (fs.existsSync(path.join(maybeJavaHome, 'bin', 'java')) ||
fs.existsSync(path.join(maybeJavaHome, 'bin', 'java.exe'))) { fs.existsSync(path.join(maybeJavaHome, 'bin', 'java.exe'))) {
environment.JAVA_HOME = maybeJavaHome; environment.JAVA_HOME = maybeJavaHome;

View File

@ -14,19 +14,19 @@
* *
*/ */
var fs = require('fs-extra'); const fs = require('fs-extra');
var path = require('path'); const path = require('path');
var isPathInside = require('is-path-inside'); const isPathInside = require('is-path-inside');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
var handlers = { const handlers = {
'source-file': { 'source-file': {
install: function (obj, plugin, project, options) { install: function (obj, plugin, project, options) {
if (!obj.src) throw new CordovaError(generateAttributeError('src', 'source-file', plugin.id)); if (!obj.src) throw new CordovaError(generateAttributeError('src', 'source-file', plugin.id));
if (!obj.targetDir) throw new CordovaError(generateAttributeError('target-dir', 'source-file', plugin.id)); if (!obj.targetDir) throw new CordovaError(generateAttributeError('target-dir', 'source-file', plugin.id));
var dest = getInstallDestination(obj); const dest = getInstallDestination(obj);
if (options && options.force) { if (options && options.force) {
copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link)); copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));
@ -35,7 +35,7 @@ var handlers = {
} }
}, },
uninstall: function (obj, plugin, project, options) { uninstall: function (obj, plugin, project, options) {
var dest = getInstallDestination(obj); const dest = getInstallDestination(obj);
// TODO: Add Koltin extension to uninstall, since they are handled like Java files // TODO: Add Koltin extension to uninstall, since they are handled like Java files
if (obj.src.endsWith('java')) { if (obj.src.endsWith('java')) {
@ -48,35 +48,35 @@ var handlers = {
}, },
'lib-file': { 'lib-file': {
install: function (obj, plugin, project, options) { install: function (obj, plugin, project, options) {
var dest = path.join('app/libs', path.basename(obj.src)); const dest = path.join('app/libs', path.basename(obj.src));
copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link)); copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));
}, },
uninstall: function (obj, plugin, project, options) { uninstall: function (obj, plugin, project, options) {
var dest = path.join('app/libs', path.basename(obj.src)); const dest = path.join('app/libs', path.basename(obj.src));
removeFile(path.resolve(project.projectDir, dest)); removeFile(path.resolve(project.projectDir, dest));
} }
}, },
'resource-file': { 'resource-file': {
install: function (obj, plugin, project, options) { install: function (obj, plugin, project, options) {
var dest = path.join('app', 'src', 'main', obj.target); const dest = path.join('app', 'src', 'main', obj.target);
copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link)); copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));
}, },
uninstall: function (obj, plugin, project, options) { uninstall: function (obj, plugin, project, options) {
var dest = path.join('app', 'src', 'main', obj.target); const dest = path.join('app', 'src', 'main', obj.target);
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; const src = obj.src;
if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id)); if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));
events.emit('verbose', 'Installing Android library: ' + src); events.emit('verbose', 'Installing Android library: ' + src);
var parentDir = obj.parent ? path.resolve(project.projectDir, obj.parent) : project.projectDir; const parentDir = obj.parent ? path.resolve(project.projectDir, obj.parent) : project.projectDir;
var subDir; let subDir;
if (obj.custom) { if (obj.custom) {
var subRelativeDir = project.getCustomSubprojectRelativeDir(plugin.id, src); const subRelativeDir = project.getCustomSubprojectRelativeDir(plugin.id, src);
copyNewFile(plugin.dir, src, project.projectDir, subRelativeDir, !!(options && options.link)); copyNewFile(plugin.dir, src, project.projectDir, subRelativeDir, !!(options && options.link));
subDir = path.resolve(project.projectDir, subRelativeDir); subDir = path.resolve(project.projectDir, subRelativeDir);
} else { } else {
@ -93,19 +93,19 @@ var handlers = {
} }
}, },
uninstall: function (obj, plugin, project, options) { uninstall: function (obj, plugin, project, options) {
var src = obj.src; const src = obj.src;
if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id)); if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));
events.emit('verbose', 'Uninstalling Android library: ' + src); events.emit('verbose', 'Uninstalling Android library: ' + src);
var parentDir = obj.parent ? path.resolve(project.projectDir, obj.parent) : project.projectDir; const parentDir = obj.parent ? path.resolve(project.projectDir, obj.parent) : project.projectDir;
var subDir; let subDir;
if (obj.custom) { if (obj.custom) {
var subRelativeDir = project.getCustomSubprojectRelativeDir(plugin.id, src); const subRelativeDir = project.getCustomSubprojectRelativeDir(plugin.id, src);
removeFile(path.resolve(project.projectDir, subRelativeDir)); removeFile(path.resolve(project.projectDir, subRelativeDir));
subDir = path.resolve(project.projectDir, subRelativeDir); subDir = path.resolve(project.projectDir, subRelativeDir);
// If it's the last framework in the plugin, remove the parent directory. // If it's the last framework in the plugin, remove the parent directory.
var parDir = path.dirname(subDir); const parDir = path.dirname(subDir);
if (fs.existsSync(parDir) && fs.readdirSync(parDir).length === 0) { if (fs.existsSync(parDir) && fs.readdirSync(parDir).length === 0) {
fs.rmdirSync(parDir); fs.rmdirSync(parDir);
} }
@ -139,7 +139,7 @@ var handlers = {
} }
}, },
uninstall: function (obj, plugin, project, options) { uninstall: function (obj, plugin, project, options) {
var target = obj.target || obj.src; const target = obj.target || obj.src;
if (!target) throw new CordovaError(generateAttributeError('target', 'asset', plugin.id)); if (!target) throw new CordovaError(generateAttributeError('target', 'asset', plugin.id));
@ -155,29 +155,29 @@ var handlers = {
'js-module': { 'js-module': {
install: function (obj, plugin, project, options) { install: function (obj, plugin, project, options) {
// Copy the plugin's files into the www directory. // Copy the plugin's files into the www directory.
var moduleSource = path.resolve(plugin.dir, obj.src); const moduleSource = path.resolve(plugin.dir, obj.src);
var moduleName = plugin.id + '.' + (obj.name || path.basename(obj.src, path.extname(obj.src))); const moduleName = plugin.id + '.' + (obj.name || path.basename(obj.src, path.extname(obj.src)));
// Read in the file, prepend the cordova.define, and write it back out. // Read in the file, prepend the cordova.define, and write it back out.
var scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOM let scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOM
if (moduleSource.match(/.*\.json$/)) { if (moduleSource.match(/.*\.json$/)) {
scriptContent = 'module.exports = ' + scriptContent; scriptContent = 'module.exports = ' + scriptContent;
} }
scriptContent = 'cordova.define("' + moduleName + '", function(require, exports, module) {\n' + scriptContent + '\n});\n'; scriptContent = 'cordova.define("' + moduleName + '", function(require, exports, module) {\n' + scriptContent + '\n});\n';
var wwwDest = path.resolve(project.www, 'plugins', plugin.id, obj.src); const wwwDest = path.resolve(project.www, 'plugins', plugin.id, obj.src);
fs.ensureDirSync(path.dirname(wwwDest)); fs.ensureDirSync(path.dirname(wwwDest));
fs.writeFileSync(wwwDest, scriptContent, 'utf-8'); fs.writeFileSync(wwwDest, scriptContent, 'utf-8');
if (options && options.usePlatformWww) { if (options && options.usePlatformWww) {
// CB-11022 copy file to both directories if usePlatformWww is specified // CB-11022 copy file to both directories if usePlatformWww is specified
var platformWwwDest = path.resolve(project.platformWww, 'plugins', plugin.id, obj.src); const platformWwwDest = path.resolve(project.platformWww, 'plugins', plugin.id, obj.src);
fs.ensureDirSync(path.dirname(platformWwwDest)); fs.ensureDirSync(path.dirname(platformWwwDest));
fs.writeFileSync(platformWwwDest, scriptContent, 'utf-8'); fs.writeFileSync(platformWwwDest, scriptContent, 'utf-8');
} }
}, },
uninstall: function (obj, plugin, project, options) { uninstall: function (obj, plugin, project, options) {
var pluginRelativePath = path.join('plugins', plugin.id, obj.src); const pluginRelativePath = path.join('plugins', plugin.id, obj.src);
removeFileAndParents(project.www, pluginRelativePath); removeFileAndParents(project.www, pluginRelativePath);
if (options && options.usePlatformWww) { if (options && options.usePlatformWww) {
// CB-11022 remove file from both directories if usePlatformWww is specified // CB-11022 remove file from both directories if usePlatformWww is specified
@ -208,8 +208,8 @@ function copyFile (plugin_dir, src, project_dir, dest, link) {
if (!fs.existsSync(src)) throw new CordovaError('"' + src + '" not found!'); if (!fs.existsSync(src)) throw new CordovaError('"' + src + '" not found!');
// check that src path is inside plugin directory // check that src path is inside plugin directory
var real_path = fs.realpathSync(src); const real_path = fs.realpathSync(src);
var real_plugin_path = fs.realpathSync(plugin_dir); const real_plugin_path = fs.realpathSync(plugin_dir);
if (!isPathInside(real_path, real_plugin_path)) { throw new CordovaError('File "' + src + '" is located outside the plugin directory "' + plugin_dir + '"'); } if (!isPathInside(real_path, real_plugin_path)) { throw new CordovaError('File "' + src + '" is located outside the plugin directory "' + plugin_dir + '"'); }
dest = path.resolve(project_dir, dest); dest = path.resolve(project_dir, dest);
@ -227,7 +227,7 @@ function copyFile (plugin_dir, src, project_dir, dest, link) {
// Same as copy file but throws error if target exists // Same as copy file but throws error if target exists
function copyNewFile (plugin_dir, src, project_dir, dest, link) { function copyNewFile (plugin_dir, src, project_dir, dest, link) {
var target_path = path.resolve(project_dir, dest); const target_path = path.resolve(project_dir, dest);
if (fs.existsSync(target_path)) { throw new CordovaError('"' + target_path + '" already exists!'); } if (fs.existsSync(target_path)) { throw new CordovaError('"' + target_path + '" already exists!'); }
copyFile(plugin_dir, src, project_dir, dest, !!link); copyFile(plugin_dir, src, project_dir, dest, !!link);
@ -259,13 +259,13 @@ function deleteJava (project_dir, destFile) {
function removeFileAndParents (baseDir, destFile, stopper) { function removeFileAndParents (baseDir, destFile, stopper) {
stopper = stopper || '.'; stopper = stopper || '.';
var file = path.resolve(baseDir, destFile); const file = path.resolve(baseDir, destFile);
if (!fs.existsSync(file)) return; if (!fs.existsSync(file)) return;
removeFile(file); removeFile(file);
// check if directory is empty // check if directory is empty
var curDir = path.dirname(file); let curDir = path.dirname(file);
while (curDir !== path.resolve(baseDir, stopper)) { while (curDir !== path.resolve(baseDir, stopper)) {
if (fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) { if (fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {
@ -283,16 +283,16 @@ function generateAttributeError (attribute, element, id) {
} }
function getInstallDestination (obj) { function getInstallDestination (obj) {
var APP_MAIN_PREFIX = 'app/src/main'; const APP_MAIN_PREFIX = 'app/src/main';
var PATH_SEPARATOR = '/'; const PATH_SEPARATOR = '/';
var PATH_SEP_MATCH = '\\' + PATH_SEPARATOR; const PATH_SEP_MATCH = '\\' + PATH_SEPARATOR;
var PATH_SEP_OR_EOL_MATCH = '(\\' + PATH_SEPARATOR + '|$)'; const PATH_SEP_OR_EOL_MATCH = '(\\' + PATH_SEPARATOR + '|$)';
var appReg = new RegExp('^app' + PATH_SEP_OR_EOL_MATCH); const appReg = new RegExp('^app' + PATH_SEP_OR_EOL_MATCH);
var libsReg = new RegExp('^libs' + PATH_SEP_OR_EOL_MATCH); const libsReg = new RegExp('^libs' + PATH_SEP_OR_EOL_MATCH);
var srcReg = new RegExp('^src' + PATH_SEP_OR_EOL_MATCH); const srcReg = new RegExp('^src' + PATH_SEP_OR_EOL_MATCH);
var srcMainReg = new RegExp('^src' + PATH_SEP_MATCH + 'main' + PATH_SEP_OR_EOL_MATCH); const srcMainReg = new RegExp('^src' + PATH_SEP_MATCH + 'main' + PATH_SEP_OR_EOL_MATCH);
if (appReg.test(obj.targetDir)) { if (appReg.test(obj.targetDir)) {
// If any source file is using the new app directory structure, // If any source file is using the new app directory structure,

View File

@ -17,20 +17,20 @@
under the License. under the License.
*/ */
var fs = require('fs-extra'); const fs = require('fs-extra');
var path = require('path'); const path = require('path');
const nopt = require('nopt'); const nopt = require('nopt');
const glob = require('fast-glob'); const glob = require('fast-glob');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var AndroidManifest = require('./AndroidManifest'); const AndroidManifest = require('./AndroidManifest');
var checkReqs = require('./check_reqs'); const checkReqs = require('./check_reqs');
var xmlHelpers = require('cordova-common').xmlHelpers; const xmlHelpers = require('cordova-common').xmlHelpers;
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
var ConfigParser = require('cordova-common').ConfigParser; const ConfigParser = require('cordova-common').ConfigParser;
var FileUpdater = require('cordova-common').FileUpdater; const FileUpdater = require('cordova-common').FileUpdater;
var PlatformJson = require('cordova-common').PlatformJson; const PlatformJson = require('cordova-common').PlatformJson;
var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger; const PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;
var PluginInfoProvider = require('cordova-common').PluginInfoProvider; const PluginInfoProvider = require('cordova-common').PluginInfoProvider;
const utils = require('./utils'); const utils = require('./utils');
const gradleConfigDefaults = require('./gradle-config-defaults'); const gradleConfigDefaults = require('./gradle-config-defaults');
@ -44,15 +44,15 @@ function parseArguments (argv) {
} }
module.exports.prepare = function (cordovaProject, options) { module.exports.prepare = function (cordovaProject, options) {
var self = this; const self = this;
let args = {}; let args = {};
if (options && options.options) { if (options && options.options) {
args = parseArguments(options.options.argv); args = parseArguments(options.options.argv);
} }
var platformJson = PlatformJson.load(this.locations.root, this.platform); const platformJson = PlatformJson.load(this.locations.root, this.platform);
var munger = new PlatformMunger(this.platform, this.locations.root, platformJson, new PluginInfoProvider()); const munger = new PlatformMunger(this.platform, this.locations.root, platformJson, new PluginInfoProvider());
this._config = updateConfigFilesFrom(cordovaProject.projectConfig, munger, this.locations); this._config = updateConfigFilesFrom(cordovaProject.projectConfig, munger, this.locations);
@ -151,15 +151,15 @@ module.exports.clean = function (options) {
// been called from the platform shell script rather than the CLI. Check for the // been called from the platform shell script rather than the CLI. Check for the
// noPrepare option passed in by the non-CLI clean script. If that's present, or if // noPrepare option passed in by the non-CLI clean script. If that's present, or if
// there's no config.xml found at the project root, then don't clean prepared files. // there's no config.xml found at the project root, then don't clean prepared files.
var projectRoot = path.resolve(this.root, '../..'); const projectRoot = path.resolve(this.root, '../..');
if ((options && options.noPrepare) || !fs.existsSync(this.locations.configXml) || if ((options && options.noPrepare) || !fs.existsSync(this.locations.configXml) ||
!fs.existsSync(this.locations.configXml)) { !fs.existsSync(this.locations.configXml)) {
return Promise.resolve(); return Promise.resolve();
} }
var projectConfig = new ConfigParser(this.locations.configXml); const projectConfig = new ConfigParser(this.locations.configXml);
var self = this; const self = this;
return Promise.resolve().then(function () { return Promise.resolve().then(function () {
cleanWww(projectRoot, self.locations); cleanWww(projectRoot, self.locations);
cleanIcons(projectRoot, projectConfig, path.relative(projectRoot, self.locations.res)); cleanIcons(projectRoot, projectConfig, path.relative(projectRoot, self.locations.res));
@ -195,7 +195,7 @@ function updateConfigFilesFrom (sourceConfig, configMunger, locations) {
events.emit('verbose', 'Merging project\'s config.xml into platform-specific android config.xml'); events.emit('verbose', 'Merging project\'s config.xml into platform-specific android config.xml');
// Merge changes from app's config.xml into platform's one // Merge changes from app's config.xml into platform's one
var config = new ConfigParser(locations.configXml); const config = new ConfigParser(locations.configXml);
xmlHelpers.mergeXml(sourceConfig.doc.getroot(), xmlHelpers.mergeXml(sourceConfig.doc.getroot(),
config.doc.getroot(), 'android', /* clobber= */true); config.doc.getroot(), 'android', /* clobber= */true);
@ -220,19 +220,19 @@ function logFileOp (message) {
* paths for www files. * paths for www files.
*/ */
function updateWww (cordovaProject, destinations) { function updateWww (cordovaProject, destinations) {
var sourceDirs = [ const sourceDirs = [
path.relative(cordovaProject.root, cordovaProject.locations.www), path.relative(cordovaProject.root, cordovaProject.locations.www),
path.relative(cordovaProject.root, destinations.platformWww) path.relative(cordovaProject.root, destinations.platformWww)
]; ];
// If project contains 'merges' for our platform, use them as another overrides // If project contains 'merges' for our platform, use them as another overrides
var merges_path = path.join(cordovaProject.root, 'merges', 'android'); const merges_path = path.join(cordovaProject.root, 'merges', 'android');
if (fs.existsSync(merges_path)) { if (fs.existsSync(merges_path)) {
events.emit('verbose', 'Found "merges/android" folder. Copying its contents into the android project.'); events.emit('verbose', 'Found "merges/android" folder. Copying its contents into the android project.');
sourceDirs.push(path.join('merges', 'android')); sourceDirs.push(path.join('merges', 'android'));
} }
var targetDir = path.relative(cordovaProject.root, destinations.www); const targetDir = path.relative(cordovaProject.root, destinations.www);
events.emit( events.emit(
'verbose', 'Merging and updating files from [' + sourceDirs.join(', ') + '] to ' + targetDir); 'verbose', 'Merging and updating files from [' + sourceDirs.join(', ') + '] to ' + targetDir);
FileUpdater.mergeAndUpdateDir( FileUpdater.mergeAndUpdateDir(
@ -243,7 +243,7 @@ function updateWww (cordovaProject, destinations) {
* Cleans all files from the platform 'www' directory. * Cleans all files from the platform 'www' directory.
*/ */
function cleanWww (projectRoot, locations) { function cleanWww (projectRoot, locations) {
var targetDir = path.relative(projectRoot, locations.www); const targetDir = path.relative(projectRoot, locations.www);
events.emit('verbose', 'Cleaning ' + targetDir); events.emit('verbose', 'Cleaning ' + targetDir);
// No source paths are specified, so mergeAndUpdateDir() will clear the target directory. // No source paths are specified, so mergeAndUpdateDir() will clear the target directory.
@ -260,12 +260,12 @@ function cleanWww (projectRoot, locations) {
*/ */
function updateProjectAccordingTo (platformConfig, locations) { function updateProjectAccordingTo (platformConfig, locations) {
// Update app name by editing res/values/strings.xml // Update app name by editing res/values/strings.xml
var strings = xmlHelpers.parseElementtreeSync(locations.strings); const strings = xmlHelpers.parseElementtreeSync(locations.strings);
var name = platformConfig.name(); const name = platformConfig.name();
strings.find('string[@name="app_name"]').text = name.replace(/'/g, '\\\''); strings.find('string[@name="app_name"]').text = name.replace(/'/g, '\\\'');
var shortName = platformConfig.shortName && platformConfig.shortName(); const shortName = platformConfig.shortName && platformConfig.shortName();
if (shortName && shortName !== name) { if (shortName && shortName !== name) {
strings.find('string[@name="launcher_name"]').text = shortName.replace(/'/g, '\\\''); strings.find('string[@name="launcher_name"]').text = shortName.replace(/'/g, '\\\'');
} }
@ -279,10 +279,10 @@ function updateProjectAccordingTo (platformConfig, locations) {
'rootProject.name = "' + name.replace(/[/\\:<>"?*|]/g, '_') + '"\n'); 'rootProject.name = "' + name.replace(/[/\\:<>"?*|]/g, '_') + '"\n');
// Java packages cannot support dashes // Java packages cannot support dashes
var androidPkgName = (platformConfig.android_packageName() || platformConfig.packageName()).replace(/-/g, '_'); const androidPkgName = (platformConfig.android_packageName() || platformConfig.packageName()).replace(/-/g, '_');
var manifest = new AndroidManifest(locations.manifest); const manifest = new AndroidManifest(locations.manifest);
var manifestId = manifest.getPackageId(); const manifestId = manifest.getPackageId();
manifest.getActivity() manifest.getActivity()
.setOrientation(platformConfig.getPreference('orientation')) .setOrientation(platformConfig.getPreference('orientation'))
@ -317,7 +317,7 @@ 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() const removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin()
? manifestId.toUpperCase() !== androidPkgName.toUpperCase() ? manifestId.toUpperCase() !== androidPkgName.toUpperCase()
: manifestId !== androidPkgName; : manifestId !== androidPkgName;
@ -325,8 +325,8 @@ function updateProjectAccordingTo (platformConfig, locations) {
// 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
fs.removeSync(java_files[0]); fs.removeSync(java_files[0]);
// remove any empty directories // remove any empty directories
var currentDir = path.dirname(java_files[0]); let currentDir = path.dirname(java_files[0]);
var sourcesRoot = path.resolve(locations.root, 'src'); const sourcesRoot = path.resolve(locations.root, 'src');
while (currentDir !== sourcesRoot) { while (currentDir !== sourcesRoot) {
if (fs.existsSync(currentDir) && fs.readdirSync(currentDir).length === 0) { if (fs.existsSync(currentDir) && fs.readdirSync(currentDir).length === 0) {
fs.rmdirSync(currentDir); fs.rmdirSync(currentDir);
@ -342,8 +342,8 @@ function updateProjectAccordingTo (platformConfig, locations) {
// PATCH + MINOR * 100 + MAJOR * 10000 // PATCH + MINOR * 100 + MAJOR * 10000
// see http://developer.android.com/tools/publishing/versioning.html // see http://developer.android.com/tools/publishing/versioning.html
function default_versionCode (version) { function default_versionCode (version) {
var nums = version.split('-')[0].split('.'); const nums = version.split('-')[0].split('.');
var versionCode = 0; let versionCode = 0;
if (+nums[0]) { if (+nums[0]) {
versionCode += +nums[0] * 10000; versionCode += +nums[0] * 10000;
} }
@ -361,7 +361,8 @@ function default_versionCode (version) {
function getImageResourcePath (resourcesDir, type, density, name, sourceName) { function getImageResourcePath (resourcesDir, type, density, name, sourceName) {
// Use same extension as source with special case for 9-Patch files // Use same extension as source with special case for 9-Patch files
const ext = sourceName.endsWith('.9.png') const ext = sourceName.endsWith('.9.png')
? '.9.png' : path.extname(sourceName).toLowerCase(); ? '.9.png'
: path.extname(sourceName).toLowerCase();
const subDir = density ? `${type}-${density}` : type; const subDir = density ? `${type}-${density}` : type;
return path.join(resourcesDir, subDir, name + ext); return path.join(resourcesDir, subDir, name + ext);
@ -371,7 +372,7 @@ function getAdaptiveImageResourcePath (resourcesDir, type, density, name, source
if (/\.9\.png$/.test(sourceName)) { if (/\.9\.png$/.test(sourceName)) {
name = name.replace(/\.png$/, '.9.png'); name = name.replace(/\.png$/, '.9.png');
} }
var resourcePath = path.join(resourcesDir, (density ? type + '-' + density + '-v26' : type), name); const resourcePath = path.join(resourcesDir, (density ? type + '-' + density + '-v26' : type), name);
return resourcePath; return resourcePath;
} }
@ -385,7 +386,7 @@ function makeSplashCleanupMap (projectRoot, resourcesDir) {
} }
function updateSplashes (cordovaProject, platformResourcesDir) { function updateSplashes (cordovaProject, platformResourcesDir) {
var resources = cordovaProject.projectConfig.getSplashScreens('android'); const resources = cordovaProject.projectConfig.getSplashScreens('android');
// if there are no "splash" elements in config.xml // if there are no "splash" elements in config.xml
if (resources.length === 0) { if (resources.length === 0) {
@ -399,7 +400,7 @@ function updateSplashes (cordovaProject, platformResourcesDir) {
// Build an initial resource map that deletes all existing splash screens // Build an initial resource map that deletes all existing splash screens
const resourceMap = makeSplashCleanupMap(cordovaProject.root, platformResourcesDir); const resourceMap = makeSplashCleanupMap(cordovaProject.root, platformResourcesDir);
var hadMdpi = false; let hadMdpi = false;
resources.forEach(function (resource) { resources.forEach(function (resource) {
if (!resource.density) { if (!resource.density) {
return; return;
@ -407,14 +408,14 @@ function updateSplashes (cordovaProject, platformResourcesDir) {
if (resource.density === 'mdpi') { if (resource.density === 'mdpi') {
hadMdpi = true; hadMdpi = true;
} }
var targetPath = getImageResourcePath( const targetPath = getImageResourcePath(
platformResourcesDir, 'drawable', resource.density, 'screen', path.basename(resource.src)); platformResourcesDir, 'drawable', resource.density, 'screen', path.basename(resource.src));
resourceMap[targetPath] = resource.src; resourceMap[targetPath] = resource.src;
}); });
// There's no "default" drawable, so assume default == mdpi. // There's no "default" drawable, so assume default == mdpi.
if (!hadMdpi && resources.defaultResource) { if (!hadMdpi && resources.defaultResource) {
var targetPath = getImageResourcePath( const targetPath = getImageResourcePath(
platformResourcesDir, 'drawable', 'mdpi', 'screen', path.basename(resources.defaultResource.src)); platformResourcesDir, 'drawable', 'mdpi', 'screen', path.basename(resources.defaultResource.src));
resourceMap[targetPath] = resources.defaultResource.src; resourceMap[targetPath] = resources.defaultResource.src;
} }
@ -425,7 +426,7 @@ function updateSplashes (cordovaProject, platformResourcesDir) {
} }
function cleanSplashes (projectRoot, projectConfig, platformResourcesDir) { function cleanSplashes (projectRoot, projectConfig, platformResourcesDir) {
var resources = projectConfig.getSplashScreens('android'); const resources = projectConfig.getSplashScreens('android');
if (resources.length > 0) { if (resources.length > 0) {
const resourceMap = makeSplashCleanupMap(projectRoot, platformResourcesDir); const resourceMap = makeSplashCleanupMap(projectRoot, platformResourcesDir);
@ -617,14 +618,14 @@ function updateIconResourceForLegacy (preparedIcons, resourceMap, platformResour
// 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.
for (var density in android_icons) { for (const density in android_icons) {
var targetPath = getImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher', path.basename(android_icons[density].src)); const targetPath = getImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher', path.basename(android_icons[density].src));
resourceMap[targetPath] = android_icons[density].src; resourceMap[targetPath] = android_icons[density].src;
} }
// There's no "default" drawable, so assume default == mdpi. // There's no "default" drawable, so assume default == mdpi.
if (default_icon && !android_icons.mdpi) { if (default_icon && !android_icons.mdpi) {
var defaultTargetPath = getImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher', path.basename(default_icon.src)); const defaultTargetPath = getImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher', path.basename(default_icon.src));
resourceMap[defaultTargetPath] = default_icon.src; resourceMap[defaultTargetPath] = default_icon.src;
} }
@ -647,14 +648,14 @@ function prepareIcons (icons) {
// find the best matching icon for a given density or size // find the best matching icon for a given density or size
// @output android_icons // @output android_icons
var parseIcon = function (icon, icon_size) { const parseIcon = function (icon, icon_size) {
// do I have a platform icon for that density already // do I have a platform icon for that density already
var density = icon.density || SIZE_TO_DENSITY_MAP[icon_size]; const density = icon.density || SIZE_TO_DENSITY_MAP[icon_size];
if (!density) { if (!density) {
// invalid icon defition ( or unsupported size) // invalid icon defition ( or unsupported size)
return; return;
} }
var previous = android_icons[density]; const previous = android_icons[density];
if (previous && previous.platform) { if (previous && previous.platform) {
return; return;
} }
@ -662,9 +663,9 @@ function prepareIcons (icons) {
}; };
// iterate over all icon elements to find the default icon and call parseIcon // iterate over all icon elements to find the default icon and call parseIcon
for (var i = 0; i < icons.length; i++) { for (let i = 0; i < icons.length; i++) {
var icon = icons[i]; const icon = icons[i];
var size = icon.width; let size = icon.width;
if (!size) { if (!size) {
size = icon.height; size = icon.height;
@ -708,7 +709,7 @@ function prepareIcons (icons) {
} }
function cleanIcons (projectRoot, projectConfig, platformResourcesDir) { function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {
var icons = projectConfig.getIcons('android'); const icons = 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) {
@ -756,7 +757,7 @@ function makeCleanResourceMap (resourcePaths) {
} }
function updateFileResources (cordovaProject, platformDir) { function updateFileResources (cordovaProject, platformDir) {
var files = cordovaProject.projectConfig.getFileResources('android'); const files = cordovaProject.projectConfig.getFileResources('android');
// if there are resource-file elements in config.xml // if there are resource-file elements in config.xml
if (files.length === 0) { if (files.length === 0) {
@ -764,9 +765,9 @@ function updateFileResources (cordovaProject, platformDir) {
return; return;
} }
var resourceMap = {}; const resourceMap = {};
files.forEach(function (res) { files.forEach(function (res) {
var targetPath = path.join(platformDir, res.target); const targetPath = path.join(platformDir, res.target);
resourceMap[targetPath] = res.src; resourceMap[targetPath] = res.src;
}); });
@ -776,13 +777,13 @@ function updateFileResources (cordovaProject, platformDir) {
} }
function cleanFileResources (projectRoot, projectConfig, platformDir) { function cleanFileResources (projectRoot, projectConfig, platformDir) {
var files = projectConfig.getFileResources('android', true); const files = projectConfig.getFileResources('android', true);
if (files.length > 0) { if (files.length > 0) {
events.emit('verbose', 'Cleaning resource files at ' + platformDir); events.emit('verbose', 'Cleaning resource files at ' + platformDir);
var resourceMap = {}; const resourceMap = {};
files.forEach(function (res) { files.forEach(function (res) {
var filePath = path.join(platformDir, res.target); const filePath = path.join(platformDir, res.target);
resourceMap[filePath] = null; resourceMap[filePath] = null;
}); });
@ -803,14 +804,14 @@ function cleanFileResources (projectRoot, projectConfig, platformDir) {
* 'singleTop' * 'singleTop'
*/ */
function findAndroidLaunchModePreference (platformConfig) { function findAndroidLaunchModePreference (platformConfig) {
var launchMode = platformConfig.getPreference('AndroidLaunchMode'); const launchMode = platformConfig.getPreference('AndroidLaunchMode');
if (!launchMode) { if (!launchMode) {
// Return a default value // Return a default value
return 'singleTop'; return 'singleTop';
} }
var expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance']; const expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance'];
var valid = expectedValues.indexOf(launchMode) >= 0; const valid = expectedValues.indexOf(launchMode) >= 0;
if (!valid) { if (!valid) {
// Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future // Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future
events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' + events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' +

View File

@ -19,7 +19,7 @@
'use strict'; 'use strict';
var events = require('cordova-common').events; const events = require('cordova-common').events;
/** /**
* Retry a promise-returning function a number of times, propagating its * Retry a promise-returning function a number of times, propagating its

View File

@ -17,7 +17,7 @@
under the License. under the License.
*/ */
var emulator = require('./emulator'); const emulator = require('./emulator');
const target = require('./target'); const target = require('./target');
const build = require('./build'); const build = require('./build');
const PackageType = require('./PackageType'); const PackageType = require('./PackageType');

2881
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -36,7 +36,7 @@
"which": "^2.0.2" "which": "^2.0.2"
}, },
"devDependencies": { "devDependencies": {
"@cordova/eslint-config": "^3.0.0", "@cordova/eslint-config": "^4.0.0",
"cordova-js": "^6.1.0", "cordova-js": "^6.1.0",
"jasmine": "^4.1.0", "jasmine": "^4.1.0",
"jasmine-spec-reporter": "^7.0.0", "jasmine-spec-reporter": "^7.0.0",

View File

@ -17,29 +17,29 @@
under the License. under the License.
*/ */
var os = require('os'); const os = require('os');
var path = require('path'); const path = require('path');
var common = require('cordova-common'); const common = require('cordova-common');
const EventEmitter = require('events'); const EventEmitter = require('events');
var Api = require('../../lib/Api'); const Api = require('../../lib/Api');
var AndroidProject = require('../../lib/AndroidProject'); const AndroidProject = require('../../lib/AndroidProject');
var PluginInfo = common.PluginInfo; const PluginInfo = common.PluginInfo;
var FIXTURES = path.join(__dirname, '../e2e/fixtures'); const FIXTURES = path.join(__dirname, '../e2e/fixtures');
var FAKE_PROJECT_DIR = path.join(os.tmpdir(), 'plugin-test-project'); const FAKE_PROJECT_DIR = path.join(os.tmpdir(), 'plugin-test-project');
describe('Api', () => { describe('Api', () => {
describe('addPlugin method', function () { describe('addPlugin method', function () {
var api; let api;
beforeEach(function () { beforeEach(function () {
var pluginManager = jasmine.createSpyObj('pluginManager', ['addPlugin']); const pluginManager = jasmine.createSpyObj('pluginManager', ['addPlugin']);
pluginManager.addPlugin.and.resolveTo(); pluginManager.addPlugin.and.resolveTo();
spyOn(common.PluginManager, 'get').and.returnValue(pluginManager); spyOn(common.PluginManager, 'get').and.returnValue(pluginManager);
var projectSpy = jasmine.createSpyObj('AndroidProject', ['getPackageName', 'write', 'isClean']); const projectSpy = jasmine.createSpyObj('AndroidProject', ['getPackageName', 'write', 'isClean']);
spyOn(AndroidProject, 'getProjectFile').and.returnValue(projectSpy); spyOn(AndroidProject, 'getProjectFile').and.returnValue(projectSpy);
api = new Api('android', FAKE_PROJECT_DIR, new EventEmitter()); api = new Api('android', FAKE_PROJECT_DIR, new EventEmitter());

View File

@ -17,12 +17,12 @@
under the License. under the License.
*/ */
var rewire = require('rewire'); const rewire = require('rewire');
var android_sdk = require('../../lib/android_sdk'); const android_sdk = require('../../lib/android_sdk');
var fs = require('fs-extra'); const fs = require('fs-extra');
var path = require('path'); const path = require('path');
var events = require('cordova-common').events; const events = require('cordova-common').events;
var which = require('which'); const which = require('which');
const { const {
SDK_VERSION: DEFAULT_TARGET_API SDK_VERSION: DEFAULT_TARGET_API
@ -34,7 +34,7 @@ describe('check_reqs', function () {
check_reqs = rewire('../../lib/check_reqs'); check_reqs = rewire('../../lib/check_reqs');
}); });
var original_env; let original_env;
beforeAll(function () { beforeAll(function () {
original_env = Object.assign({}, process.env); original_env = Object.assign({}, process.env);
}); });
@ -263,8 +263,8 @@ describe('check_reqs', function () {
describe('get_target', function () { describe('get_target', function () {
const projectRoot = 'fakeProjectRoot'; const projectRoot = 'fakeProjectRoot';
var ConfigParser; let ConfigParser;
var getPreferenceSpy; let getPreferenceSpy;
beforeEach(function () { beforeEach(function () {
getPreferenceSpy = jasmine.createSpy(); getPreferenceSpy = jasmine.createSpy();
ConfigParser = jasmine.createSpy().and.returnValue({ ConfigParser = jasmine.createSpy().and.returnValue({
@ -274,7 +274,7 @@ describe('check_reqs', function () {
}); });
it('should retrieve DEFAULT_TARGET_API', function () { it('should retrieve DEFAULT_TARGET_API', function () {
var target = check_reqs.get_target(projectRoot); const target = check_reqs.get_target(projectRoot);
expect(target).toBeDefined(); expect(target).toBeDefined();
expect(target).toContain('android-' + DEFAULT_TARGET_API); expect(target).toContain('android-' + DEFAULT_TARGET_API);
}); });
@ -283,7 +283,7 @@ describe('check_reqs', function () {
spyOn(fs, 'existsSync').and.returnValue(true); spyOn(fs, 'existsSync').and.returnValue(true);
getPreferenceSpy.and.returnValue(String(DEFAULT_TARGET_API + 1)); getPreferenceSpy.and.returnValue(String(DEFAULT_TARGET_API + 1));
var target = check_reqs.get_target(projectRoot); const target = check_reqs.get_target(projectRoot);
expect(getPreferenceSpy).toHaveBeenCalledWith('android-targetSdkVersion', 'android'); expect(getPreferenceSpy).toHaveBeenCalledWith('android-targetSdkVersion', 'android');
expect(target).toBe('android-' + (DEFAULT_TARGET_API + 1)); expect(target).toBe('android-' + (DEFAULT_TARGET_API + 1));
@ -293,7 +293,7 @@ describe('check_reqs', function () {
spyOn(fs, 'existsSync').and.returnValue(true); spyOn(fs, 'existsSync').and.returnValue(true);
getPreferenceSpy.and.returnValue('android-99'); getPreferenceSpy.and.returnValue('android-99');
var target = check_reqs.get_target(projectRoot); const target = check_reqs.get_target(projectRoot);
expect(getPreferenceSpy).toHaveBeenCalledWith('android-targetSdkVersion', 'android'); expect(getPreferenceSpy).toHaveBeenCalledWith('android-targetSdkVersion', 'android');
expect(target).toBe('android-' + DEFAULT_TARGET_API); expect(target).toBe('android-' + DEFAULT_TARGET_API);
@ -306,7 +306,7 @@ describe('check_reqs', function () {
getPreferenceSpy.and.returnValue(String(DEFAULT_TARGET_API - 1)); getPreferenceSpy.and.returnValue(String(DEFAULT_TARGET_API - 1));
var target = check_reqs.get_target(projectRoot); const target = check_reqs.get_target(projectRoot);
expect(getPreferenceSpy).toHaveBeenCalledWith('android-targetSdkVersion', 'android'); expect(getPreferenceSpy).toHaveBeenCalledWith('android-targetSdkVersion', 'android');
expect(target).toBe('android-' + DEFAULT_TARGET_API); expect(target).toBe('android-' + DEFAULT_TARGET_API);
@ -316,7 +316,7 @@ describe('check_reqs', function () {
describe('check_android_target', function () { describe('check_android_target', function () {
it('should should return full list of supported targets if there is a match to ideal api level', () => { it('should should return full list of supported targets if there is a match to ideal api level', () => {
var fake_targets = ['you are my fire', 'my one desire']; const fake_targets = ['you are my fire', 'my one desire'];
spyOn(android_sdk, 'list_targets').and.resolveTo(fake_targets); spyOn(android_sdk, 'list_targets').and.resolveTo(fake_targets);
spyOn(check_reqs, 'get_target').and.returnValue('you are my fire'); spyOn(check_reqs, 'get_target').and.returnValue('you are my fire');
return check_reqs.check_android_target().then(function (targets) { return check_reqs.check_android_target().then(function (targets) {
@ -325,7 +325,7 @@ describe('check_reqs', function () {
}); });
}); });
it('should error out if there is no match between ideal api level and installed targets', () => { it('should error out if there is no match between ideal api level and installed targets', () => {
var fake_targets = ['you are my fire', 'my one desire']; const fake_targets = ['you are my fire', 'my one desire'];
spyOn(android_sdk, 'list_targets').and.resolveTo(fake_targets); spyOn(android_sdk, 'list_targets').and.resolveTo(fake_targets);
spyOn(check_reqs, 'get_target').and.returnValue('and i knowwwwwwwwwwww'); spyOn(check_reqs, 'get_target').and.returnValue('and i knowwwwwwwwwwww');
return check_reqs.check_android_target().then(() => { return check_reqs.check_android_target().then(() => {

View File

@ -17,17 +17,17 @@
under the License. under the License.
*/ */
var rewire = require('rewire'); const rewire = require('rewire');
var utils = require('../../lib/utils'); const utils = require('../../lib/utils');
var create = rewire('../../lib/create'); const create = rewire('../../lib/create');
var check_reqs = require('../../lib/check_reqs'); const check_reqs = require('../../lib/check_reqs');
var fs = require('fs-extra'); const fs = require('fs-extra');
var path = require('path'); const path = require('path');
describe('create', function () { describe('create', function () {
describe('validatePackageName helper method', function () { describe('validatePackageName helper method', function () {
describe('happy path (valid package names)', function () { describe('happy path (valid package names)', function () {
var valid = [ const valid = [
'org.apache.mobilespec', 'org.apache.mobilespec',
'com.example', 'com.example',
'com.floors42.package', 'com.floors42.package',
@ -82,7 +82,7 @@ describe('create', function () {
describe('validateProjectName helper method', function () { describe('validateProjectName helper method', function () {
describe('happy path (valid project names)', function () { describe('happy path (valid project names)', function () {
var valid = [ const valid = [
'mobilespec', 'mobilespec',
'package_name', 'package_name',
'PackageName', 'PackageName',
@ -111,14 +111,14 @@ describe('create', function () {
}); });
describe('main method', function () { describe('main method', function () {
var config_mock; let config_mock;
var events_mock; let events_mock;
var Manifest_mock = function () {}; const Manifest_mock = function () {};
var revert_manifest_mock; let revert_manifest_mock;
var project_path = path.join('some', 'path'); const project_path = path.join('some', 'path');
var app_path = path.join(project_path, 'app', 'src', 'main'); const app_path = path.join(project_path, 'app', 'src', 'main');
var default_templates = path.join(__dirname, '..', '..', 'templates', 'project'); const default_templates = path.join(__dirname, '..', '..', 'templates', 'project');
var fake_android_target = 'android-1337'; const fake_android_target = 'android-1337';
beforeEach(function () { beforeEach(function () {
Manifest_mock.prototype = jasmine.createSpyObj('AndroidManifest instance mock', ['setPackageId', 'getActivity', 'setName', 'write']); Manifest_mock.prototype = jasmine.createSpyObj('AndroidManifest instance mock', ['setPackageId', 'getActivity', 'setName', 'write']);
@ -260,7 +260,7 @@ describe('create', function () {
it('should copy, rename and interpolate the template Activity java class with the project-specific activity name and package name', () => { it('should copy, rename and interpolate the template Activity java class with the project-specific activity name and package name', () => {
config_mock.packageName.and.returnValue('org.apache.cordova'); config_mock.packageName.and.returnValue('org.apache.cordova');
config_mock.android_activityName.and.returnValue('CEEDEEVEE'); config_mock.android_activityName.and.returnValue('CEEDEEVEE');
var activity_path = path.join(app_path, 'java', 'org', 'apache', 'cordova', 'CEEDEEVEE.java'); const activity_path = path.join(app_path, 'java', 'org', 'apache', 'cordova', 'CEEDEEVEE.java');
return create.create(project_path, config_mock, {}, events_mock).then(() => { return create.create(project_path, config_mock, {}, events_mock).then(() => {
expect(fs.copySync).toHaveBeenCalledWith(path.join(default_templates, 'Activity.java'), activity_path); expect(fs.copySync).toHaveBeenCalledWith(path.join(default_templates, 'Activity.java'), activity_path);
expect(utils.replaceFileContents).toHaveBeenCalledWith(activity_path, /__ACTIVITY__/, 'CEEDEEVEE'); expect(utils.replaceFileContents).toHaveBeenCalledWith(activity_path, /__ACTIVITY__/, 'CEEDEEVEE');

View File

@ -16,24 +16,24 @@
* *
*/ */
var rewire = require('rewire'); const rewire = require('rewire');
var common = rewire('../../../lib/pluginHandlers'); const common = rewire('../../../lib/pluginHandlers');
var path = require('path'); const path = require('path');
var fs = require('fs-extra'); const fs = require('fs-extra');
var osenv = require('os'); const osenv = require('os');
var test_dir = path.join(osenv.tmpdir(), 'test_plugman'); const test_dir = path.join(osenv.tmpdir(), 'test_plugman');
var project_dir = path.join(test_dir, 'project'); const project_dir = path.join(test_dir, 'project');
var src = path.join(project_dir, 'src'); const src = path.join(project_dir, 'src');
var dest = path.join(project_dir, 'dest'); const dest = path.join(project_dir, 'dest');
var java_dir = path.join(src, 'one', 'two', 'three'); const java_dir = path.join(src, 'one', 'two', 'three');
var java_file = path.join(java_dir, 'test.java'); const java_file = path.join(java_dir, 'test.java');
var symlink_file = path.join(java_dir, 'symlink'); const symlink_file = path.join(java_dir, 'symlink');
var non_plugin_file = path.join(osenv.tmpdir(), 'non_plugin_file'); const non_plugin_file = path.join(osenv.tmpdir(), 'non_plugin_file');
var copyFile = common.__get__('copyFile'); const copyFile = common.__get__('copyFile');
var deleteJava = common.__get__('deleteJava'); const deleteJava = common.__get__('deleteJava');
var copyNewFile = common.__get__('copyNewFile'); const copyNewFile = common.__get__('copyNewFile');
describe('common platform handler', function () { describe('common platform handler', function () {
afterEach(() => { afterEach(() => {
@ -50,7 +50,7 @@ describe('common platform handler', function () {
it('Test#002 : should throw if src not in plugin directory', function () { it('Test#002 : should throw if src not in plugin directory', function () {
fs.ensureDirSync(project_dir); fs.ensureDirSync(project_dir);
fs.outputFileSync(non_plugin_file, 'contents'); fs.outputFileSync(non_plugin_file, 'contents');
var outside_file = '../non_plugin_file'; const outside_file = '../non_plugin_file';
expect(function () { copyFile(test_dir, outside_file, project_dir, dest); }) expect(function () { copyFile(test_dir, outside_file, project_dir, dest); })
.toThrow(new Error('File "' + path.resolve(test_dir, outside_file) + '" is located outside the plugin directory "' + test_dir + '"')); .toThrow(new Error('File "' + path.resolve(test_dir, outside_file) + '" is located outside the plugin directory "' + test_dir + '"'));
}); });
@ -88,8 +88,8 @@ describe('common platform handler', function () {
it('Test#006 : should call mkdir -p on target path', function () { it('Test#006 : should call mkdir -p on target path', function () {
fs.outputFileSync(java_file, 'contents'); fs.outputFileSync(java_file, 'contents');
var s = spyOn(fs, 'ensureDirSync').and.callThrough(); const s = spyOn(fs, 'ensureDirSync').and.callThrough();
var resolvedDest = path.resolve(project_dir, dest); const resolvedDest = path.resolve(project_dir, dest);
copyFile(test_dir, java_file, project_dir, dest); copyFile(test_dir, java_file, project_dir, dest);
@ -100,8 +100,8 @@ describe('common platform handler', function () {
it('Test#007 : should call cp source/dest paths', function () { it('Test#007 : should call cp source/dest paths', function () {
fs.outputFileSync(java_file, 'contents'); fs.outputFileSync(java_file, 'contents');
var s = spyOn(fs, 'copySync').and.callThrough(); const s = spyOn(fs, 'copySync').and.callThrough();
var resolvedDest = path.resolve(project_dir, dest); const resolvedDest = path.resolve(project_dir, dest);
copyFile(test_dir, java_file, project_dir, dest); copyFile(test_dir, java_file, project_dir, dest);
@ -133,7 +133,7 @@ describe('common platform handler', function () {
}); });
it('Test#009 : should call fs.unlinkSync on the provided paths', function () { it('Test#009 : should call fs.unlinkSync on the provided paths', function () {
var s = spyOn(fs, 'removeSync').and.callThrough(); const s = spyOn(fs, 'removeSync').and.callThrough();
deleteJava(project_dir, java_file); deleteJava(project_dir, java_file);
expect(s).toHaveBeenCalled(); expect(s).toHaveBeenCalled();
expect(s).toHaveBeenCalledWith(path.resolve(project_dir, java_file)); expect(s).toHaveBeenCalledWith(path.resolve(project_dir, java_file));

View File

@ -17,34 +17,34 @@
under the License. under the License.
*/ */
var rewire = require('rewire'); const rewire = require('rewire');
var common = rewire('../../../lib/pluginHandlers'); const common = rewire('../../../lib/pluginHandlers');
var android = common.__get__('handlers'); const android = common.__get__('handlers');
var path = require('path'); const path = require('path');
var fs = require('fs-extra'); const fs = require('fs-extra');
var os = require('os'); const os = require('os');
var temp = path.join(os.tmpdir(), 'plugman'); const temp = path.join(os.tmpdir(), 'plugman');
var plugins_dir = path.join(temp, 'cordova/plugins'); const plugins_dir = path.join(temp, 'cordova/plugins');
var dummyplugin = path.join(__dirname, '../../fixtures/org.test.plugins.dummyplugin'); const dummyplugin = path.join(__dirname, '../../fixtures/org.test.plugins.dummyplugin');
var faultyplugin = path.join(__dirname, '../../fixtures/org.test.plugins.faultyplugin'); const faultyplugin = path.join(__dirname, '../../fixtures/org.test.plugins.faultyplugin');
var android_studio_project = path.join(__dirname, '../../fixtures/android_studio_project'); const android_studio_project = path.join(__dirname, '../../fixtures/android_studio_project');
var PluginInfo = require('cordova-common').PluginInfo; const PluginInfo = require('cordova-common').PluginInfo;
var AndroidProject = require('../../../lib/AndroidProject'); const AndroidProject = require('../../../lib/AndroidProject');
var dummyPluginInfo = new PluginInfo(dummyplugin); const dummyPluginInfo = new PluginInfo(dummyplugin);
var valid_source = dummyPluginInfo.getSourceFiles('android'); const valid_source = dummyPluginInfo.getSourceFiles('android');
var valid_resources = dummyPluginInfo.getResourceFiles('android'); const valid_resources = dummyPluginInfo.getResourceFiles('android');
var valid_libs = dummyPluginInfo.getLibFiles('android'); const valid_libs = dummyPluginInfo.getLibFiles('android');
var faultyPluginInfo = new PluginInfo(faultyplugin); const faultyPluginInfo = new PluginInfo(faultyplugin);
var invalid_source = faultyPluginInfo.getSourceFiles('android'); const invalid_source = faultyPluginInfo.getSourceFiles('android');
describe('android project handler', function () { describe('android project handler', function () {
describe('installation', function () { describe('installation', function () {
var copyFileOrig = common.__get__('copyFile'); const copyFileOrig = common.__get__('copyFile');
var copyFileSpy = jasmine.createSpy('copyFile'); const copyFileSpy = jasmine.createSpy('copyFile');
var dummyProject; let dummyProject;
beforeEach(function () { beforeEach(function () {
fs.ensureDirSync(temp); fs.ensureDirSync(temp);
@ -177,10 +177,10 @@ describe('android project handler', function () {
}); });
describe('of <framework> elements', function () { describe('of <framework> elements', function () {
var someString = jasmine.any(String); const someString = jasmine.any(String);
var copyNewFileOrig = common.__get__('copyNewFile'); const copyNewFileOrig = common.__get__('copyNewFile');
var copyNewFileSpy = jasmine.createSpy('copyNewFile'); const copyNewFileSpy = jasmine.createSpy('copyNewFile');
beforeEach(function () { beforeEach(function () {
fs.copySync(android_studio_project, temp); fs.copySync(android_studio_project, temp);
@ -200,34 +200,34 @@ describe('android project handler', function () {
}); });
it('Test#008 : should install framework without "parent" attribute into project root', function () { it('Test#008 : should install framework without "parent" attribute into project root', function () {
var framework = { src: 'plugin-lib' }; const framework = { src: 'plugin-lib' };
android.framework.install(framework, dummyPluginInfo, dummyProject); android.framework.install(framework, dummyPluginInfo, dummyProject);
expect(dummyProject.addSystemLibrary).toHaveBeenCalledWith(dummyProject.projectDir, someString); expect(dummyProject.addSystemLibrary).toHaveBeenCalledWith(dummyProject.projectDir, someString);
}); });
it('Test#009 : should install framework with "parent" attribute into parent framework dir', function () { it('Test#009 : should install framework with "parent" attribute into parent framework dir', function () {
var childFramework = { src: 'plugin-lib2', parent: 'plugin-lib' }; const childFramework = { src: 'plugin-lib2', parent: 'plugin-lib' };
android.framework.install(childFramework, dummyPluginInfo, dummyProject); android.framework.install(childFramework, dummyPluginInfo, dummyProject);
expect(dummyProject.addSystemLibrary).toHaveBeenCalledWith(path.resolve(dummyProject.projectDir, childFramework.parent), someString); expect(dummyProject.addSystemLibrary).toHaveBeenCalledWith(path.resolve(dummyProject.projectDir, childFramework.parent), someString);
}); });
it('Test#010 : should not copy anything if "custom" attribute is not set', function () { it('Test#010 : should not copy anything if "custom" attribute is not set', function () {
var framework = { src: 'plugin-lib' }; const framework = { src: 'plugin-lib' };
var cpSpy = spyOn(fs, 'copySync'); const cpSpy = spyOn(fs, 'copySync');
android.framework.install(framework, dummyPluginInfo, dummyProject); android.framework.install(framework, dummyPluginInfo, dummyProject);
expect(dummyProject.addSystemLibrary).toHaveBeenCalledWith(someString, framework.src); expect(dummyProject.addSystemLibrary).toHaveBeenCalledWith(someString, framework.src);
expect(cpSpy).not.toHaveBeenCalled(); expect(cpSpy).not.toHaveBeenCalled();
}); });
it('Test#011 : should copy framework sources if "custom" attribute is set', function () { it('Test#011 : should copy framework sources if "custom" attribute is set', function () {
var framework = { src: 'plugin-lib', custom: true }; const framework = { src: 'plugin-lib', custom: true };
android.framework.install(framework, dummyPluginInfo, dummyProject); android.framework.install(framework, dummyPluginInfo, dummyProject);
expect(dummyProject.addSubProject).toHaveBeenCalledWith(dummyProject.projectDir, someString); expect(dummyProject.addSubProject).toHaveBeenCalledWith(dummyProject.projectDir, someString);
expect(copyNewFileSpy).toHaveBeenCalledWith(dummyPluginInfo.dir, framework.src, dummyProject.projectDir, someString, false); expect(copyNewFileSpy).toHaveBeenCalledWith(dummyPluginInfo.dir, framework.src, dummyProject.projectDir, someString, false);
}); });
it('Test#012 : should install gradleReference using project.addGradleReference', function () { it('Test#012 : should install gradleReference using project.addGradleReference', function () {
var framework = { src: 'plugin-lib', custom: true, type: 'gradleReference' }; const framework = { src: 'plugin-lib', custom: true, type: 'gradleReference' };
android.framework.install(framework, dummyPluginInfo, dummyProject); android.framework.install(framework, dummyPluginInfo, dummyProject);
expect(copyNewFileSpy).toHaveBeenCalledWith(dummyPluginInfo.dir, framework.src, dummyProject.projectDir, someString, false); expect(copyNewFileSpy).toHaveBeenCalledWith(dummyPluginInfo.dir, framework.src, dummyProject.projectDir, someString, false);
expect(dummyProject.addGradleReference).toHaveBeenCalledWith(dummyProject.projectDir, someString); expect(dummyProject.addGradleReference).toHaveBeenCalledWith(dummyProject.projectDir, someString);
@ -235,8 +235,8 @@ describe('android project handler', function () {
}); });
describe('of <js-module> elements', function () { describe('of <js-module> elements', function () {
var jsModule = { src: 'www/dummyplugin.js' }; const jsModule = { src: 'www/dummyplugin.js' };
var wwwDest, platformWwwDest; let wwwDest, platformWwwDest;
beforeEach(function () { beforeEach(function () {
spyOn(fs, 'writeFileSync'); spyOn(fs, 'writeFileSync');
@ -258,7 +258,7 @@ describe('android project handler', function () {
}); });
describe('of <asset> elements', function () { describe('of <asset> elements', function () {
var asset; let asset;
beforeEach(function () { beforeEach(function () {
asset = { src: 'www/dummyPlugin.js', target: 'foo/dummy.js' }; asset = { src: 'www/dummyPlugin.js', target: 'foo/dummy.js' };
@ -279,10 +279,10 @@ describe('android project handler', function () {
}); });
describe('uninstallation', function () { describe('uninstallation', function () {
var deleteJavaOrig = common.__get__('deleteJava'); const deleteJavaOrig = common.__get__('deleteJava');
const originalRemoveSync = fs.removeSync; const originalRemoveSync = fs.removeSync;
var deleteJavaSpy = jasmine.createSpy('deleteJava'); const deleteJavaSpy = jasmine.createSpy('deleteJava');
var dummyProject; let dummyProject;
let removeSyncSpy; let removeSyncSpy;
beforeEach(function () { beforeEach(function () {
@ -385,7 +385,7 @@ describe('android project handler', function () {
}); });
describe('of <framework> elements', function () { describe('of <framework> elements', function () {
var someString = jasmine.any(String); const someString = jasmine.any(String);
beforeEach(function () { beforeEach(function () {
fs.ensureDirSync(path.join(dummyProject.projectDir, dummyPluginInfo.id)); fs.ensureDirSync(path.join(dummyProject.projectDir, dummyPluginInfo.id));
@ -400,26 +400,26 @@ describe('android project handler', function () {
}); });
it('Test#021 : should uninstall framework without "parent" attribute into project root', function () { it('Test#021 : should uninstall framework without "parent" attribute into project root', function () {
var framework = { src: 'plugin-lib' }; const framework = { src: 'plugin-lib' };
android.framework.uninstall(framework, dummyPluginInfo, dummyProject); android.framework.uninstall(framework, dummyPluginInfo, dummyProject);
expect(dummyProject.removeSystemLibrary).toHaveBeenCalledWith(dummyProject.projectDir, someString); expect(dummyProject.removeSystemLibrary).toHaveBeenCalledWith(dummyProject.projectDir, someString);
}); });
it('Test#022 : should uninstall framework with "parent" attribute into parent framework dir', function () { it('Test#022 : should uninstall framework with "parent" attribute into parent framework dir', function () {
var childFramework = { src: 'plugin-lib2', parent: 'plugin-lib' }; const childFramework = { src: 'plugin-lib2', parent: 'plugin-lib' };
android.framework.uninstall(childFramework, dummyPluginInfo, dummyProject); android.framework.uninstall(childFramework, dummyPluginInfo, dummyProject);
expect(dummyProject.removeSystemLibrary).toHaveBeenCalledWith(path.resolve(dummyProject.projectDir, childFramework.parent), someString); expect(dummyProject.removeSystemLibrary).toHaveBeenCalledWith(path.resolve(dummyProject.projectDir, childFramework.parent), someString);
}); });
it('Test#023 : should remove framework sources if "custom" attribute is set', function () { it('Test#023 : should remove framework sources if "custom" attribute is set', function () {
var framework = { src: 'plugin-lib', custom: true }; const framework = { src: 'plugin-lib', custom: true };
android.framework.uninstall(framework, dummyPluginInfo, dummyProject); android.framework.uninstall(framework, dummyPluginInfo, dummyProject);
expect(dummyProject.removeSubProject).toHaveBeenCalledWith(dummyProject.projectDir, someString); expect(dummyProject.removeSubProject).toHaveBeenCalledWith(dummyProject.projectDir, someString);
expect(removeSyncSpy).toHaveBeenCalledWith(someString); expect(removeSyncSpy).toHaveBeenCalledWith(someString);
}); });
it('Test#24 : should install gradleReference using project.removeGradleReference', function () { it('Test#24 : should install gradleReference using project.removeGradleReference', function () {
var framework = { src: 'plugin-lib', custom: true, type: 'gradleReference' }; const framework = { src: 'plugin-lib', custom: true, type: 'gradleReference' };
android.framework.uninstall(framework, dummyPluginInfo, dummyProject); android.framework.uninstall(framework, dummyPluginInfo, dummyProject);
expect(removeSyncSpy).toHaveBeenCalledWith(someString); expect(removeSyncSpy).toHaveBeenCalledWith(someString);
expect(dummyProject.removeGradleReference).toHaveBeenCalledWith(dummyProject.projectDir, someString); expect(dummyProject.removeGradleReference).toHaveBeenCalledWith(dummyProject.projectDir, someString);
@ -427,15 +427,15 @@ describe('android project handler', function () {
}); });
describe('of <js-module> elements', function () { describe('of <js-module> elements', function () {
var jsModule = { src: 'www/dummyPlugin.js' }; const jsModule = { src: 'www/dummyPlugin.js' };
var wwwDest; let wwwDest;
var platformWwwDest; let platformWwwDest;
beforeEach(function () { beforeEach(function () {
wwwDest = path.resolve(dummyProject.www, 'plugins', dummyPluginInfo.id, jsModule.src); wwwDest = path.resolve(dummyProject.www, 'plugins', dummyPluginInfo.id, jsModule.src);
platformWwwDest = path.resolve(dummyProject.platformWww, 'plugins', dummyPluginInfo.id, jsModule.src); platformWwwDest = path.resolve(dummyProject.platformWww, 'plugins', dummyPluginInfo.id, jsModule.src);
var existsSyncOrig = fs.existsSync; const existsSyncOrig = fs.existsSync;
spyOn(fs, 'existsSync').and.callFake(function (file) { spyOn(fs, 'existsSync').and.callFake(function (file) {
if ([wwwDest, platformWwwDest].indexOf(file) >= 0) return true; if ([wwwDest, platformWwwDest].indexOf(file) >= 0) return true;
return existsSyncOrig.call(fs, file); return existsSyncOrig.call(fs, file);
@ -456,14 +456,14 @@ describe('android project handler', function () {
}); });
describe('of <asset> elements', function () { describe('of <asset> elements', function () {
var asset = { src: 'www/dummyPlugin.js', target: 'foo/dummy.js' }; const asset = { src: 'www/dummyPlugin.js', target: 'foo/dummy.js' };
var wwwDest, platformWwwDest; let wwwDest, platformWwwDest;
beforeEach(function () { beforeEach(function () {
wwwDest = path.resolve(dummyProject.www, asset.target); wwwDest = path.resolve(dummyProject.www, asset.target);
platformWwwDest = path.resolve(dummyProject.platformWww, asset.target); platformWwwDest = path.resolve(dummyProject.platformWww, asset.target);
var existsSyncOrig = fs.existsSync; const existsSyncOrig = fs.existsSync;
spyOn(fs, 'existsSync').and.callFake(function (file) { spyOn(fs, 'existsSync').and.callFake(function (file) {
if ([wwwDest, platformWwwDest].indexOf(file) >= 0) return true; if ([wwwDest, platformWwwDest].indexOf(file) >= 0) return true;
return existsSyncOrig.call(fs, file); return existsSyncOrig.call(fs, file);

View File

@ -17,9 +17,9 @@
under the License. under the License.
*/ */
var rewire = require('rewire'); const rewire = require('rewire');
var path = require('path'); const path = require('path');
var CordovaError = require('cordova-common').CordovaError; const CordovaError = require('cordova-common').CordovaError;
const GradlePropertiesParser = require('../../lib/config/GradlePropertiesParser'); const GradlePropertiesParser = require('../../lib/config/GradlePropertiesParser');
const PATH_RESOURCE = path.join('platforms', 'android', 'app', 'src', 'main', 'res'); const PATH_RESOURCE = path.join('platforms', 'android', 'app', 'src', 'main', 'res');
@ -688,7 +688,7 @@ describe('prepare', () => {
}; };
const platformResourcesDir = PATH_RESOURCE; const platformResourcesDir = PATH_RESOURCE;
var expectedResourceMapBackground = createResourceMap('ic_launcher_background.png'); const expectedResourceMapBackground = createResourceMap('ic_launcher_background.png');
// mocking initial responses for mapImageResources // mocking initial responses for mapImageResources
prepare.__set__('mapImageResources', function (rootDir, subDir, type, resourceName) { prepare.__set__('mapImageResources', function (rootDir, subDir, type, resourceName) {
@ -719,7 +719,7 @@ describe('prepare', () => {
}; };
const platformResourcesDir = PATH_RESOURCE; const platformResourcesDir = PATH_RESOURCE;
var expectedResourceMap = createResourceMap(); const expectedResourceMap = createResourceMap();
// mocking initial responses for mapImageResources // mocking initial responses for mapImageResources
prepare.__set__('mapImageResources', function (rootDir, subDir, type, resourceName) { prepare.__set__('mapImageResources', function (rootDir, subDir, type, resourceName) {

View File

@ -19,7 +19,7 @@
under the License. under the License.
*/ */
var android_sdk = require('cordova-android/lib/android_sdk'); const android_sdk = require('cordova-android/lib/android_sdk');
android_sdk.print_newest_available_sdk_target().catch(err => { android_sdk.print_newest_available_sdk_target().catch(err => {
console.error(err); console.error(err);

View File

@ -19,7 +19,7 @@
under the License. under the License.
*/ */
var emulators = require('cordova-android/lib/emulator'); const emulators = require('cordova-android/lib/emulator');
// Usage support for when args are given // Usage support for when args are given
require('cordova-android/lib/check_reqs').check_android().then(function () { require('cordova-android/lib/check_reqs').check_android().then(function () {