This commit is contained in:
tiago.kayaya
2021-08-18 18:58:02 +01:00
parent 4439604772
commit 24e2a8f518
5000 changed files with 655398 additions and 26 deletions
+531
View File
@@ -0,0 +1,531 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
'License'); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
this file is found by cordova-lib when you attempt to
'cordova platform add PATH' where path is this repo.
*/
var shell = require('shelljs');
var path = require('path');
var fs = require('fs');
var cdvcmn = require('cordova-common');
var CordovaLogger = cdvcmn.CordovaLogger;
var ConfigParser = cdvcmn.ConfigParser;
var ActionStack = cdvcmn.ActionStack;
var selfEvents = cdvcmn.events;
var xmlHelpers = cdvcmn.xmlHelpers;
var PlatformJson = cdvcmn.PlatformJson;
var PlatformMunger = cdvcmn.ConfigChanges.PlatformMunger;
var PluginInfoProvider = cdvcmn.PluginInfoProvider;
var BrowserParser = require('./browser_parser');
var PLATFORM_NAME = 'browser';
function setupEvents (externalEventEmitter) {
if (externalEventEmitter) {
// This will make the platform internal events visible outside
selfEvents.forwardEventsTo(externalEventEmitter);
return externalEventEmitter;
}
// There is no logger if external emitter is not present,
// so attach a console logger
CordovaLogger.get().subscribe(selfEvents);
return selfEvents;
}
function Api (platform, platformRootDir, events) {
this.platform = platform || PLATFORM_NAME;
// MyApp/platforms/browser
this.root = path.resolve(__dirname, '..');
this.events = setupEvents(events);
this.parser = new BrowserParser(this.root);
this._handler = require('./browser_handler');
this.locations = {
platformRootDir: platformRootDir,
root: this.root,
www: path.join(this.root, 'www'),
res: path.join(this.root, 'res'),
platformWww: path.join(this.root, 'platform_www'),
configXml: path.join(this.root, 'config.xml'),
defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),
build: path.join(this.root, 'build'),
// NOTE: Due to platformApi spec we need to return relative paths here
cordovaJs: 'bin/templates/project/assets/www/cordova.js',
cordovaJsSrc: 'cordova-js-src'
};
this._platformJson = PlatformJson.load(this.root, platform);
this._pluginInfoProvider = new PluginInfoProvider();
this._munger = new PlatformMunger(platform, this.root, this._platformJson, this._pluginInfoProvider);
}
Api.createPlatform = function (dest, config, options, events) {
var creator = require('../../lib/create');
events = setupEvents(events);
var name = 'HelloCordova';
var id = 'io.cordova.hellocordova';
if (config) {
name = config.name();
id = config.packageName();
}
var result;
try {
// we create the project using our scripts in this platform
result = creator.createProject(dest, id, name, options)
.then(function () {
// after platform is created we return Api instance based on new Api.js location
// Api.js has been copied to the new project
// This is required to correctly resolve paths in the future api calls
var PlatformApi = require(path.resolve(dest, 'cordova/Api'));
return new PlatformApi('browser', dest, events);
});
} catch (e) {
events.emit('error', 'createPlatform is not callable from the browser project API.');
throw (e);
}
return result;
};
Api.updatePlatform = function (dest, options, events) {
// console.log("test-platform:Api:updatePlatform");
// todo?: create projectInstance and fulfill promise with it.
return Promise.resolve();
};
Api.prototype.getPlatformInfo = function () {
// console.log("browser-platform:Api:getPlatformInfo");
// return PlatformInfo object
return {
'locations': this.locations,
'root': this.root,
'name': this.platform,
'version': { 'version': '1.0.0' }, // um, todo!
'projectConfig': this.config
};
};
Api.prototype.prepare = function (cordovaProject, options) {
// First cleanup current config and merge project's one into own
var defaultConfigPath = path.join(this.locations.platformRootDir, 'cordova',
'defaults.xml');
var ownConfigPath = this.locations.configXml;
var sourceCfg = cordovaProject.projectConfig;
// If defaults.xml is present, overwrite platform config.xml with it.
// Otherwise save whatever is there as defaults so it can be
// restored or copy project config into platform if none exists.
if (fs.existsSync(defaultConfigPath)) {
this.events.emit('verbose', 'Generating config.xml from defaults for platform "' + this.platform + '"');
shell.cp('-f', defaultConfigPath, ownConfigPath);
} else if (fs.existsSync(ownConfigPath)) {
this.events.emit('verbose', 'Generating defaults.xml from own config.xml for platform "' + this.platform + '"');
shell.cp('-f', ownConfigPath, defaultConfigPath);
} else {
this.events.emit('verbose', 'case 3"' + this.platform + '"');
shell.cp('-f', sourceCfg.path, ownConfigPath);
}
// merge our configs
this.config = new ConfigParser(ownConfigPath);
xmlHelpers.mergeXml(cordovaProject.projectConfig.doc.getroot(),
this.config.doc.getroot(),
this.platform, true);
this.config.write();
// Update own www dir with project's www assets and plugins' assets and js-files
this.parser.update_www(cordovaProject, options);
// Copy or Create manifest.json
// todo: move this to a manifest helper module
// output path
var manifestPath = path.join(this.locations.www, 'manifest.json');
var srcManifestPath = path.join(cordovaProject.locations.www, 'manifest.json');
if (fs.existsSync(srcManifestPath)) {
// just blindly copy it to our output/www
// todo: validate it? ensure all properties we expect exist?
this.events.emit('verbose', 'copying ' + srcManifestPath + ' => ' + manifestPath);
shell.cp('-f', srcManifestPath, manifestPath);
} else {
var manifestJson = {
'background_color': '#FFF',
'display': 'standalone'
};
if (this.config) {
if (this.config.name()) {
manifestJson.name = this.config.name();
}
if (this.config.shortName()) {
manifestJson.short_name = this.config.shortName();
}
if (this.config.packageName()) {
manifestJson.version = this.config.packageName();
}
if (this.config.description()) {
manifestJson.description = this.config.description();
}
if (this.config.author()) {
manifestJson.author = this.config.author();
}
// icons
var icons = this.config.getStaticResources('browser', 'icon');
var manifestIcons = icons.map(function (icon) {
// given a tag like this :
// <icon src="res/ios/icon.png" width="57" height="57" density="mdpi" />
/* configParser returns icons that look like this :
{ src: 'res/ios/icon.png',
target: undefined,
density: 'mdpi',
platform: null,
width: 57,
height: 57
} ******/
/* manifest expects them to be like this :
{ "src": "images/touch/icon-128x128.png",
"type": "image/png",
"sizes": "128x128"
} ******/
// ?Is it worth looking at file extentions?
return { 'src': icon.src,
'type': 'image/png',
'sizes': (icon.width + 'x' + icon.height) };
});
manifestJson.icons = manifestIcons;
// orientation
// <preference name="Orientation" value="landscape" />
var oriPref = this.config.getGlobalPreference('Orientation');
if (oriPref) {
// if it's a supported value, use it
if (['landscape', 'portrait'].indexOf(oriPref) > -1) {
manifestJson.orientation = oriPref;
} else { // anything else maps to 'any'
manifestJson.orientation = 'any';
}
}
// get start_url
var contentNode = this.config.doc.find('content') || { 'attrib': { 'src': 'index.html' } }; // sensible default
manifestJson.start_url = contentNode.attrib.src;
// now we get some values from start_url page ...
var startUrlPath = path.join(cordovaProject.locations.www, manifestJson.start_url);
if (fs.existsSync(startUrlPath)) {
var contents = fs.readFileSync(startUrlPath, 'utf-8');
// matches <meta name="theme-color" content="#FF0044">
var themeColorRegex = /<meta(?=[^>]*name="theme-color")\s[^>]*content="([^>]*)"/i;
var result = themeColorRegex.exec(contents);
var themeColor;
if (result && result.length >= 2) {
themeColor = result[1];
} else { // see if there is a preference in config.xml
// <preference name="StatusBarBackgroundColor" value="#000000" />
themeColor = this.config.getGlobalPreference('StatusBarBackgroundColor');
}
if (themeColor) {
manifestJson.theme_color = themeColor;
}
}
}
fs.writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 2), 'utf8');
}
// update project according to config.xml changes.
return this.parser.update_project(this.config, options);
};
Api.prototype.addPlugin = function (pluginInfo, installOptions) {
// console.log(new Error().stack);
if (!pluginInfo) {
return Promise.reject(new Error('The parameter is incorrect. The first parameter ' +
'should be valid PluginInfo instance'));
}
installOptions = installOptions || {};
installOptions.variables = installOptions.variables || {};
// CB-10108 platformVersion option is required for proper plugin installation
installOptions.platformVersion = installOptions.platformVersion ||
this.getPlatformInfo().version;
var self = this;
var actions = new ActionStack();
var projectFile = this._handler.parseProjectFile && this._handler.parseProjectFile(this.root);
// gather all files needs to be handled during install
pluginInfo.getFilesAndFrameworks(this.platform)
.concat(pluginInfo.getAssets(this.platform))
.concat(pluginInfo.getJsModules(this.platform))
.forEach(function (item) {
actions.push(actions.createAction(
self._getInstaller(item.itemType),
[item, pluginInfo.dir, pluginInfo.id, installOptions, projectFile],
self._getUninstaller(item.itemType),
[item, pluginInfo.dir, pluginInfo.id, installOptions, projectFile]));
});
// run through the action stack
return actions.process(this.platform, this.root)
.then(function () {
if (projectFile) {
projectFile.write();
}
// Add PACKAGE_NAME variable into vars
if (!installOptions.variables.PACKAGE_NAME) {
installOptions.variables.PACKAGE_NAME = self._handler.package_name(self.root);
}
self._munger
// Ignore passed `is_top_level` option since platform itself doesn't know
// anything about managing dependencies - it's responsibility of caller.
.add_plugin_changes(pluginInfo, installOptions.variables, /* is_top_level= */true, /* should_increment= */true)
.save_all();
var targetDir = installOptions.usePlatformWww ?
self.getPlatformInfo().locations.platformWww :
self.getPlatformInfo().locations.www;
self._addModulesInfo(pluginInfo, targetDir);
});
};
Api.prototype.removePlugin = function (plugin, uninstallOptions) {
// console.log("NotImplemented :: browser-platform:Api:removePlugin ",plugin, uninstallOptions);
uninstallOptions = uninstallOptions || {};
// CB-10108 platformVersion option is required for proper plugin installation
uninstallOptions.platformVersion = uninstallOptions.platformVersion ||
this.getPlatformInfo().version;
var self = this;
var actions = new ActionStack();
var projectFile = this._handler.parseProjectFile && this._handler.parseProjectFile(this.root);
// queue up plugin files
plugin.getFilesAndFrameworks(this.platform)
.concat(plugin.getAssets(this.platform))
.concat(plugin.getJsModules(this.platform))
.forEach(function (item) {
actions.push(actions.createAction(
self._getUninstaller(item.itemType), [item, plugin.dir, plugin.id, uninstallOptions, projectFile],
self._getInstaller(item.itemType), [item, plugin.dir, plugin.id, uninstallOptions, projectFile]));
});
// run through the action stack
return actions.process(this.platform, this.root)
.then(function () {
if (projectFile) {
projectFile.write();
}
self._munger
// Ignore passed `is_top_level` option since platform itself doesn't know
// anything about managing dependencies - it's responsibility of caller.
.remove_plugin_changes(plugin, /* is_top_level= */true)
.save_all();
var targetDir = uninstallOptions.usePlatformWww ?
self.getPlatformInfo().locations.platformWww :
self.getPlatformInfo().locations.www;
self._removeModulesInfo(plugin, targetDir);
// Remove stale plugin directory
// TODO: this should be done by plugin files uninstaller
shell.rm('-rf', path.resolve(self.root, 'Plugins', plugin.id));
});
};
Api.prototype._getInstaller = function (type) {
var self = this;
return function (item, plugin_dir, plugin_id, options, project) {
var installer = self._handler[type];
if (!installer) {
console.log('unrecognized type ' + type);
} else {
var wwwDest = options.usePlatformWww ?
self.getPlatformInfo().locations.platformWww :
self._handler.www_dir(self.root);
if (type === 'asset') {
installer.install(item, plugin_dir, wwwDest);
} else if (type === 'js-module') {
installer.install(item, plugin_dir, plugin_id, wwwDest);
} else {
installer.install(item, plugin_dir, self.root, plugin_id, options, project);
}
}
};
};
Api.prototype._getUninstaller = function (type) {
var self = this;
return function (item, plugin_dir, plugin_id, options, project) {
var installer = self._handler[type];
if (!installer) {
console.log('browser plugin uninstall: unrecognized type, skipping : ' + type);
} else {
var wwwDest = options.usePlatformWww ?
self.getPlatformInfo().locations.platformWww :
self._handler.www_dir(self.root);
if (['asset', 'js-module'].indexOf(type) > -1) {
return installer.uninstall(item, wwwDest, plugin_id);
} else {
return installer.uninstall(item, self.root, plugin_id, options, project);
}
}
};
};
/**
* Removes the specified modules from list of installed modules and updates
* platform_json and cordova_plugins.js on disk.
*
* @param {PluginInfo} plugin PluginInfo instance for plugin, which modules
* needs to be added.
* @param {String} targetDir The directory, where updated cordova_plugins.js
* should be written to.
*/
Api.prototype._addModulesInfo = function (plugin, targetDir) {
var installedModules = this._platformJson.root.modules || [];
var installedPaths = installedModules.map(function (installedModule) {
return installedModule.file;
});
var modulesToInstall = plugin.getJsModules(this.platform)
.filter(function (moduleToInstall) {
return installedPaths.indexOf(moduleToInstall.file) === -1;
}).map(function (moduleToInstall) {
var moduleName = plugin.id + '.' + (moduleToInstall.name || moduleToInstall.src.match(/([^\/]+)\.js/)[1]);
var obj = {
file: ['plugins', plugin.id, moduleToInstall.src].join('/'), /* eslint no-useless-escape : 0 */
id: moduleName,
pluginId: plugin.id
};
if (moduleToInstall.clobbers.length > 0) {
obj.clobbers = moduleToInstall.clobbers.map(function (o) { return o.target; });
}
if (moduleToInstall.merges.length > 0) {
obj.merges = moduleToInstall.merges.map(function (o) { return o.target; });
}
if (moduleToInstall.runs) {
obj.runs = true;
}
return obj;
});
this._platformJson.root.modules = installedModules.concat(modulesToInstall);
if (!this._platformJson.root.plugin_metadata) {
this._platformJson.root.plugin_metadata = {};
}
this._platformJson.root.plugin_metadata[plugin.id] = plugin.version;
this._writePluginModules(targetDir);
this._platformJson.save();
};
/**
* Fetches all installed modules, generates cordova_plugins contents and writes
* it to file.
*
* @param {String} targetDir Directory, where write cordova_plugins.js to.
* Ususally it is either <platform>/www or <platform>/platform_www
* directories.
*/
Api.prototype._writePluginModules = function (targetDir) {
// Write out moduleObjects as JSON wrapped in a cordova module to cordova_plugins.js
var final_contents = 'cordova.define(\'cordova/plugin_list\', function(require, exports, module) {\n';
final_contents += 'module.exports = ' + JSON.stringify(this._platformJson.root.modules, null, ' ') + ';\n';
final_contents += 'module.exports.metadata = \n';
final_contents += '// TOP OF METADATA\n';
final_contents += JSON.stringify(this._platformJson.root.plugin_metadata || {}, null, ' ') + '\n';
final_contents += '// BOTTOM OF METADATA\n';
final_contents += '});'; // Close cordova.define.
shell.mkdir('-p', targetDir);
fs.writeFileSync(path.join(targetDir, 'cordova_plugins.js'), final_contents, 'utf-8');
};
/**
* Removes the specified modules from list of installed modules and updates
* platform_json and cordova_plugins.js on disk.
*
* @param {PluginInfo} plugin PluginInfo instance for plugin, which modules
* needs to be removed.
* @param {String} targetDir The directory, where updated cordova_plugins.js
* should be written to.
*/
Api.prototype._removeModulesInfo = function (plugin, targetDir) {
var installedModules = this._platformJson.root.modules || [];
var modulesToRemove = plugin.getJsModules(this.platform)
.map(function (jsModule) {
return ['plugins', plugin.id, jsModule.src].join('/');
});
var updatedModules = installedModules
.filter(function (installedModule) {
return (modulesToRemove.indexOf(installedModule.file) === -1);
});
this._platformJson.root.modules = updatedModules;
if (this._platformJson.root.plugin_metadata) {
delete this._platformJson.root.plugin_metadata[plugin.id];
}
this._writePluginModules(targetDir);
this._platformJson.save();
};
Api.prototype.build = function (buildOptions) {
var self = this;
return require('./lib/check_reqs').run()
.then(function () {
return require('./lib/build').run.call(self, buildOptions);
});
};
Api.prototype.run = function (runOptions) {
return require('./lib/run').run(runOptions);
};
Api.prototype.clean = function (cleanOptions) {
return require('./lib/clean').run(cleanOptions);
};
Api.prototype.requirements = function () {
return require('./lib/check_reqs').run();
};
module.exports = Api;
+135
View File
@@ -0,0 +1,135 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var path = require('path');
var fs = require('fs');
var shell = require('shelljs');
var events = require('cordova-common').events;
module.exports = {
www_dir: function (project_dir) {
return path.join(project_dir, 'www');
},
package_name: function (project_dir) {
// this method should the id from root config.xml => <widget id=xxx
// return common.package_name(project_dir, this.www_dir(project_dir));
// console.log('package_name called with ' + project_dir);
var pkgName = 'io.cordova.hellocordova';
var widget_id_regex = /(?:<widget\s+id=['"])(\S+)(?:['"])/;
var configPath = path.join(project_dir, 'config.xml');
if (fs.existsSync(configPath)) {
var configStr = fs.readFileSync(configPath, 'utf8');
var res = configStr.match(widget_id_regex);
if (res && res.length > 1) {
pkgName = res[1];
}
}
return pkgName;
},
'js-module': {
install: function (jsModule, plugin_dir, plugin_id, www_dir) {
// Copy the plugin's files into the www directory.
var moduleSource = path.resolve(plugin_dir, jsModule.src);
// Get module name based on existing 'name' attribute or filename
// Must use path.extname/path.basename instead of path.parse due to CB-9981
var moduleName = plugin_id + '.' + (jsModule.name || path.basename(jsModule.src, path.extname(jsModule.src)));
// Read in the file, prepend the cordova.define, and write it back out.
var scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOM
if (moduleSource.match(/.*\.json$/)) {
scriptContent = 'module.exports = ' + scriptContent;
}
scriptContent = 'cordova.define("' + moduleName + '", function(require, exports, module) { ' + scriptContent + '\n});\n';
var moduleDestination = path.resolve(www_dir, 'plugins', plugin_id, jsModule.src);
shell.mkdir('-p', path.dirname(moduleDestination));
fs.writeFileSync(moduleDestination, scriptContent, 'utf-8');
},
uninstall: function (jsModule, www_dir, plugin_id) {
var pluginRelativePath = path.join('plugins', plugin_id, jsModule.src);
// common.removeFileAndParents(www_dir, pluginRelativePath);
console.log('js-module uninstall called : ' + pluginRelativePath);
}
},
'source-file': {
install: function (obj, plugin_dir, project_dir, plugin_id, options) {
// var dest = path.join(obj.targetDir, path.basename(obj.src));
// common.copyFile(plugin_dir, obj.src, project_dir, dest);
console.log('install called');
},
uninstall: function (obj, project_dir, plugin_id, options) {
// var dest = path.join(obj.targetDir, path.basename(obj.src));
// common.removeFile(project_dir, dest);
console.log('uninstall called');
}
},
'header-file': {
install: function (obj, plugin_dir, project_dir, plugin_id, options) {
events.emit('verbose', 'header-fileinstall is not supported for browser');
},
uninstall: function (obj, project_dir, plugin_id, options) {
events.emit('verbose', 'header-file.uninstall is not supported for browser');
}
},
'resource-file': {
install: function (obj, plugin_dir, project_dir, plugin_id, options) {
events.emit('verbose', 'resource-file.install is not supported for browser');
},
uninstall: function (obj, project_dir, plugin_id, options) {
events.emit('verbose', 'resource-file.uninstall is not supported for browser');
}
},
'framework': {
install: function (obj, plugin_dir, project_dir, plugin_id, options) {
events.emit('verbose', 'framework.install is not supported for browser');
},
uninstall: function (obj, project_dir, plugin_id, options) {
events.emit('verbose', 'framework.uninstall is not supported for browser');
}
},
'lib-file': {
install: function (obj, plugin_dir, project_dir, plugin_id, options) {
events.emit('verbose', 'lib-file.install is not supported for browser');
},
uninstall: function (obj, project_dir, plugin_id, options) {
events.emit('verbose', 'lib-file.uninstall is not supported for browser');
}
},
asset: {
install: function (asset, plugin_dir, wwwDest) {
var src = path.join(plugin_dir, asset.src);
var dest = path.join(wwwDest, asset.target);
var destDir = path.parse(dest).dir;
if (destDir !== '' && !fs.existsSync(destDir)) {
shell.mkdir('-p', destDir);
}
if (fs.statSync(src).isDirectory()) {
shell.cp('-Rf', src + '/*', dest);
} else {
shell.cp('-f', src, dest);
}
},
uninstall: function (asset, wwwDest, plugin_id) {
shell.rm('-rf', path.join(wwwDest, asset.target));
shell.rm('-rf', path.join(wwwDest, 'plugins', plugin_id));
}
}
};
+120
View File
@@ -0,0 +1,120 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var CordovaError = require('cordova-common').CordovaError;
var events = require('cordova-common').events;
var FileUpdater = require('cordova-common').FileUpdater;
function dirExists (dir) {
return fs.existsSync(dir) && fs.statSync(dir).isDirectory();
}
function browser_parser (project) {
if (!dirExists(project) || !dirExists(path.join(project, 'cordova'))) {
throw new CordovaError('The provided path "' + project + '" is not a valid browser project.');
}
this.path = project;
}
module.exports = browser_parser;
// Returns a promise.
browser_parser.prototype.update_from_config = function () {
return Promise.resolve();
};
browser_parser.prototype.www_dir = function () {
return path.join(this.path, 'www');
};
// Used for creating platform_www in projects created by older versions.
browser_parser.prototype.cordovajs_path = function (libDir) {
var jsPath = path.join(libDir, 'cordova-lib', 'cordova.js');
return path.resolve(jsPath);
};
browser_parser.prototype.cordovajs_src_path = function (libDir) {
// console.log("cordovajs_src_path");
var jsPath = path.join(libDir, 'cordova-js-src');
return path.resolve(jsPath);
};
/**
* Logs all file operations via the verbose event stream, indented.
*/
function logFileOp (message) {
events.emit('verbose', ' ' + message);
}
// Replace the www dir with contents of platform_www and app www.
browser_parser.prototype.update_www = function (cordovaProject, opts) {
var platform_www = path.join(this.path, 'platform_www');
var my_www = this.www_dir();
// add cordova www and platform_www to sourceDirs
var sourceDirs = [
path.relative(cordovaProject.root, cordovaProject.locations.www),
path.relative(cordovaProject.root, platform_www)
];
// If project contains 'merges' for our platform, use them as another overrides
var merges_path = path.join(cordovaProject.root, 'merges', 'browser');
if (fs.existsSync(merges_path)) {
events.emit('verbose', 'Found "merges/browser" folder. Copying its contents into the browser project.');
// add merges/browser to sourceDirs
sourceDirs.push(path.join('merges', 'browser'));
}
// targetDir points to browser/www
var targetDir = path.relative(cordovaProject.root, my_www);
events.emit('verbose', 'Merging and updating files from [' + sourceDirs.join(', ') + '] to ' + targetDir);
FileUpdater.mergeAndUpdateDir(sourceDirs, targetDir, { rootDir: cordovaProject.root }, logFileOp);
};
browser_parser.prototype.update_overrides = function () {
// console.log("update_overrides");
// TODO: ?
// var projectRoot = util.isCordova(this.path);
// var mergesPath = path.join(util.appDir(projectRoot), 'merges', 'browser');
// if(fs.existsSync(mergesPath)) {
// var overrides = path.join(mergesPath, '*');
// shell.cp('-rf', overrides, this.www_dir());
// }
};
browser_parser.prototype.config_xml = function () {
return path.join(this.path, 'config.xml');
};
// Returns a promise.
browser_parser.prototype.update_project = function (cfg) {
// console.log("update_project ",cfg);
var defer = this.update_from_config();
var self = this;
var www_dir = self.www_dir();
defer.then(function () {
self.update_overrides();
// Copy munged config.xml to platform www dir
shell.cp('-rf', path.join(www_dir, '..', 'config.xml'), www_dir);
});
return defer;
};
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env node
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var build = require('./lib/build'),
args = process.argv;
// provide help
if ( args[2] == '--help' || args[2] == '/?' || args[2] == '-h' || args[2] == '/h' ||
args[2] == 'help' || args[2] == '-help' || args[2] == '/help') {
build.help();
process.exit(0);
} else {
build.run();
}
+26
View File
@@ -0,0 +1,26 @@
:: Licensed to the Apache Software Foundation (ASF) under one
:: or more contributor license agreements. See the NOTICE file
:: distributed with this work for additional information
:: regarding copyright ownership. The ASF licenses this file
:: to you under the Apache License, Version 2.0 (the
:: "License"); you may not use this file except in compliance
:: with the License. You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing,
:: software distributed under the License is distributed on an
:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET script_path="%~dp0build"
IF EXIST %script_path% (
node %script_path% %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'build' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env node
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var path = require('path'),
clean = require('./lib/clean'),
args = process.argv;
// Support basic help commands
if ( args.length > 2
|| args[2] == '--help' || args[2] == '/?' || args[2] == '-h' ||
args[2] == 'help' || args[2] == '-help' || args[2] == '/help') {
console.log('Usage: ' + path.relative(process.cwd(), path.join(__dirname, 'clean')) );
process.exit(0);
} else {
clean.run();
}
+26
View File
@@ -0,0 +1,26 @@
:: Licensed to the Apache Software Foundation (ASF) under one
:: or more contributor license agreements. See the NOTICE file
:: distributed with this work for additional information
:: regarding copyright ownership. The ASF licenses this file
:: to you under the Apache License, Version 2.0 (the
:: "License"); you may not use this file except in compliance
:: with the License. You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing,
:: software distributed under the License is distributed on an
:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
:: KIND, either express or implied. See the License for the
:: specific language governing permissions and limitations
:: under the License.
@ECHO OFF
SET script_path="%~dp0clean"
IF EXIST %script_path% (
node %script_path% %*
) ELSE (
ECHO.
ECHO ERROR: Could not find 'clean' script in 'cordova' folder, aborting...>&2
EXIT /B 1
)
+22
View File
@@ -0,0 +1,22 @@
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
</widget>
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env node
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var path = require('path');
var check_reqs = require('./check_reqs');
/**
* run
* Creates a zip file int platform/build folder
*/
module.exports.run = function () {
return check_reqs.run();
};
module.exports.help = function () {
console.log('Usage: cordova build browser');
var wwwPath = path.resolve(path.join(__dirname, '../../www'));
console.log("Build will create the packaged app in '" + wwwPath + "'.");
};
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env node
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
// add methods as we determine what are the requirements
module.exports.run = function () {
// caller expects a promise resolved with an array of conditions
return Promise.resolve([]);
};
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env node
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var fs = require('fs');
var shell = require('shelljs');
var path = require('path');
var check_reqs = require('./check_reqs');
var platformBuildDir = path.join('platforms', 'browser', 'www');
var run = function () {
// TODO: everything calls check_reqs ... why?
// Check that requirements are (still) met
if (!check_reqs.run()) {
console.error('Please make sure you meet the software requirements in order to clean an browser cordova project');
process.exit(2);
}
try {
if (fs.existsSync(platformBuildDir)) {
shell.rm('-r', platformBuildDir);
}
} catch (err) {
console.log('could not remove ' + platformBuildDir + ' : ' + err.message);
}
};
module.exports.run = run;
// just on the off chance something is still calling cleanProject, we will leave this here for a while
module.exports.cleanProject = function () {
console.log('lib/clean will soon only export a `run` command, please update to not call `cleanProject`.');
return run();
};
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env node
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var fs = require('fs');
var path = require('path');
var url = require('url');
var cordovaServe = require('cordova-serve');
module.exports.run = function (args) {
// defaults
args.port = args.port || 8000;
args.target = args.target || 'default'; // make default the system browser
args.noLogOutput = args.silent || false;
var wwwPath = path.join(__dirname, '../../www');
var manifestFilePath = path.resolve(path.join(wwwPath, 'manifest.json'));
var startPage;
// get start page from manifest
if (fs.existsSync(manifestFilePath)) {
try {
var manifest = require(manifestFilePath);
startPage = manifest.start_url;
} catch (err) {
console.log('failed to require manifest ... ' + err);
}
}
var server = cordovaServe();
server.servePlatform('browser', { port: args.port, noServerInfo: true, noLogOutput: args.noLogOutput })
.then(function () {
if (!startPage) {
// failing all else, set the default
startPage = 'index.html';
}
var projectUrl = (new url.URL(`http://localhost:${server.port}/${startPage}`)).href;
console.log('startPage = ' + startPage);
console.log('Static file server running @ ' + projectUrl + '\nCTRL + C to shut down');
return server.launchBrowser({ 'target': args.target, 'url': projectUrl });
})
.catch(function (error) {
console.log(error.message || error.toString());
if (server.server) {
server.server.close();
}
});
};
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env node
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
console.log("cordova/log");
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../shelljs/bin/shjs" "$@"
ret=$?
else
node "$basedir/../shelljs/bin/shjs" "$@"
ret=$?
fi
exit $ret
+17
View File
@@ -0,0 +1,17 @@
@ECHO off
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
"%_prog%" "%dp0%\..\shelljs\bin\shjs" %*
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
& "$basedir/node$exe" "$basedir/../shelljs/bin/shjs" $args
$ret=$LASTEXITCODE
} else {
& "node$exe" "$basedir/../shelljs/bin/shjs" $args
$ret=$LASTEXITCODE
}
exit $ret
+8
View File
@@ -0,0 +1,8 @@
/build/*
node_modules
*.node
*.sh
*.swp
.lock*
npm-debug.log
.idea
+47
View File
@@ -0,0 +1,47 @@
bplist-parser
=============
Binary Mac OS X Plist (property list) parser.
## Installation
```bash
$ npm install bplist-parser
```
## Quick Examples
```javascript
var bplist = require('bplist-parser');
bplist.parseFile('myPlist.bplist', function(err, obj) {
if (err) throw err;
console.log(JSON.stringify(obj));
});
```
## License
(The MIT License)
Copyright (c) 2012 Near Infinity Corporation
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+357
View File
@@ -0,0 +1,357 @@
'use strict';
// adapted from http://code.google.com/p/plist/source/browse/trunk/src/com/dd/plist/BinaryPropertyListParser.java
var fs = require('fs');
var bigInt = require("big-integer");
var debug = false;
exports.maxObjectSize = 100 * 1000 * 1000; // 100Meg
exports.maxObjectCount = 32768;
// EPOCH = new SimpleDateFormat("yyyy MM dd zzz").parse("2001 01 01 GMT").getTime();
// ...but that's annoying in a static initializer because it can throw exceptions, ick.
// So we just hardcode the correct value.
var EPOCH = 978307200000;
// UID object definition
var UID = exports.UID = function(id) {
this.UID = id;
}
var parseFile = exports.parseFile = function (fileNameOrBuffer, callback) {
function tryParseBuffer(buffer) {
var err = null;
var result;
try {
result = parseBuffer(buffer);
} catch (ex) {
err = ex;
}
callback(err, result);
}
if (Buffer.isBuffer(fileNameOrBuffer)) {
return tryParseBuffer(fileNameOrBuffer);
} else {
fs.readFile(fileNameOrBuffer, function (err, data) {
if (err) { return callback(err); }
tryParseBuffer(data);
});
}
};
var parseBuffer = exports.parseBuffer = function (buffer) {
var result = {};
// check header
var header = buffer.slice(0, 'bplist'.length).toString('utf8');
if (header !== 'bplist') {
throw new Error("Invalid binary plist. Expected 'bplist' at offset 0.");
}
// Handle trailer, last 32 bytes of the file
var trailer = buffer.slice(buffer.length - 32, buffer.length);
// 6 null bytes (index 0 to 5)
var offsetSize = trailer.readUInt8(6);
if (debug) {
console.log("offsetSize: " + offsetSize);
}
var objectRefSize = trailer.readUInt8(7);
if (debug) {
console.log("objectRefSize: " + objectRefSize);
}
var numObjects = readUInt64BE(trailer, 8);
if (debug) {
console.log("numObjects: " + numObjects);
}
var topObject = readUInt64BE(trailer, 16);
if (debug) {
console.log("topObject: " + topObject);
}
var offsetTableOffset = readUInt64BE(trailer, 24);
if (debug) {
console.log("offsetTableOffset: " + offsetTableOffset);
}
if (numObjects > exports.maxObjectCount) {
throw new Error("maxObjectCount exceeded");
}
// Handle offset table
var offsetTable = [];
for (var i = 0; i < numObjects; i++) {
var offsetBytes = buffer.slice(offsetTableOffset + i * offsetSize, offsetTableOffset + (i + 1) * offsetSize);
offsetTable[i] = readUInt(offsetBytes, 0);
if (debug) {
console.log("Offset for Object #" + i + " is " + offsetTable[i] + " [" + offsetTable[i].toString(16) + "]");
}
}
// Parses an object inside the currently parsed binary property list.
// For the format specification check
// <a href="http://www.opensource.apple.com/source/CF/CF-635/CFBinaryPList.c">
// Apple's binary property list parser implementation</a>.
function parseObject(tableOffset) {
var offset = offsetTable[tableOffset];
var type = buffer[offset];
var objType = (type & 0xF0) >> 4; //First 4 bits
var objInfo = (type & 0x0F); //Second 4 bits
switch (objType) {
case 0x0:
return parseSimple();
case 0x1:
return parseInteger();
case 0x8:
return parseUID();
case 0x2:
return parseReal();
case 0x3:
return parseDate();
case 0x4:
return parseData();
case 0x5: // ASCII
return parsePlistString();
case 0x6: // UTF-16
return parsePlistString(true);
case 0xA:
return parseArray();
case 0xD:
return parseDictionary();
default:
throw new Error("Unhandled type 0x" + objType.toString(16));
}
function parseSimple() {
//Simple
switch (objInfo) {
case 0x0: // null
return null;
case 0x8: // false
return false;
case 0x9: // true
return true;
case 0xF: // filler byte
return null;
default:
throw new Error("Unhandled simple type 0x" + objType.toString(16));
}
}
function bufferToHexString(buffer) {
var str = '';
var i;
for (i = 0; i < buffer.length; i++) {
if (buffer[i] != 0x00) {
break;
}
}
for (; i < buffer.length; i++) {
var part = '00' + buffer[i].toString(16);
str += part.substr(part.length - 2);
}
return str;
}
function parseInteger() {
var length = Math.pow(2, objInfo);
if (length > 4) {
var data = buffer.slice(offset + 1, offset + 1 + length);
var str = bufferToHexString(data);
return bigInt(str, 16);
} if (length < exports.maxObjectSize) {
return readUInt(buffer.slice(offset + 1, offset + 1 + length));
} else {
throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
}
}
function parseUID() {
var length = objInfo + 1;
if (length < exports.maxObjectSize) {
return new UID(readUInt(buffer.slice(offset + 1, offset + 1 + length)));
} else {
throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
}
}
function parseReal() {
var length = Math.pow(2, objInfo);
if (length < exports.maxObjectSize) {
var realBuffer = buffer.slice(offset + 1, offset + 1 + length);
if (length === 4) {
return realBuffer.readFloatBE(0);
}
else if (length === 8) {
return realBuffer.readDoubleBE(0);
}
} else {
throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
}
}
function parseDate() {
if (objInfo != 0x3) {
console.error("Unknown date type :" + objInfo + ". Parsing anyway...");
}
var dateBuffer = buffer.slice(offset + 1, offset + 9);
return new Date(EPOCH + (1000 * dateBuffer.readDoubleBE(0)));
}
function parseData() {
var dataoffset = 1;
var length = objInfo;
if (objInfo == 0xF) {
var int_type = buffer[offset + 1];
var intType = (int_type & 0xF0) / 0x10;
if (intType != 0x1) {
console.error("0x4: UNEXPECTED LENGTH-INT TYPE! " + intType);
}
var intInfo = int_type & 0x0F;
var intLength = Math.pow(2, intInfo);
dataoffset = 2 + intLength;
if (intLength < 3) {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
} else {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
}
}
if (length < exports.maxObjectSize) {
return buffer.slice(offset + dataoffset, offset + dataoffset + length);
} else {
throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
}
}
function parsePlistString (isUtf16) {
isUtf16 = isUtf16 || 0;
var enc = "utf8";
var length = objInfo;
var stroffset = 1;
if (objInfo == 0xF) {
var int_type = buffer[offset + 1];
var intType = (int_type & 0xF0) / 0x10;
if (intType != 0x1) {
console.err("UNEXPECTED LENGTH-INT TYPE! " + intType);
}
var intInfo = int_type & 0x0F;
var intLength = Math.pow(2, intInfo);
var stroffset = 2 + intLength;
if (intLength < 3) {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
} else {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
}
}
// length is String length -> to get byte length multiply by 2, as 1 character takes 2 bytes in UTF-16
length *= (isUtf16 + 1);
if (length < exports.maxObjectSize) {
var plistString = new Buffer(buffer.slice(offset + stroffset, offset + stroffset + length));
if (isUtf16) {
plistString = swapBytes(plistString);
enc = "ucs2";
}
return plistString.toString(enc);
} else {
throw new Error("To little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
}
}
function parseArray() {
var length = objInfo;
var arrayoffset = 1;
if (objInfo == 0xF) {
var int_type = buffer[offset + 1];
var intType = (int_type & 0xF0) / 0x10;
if (intType != 0x1) {
console.error("0xa: UNEXPECTED LENGTH-INT TYPE! " + intType);
}
var intInfo = int_type & 0x0F;
var intLength = Math.pow(2, intInfo);
arrayoffset = 2 + intLength;
if (intLength < 3) {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
} else {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
}
}
if (length * objectRefSize > exports.maxObjectSize) {
throw new Error("To little heap space available!");
}
var array = [];
for (var i = 0; i < length; i++) {
var objRef = readUInt(buffer.slice(offset + arrayoffset + i * objectRefSize, offset + arrayoffset + (i + 1) * objectRefSize));
array[i] = parseObject(objRef);
}
return array;
}
function parseDictionary() {
var length = objInfo;
var dictoffset = 1;
if (objInfo == 0xF) {
var int_type = buffer[offset + 1];
var intType = (int_type & 0xF0) / 0x10;
if (intType != 0x1) {
console.error("0xD: UNEXPECTED LENGTH-INT TYPE! " + intType);
}
var intInfo = int_type & 0x0F;
var intLength = Math.pow(2, intInfo);
dictoffset = 2 + intLength;
if (intLength < 3) {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
} else {
length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
}
}
if (length * 2 * objectRefSize > exports.maxObjectSize) {
throw new Error("To little heap space available!");
}
if (debug) {
console.log("Parsing dictionary #" + tableOffset);
}
var dict = {};
for (var i = 0; i < length; i++) {
var keyRef = readUInt(buffer.slice(offset + dictoffset + i * objectRefSize, offset + dictoffset + (i + 1) * objectRefSize));
var valRef = readUInt(buffer.slice(offset + dictoffset + (length * objectRefSize) + i * objectRefSize, offset + dictoffset + (length * objectRefSize) + (i + 1) * objectRefSize));
var key = parseObject(keyRef);
var val = parseObject(valRef);
if (debug) {
console.log(" DICT #" + tableOffset + ": Mapped " + key + " to " + val);
}
dict[key] = val;
}
return dict;
}
}
return [ parseObject(topObject) ];
};
function readUInt(buffer, start) {
start = start || 0;
var l = 0;
for (var i = start; i < buffer.length; i++) {
l <<= 8;
l |= buffer[i] & 0xFF;
}
return l;
}
// we're just going to toss the high order bits because javascript doesn't have 64-bit ints
function readUInt64BE(buffer, start) {
var data = buffer.slice(start, start + 8);
return data.readUInt32BE(4, 8);
}
function swapBytes(buffer) {
var len = buffer.length;
for (var i = 0; i < len; i += 2) {
var a = buffer[i];
buffer[i] = buffer[i+1];
buffer[i+1] = a;
}
return buffer;
}
+62
View File
@@ -0,0 +1,62 @@
{
"_args": [
[
"bplist-parser@0.1.1",
"C:\\Users\\tiago.kayaya\\development\\gabinete-digital"
]
],
"_development": true,
"_from": "bplist-parser@0.1.1",
"_id": "bplist-parser@0.1.1",
"_inBundle": false,
"_integrity": "sha1-1g1dzCDLptx+HymbNdPh+V2vuuY=",
"_location": "/cordova-browser/bplist-parser",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "bplist-parser@0.1.1",
"name": "bplist-parser",
"escapedName": "bplist-parser",
"rawSpec": "0.1.1",
"saveSpec": null,
"fetchSpec": "0.1.1"
},
"_requiredBy": [
"/cordova-browser/cordova-common"
],
"_resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.1.1.tgz",
"_spec": "0.1.1",
"_where": "C:\\Users\\tiago.kayaya\\development\\gabinete-digital",
"author": {
"name": "Joe Ferner",
"email": "joe.ferner@nearinfinity.com"
},
"bugs": {
"url": "https://github.com/nearinfinity/node-bplist-parser/issues"
},
"dependencies": {
"big-integer": "^1.6.7"
},
"description": "Binary plist parser.",
"devDependencies": {
"nodeunit": "~0.9.1"
},
"homepage": "https://github.com/nearinfinity/node-bplist-parser#readme",
"keywords": [
"bplist",
"plist",
"parser"
],
"license": "MIT",
"main": "bplistParser.js",
"name": "bplist-parser",
"repository": {
"type": "git",
"url": "git+https://github.com/nearinfinity/node-bplist-parser.git"
},
"scripts": {
"test": "./node_modules/nodeunit/bin/nodeunit test"
},
"version": "0.1.1"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>zero</key>
<integer>0</integer>
<key>int64item</key>
<integer>12345678901234567890</integer>
</dict>
</plist>
+159
View File
@@ -0,0 +1,159 @@
'use strict';
// tests are adapted from https://github.com/TooTallNate/node-plist
var path = require('path');
var nodeunit = require('nodeunit');
var bplist = require('../');
module.exports = {
'iTunes Small': function (test) {
var file = path.join(__dirname, "iTunes-small.bplist");
var startTime1 = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime1) + 'ms');
var dict = dicts[0];
test.equal(dict['Application Version'], "9.0.3");
test.equal(dict['Library Persistent ID'], "6F81D37F95101437");
test.done();
});
},
'sample1': function (test) {
var file = path.join(__dirname, "sample1.bplist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.equal(dict['CFBundleIdentifier'], 'com.apple.dictionary.MySample');
test.done();
});
},
'sample2': function (test) {
var file = path.join(__dirname, "sample2.bplist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.equal(dict['PopupMenu'][2]['Key'], "\n #import <Cocoa/Cocoa.h>\n\n#import <MacRuby/MacRuby.h>\n\nint main(int argc, char *argv[])\n{\n return macruby_main(\"rb_main.rb\", argc, argv);\n}\n");
test.done();
});
},
'airplay': function (test) {
var file = path.join(__dirname, "airplay.bplist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.equal(dict['duration'], 5555.0495000000001);
test.equal(dict['position'], 4.6269989039999997);
test.done();
});
},
'utf16': function (test) {
var file = path.join(__dirname, "utf16.bplist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.equal(dict['CFBundleName'], 'sellStuff');
test.equal(dict['CFBundleShortVersionString'], '2.6.1');
test.equal(dict['NSHumanReadableCopyright'], '©2008-2012, sellStuff, Inc.');
test.done();
});
},
'utf16chinese': function (test) {
var file = path.join(__dirname, "utf16_chinese.plist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.equal(dict['CFBundleName'], '天翼阅读');
test.equal(dict['CFBundleDisplayName'], '天翼阅读');
test.done();
});
},
'uid': function (test) {
var file = path.join(__dirname, "uid.bplist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.deepEqual(dict['$objects'][1]['NS.keys'], [{UID:2}, {UID:3}, {UID:4}]);
test.deepEqual(dict['$objects'][1]['NS.objects'], [{UID: 5}, {UID:6}, {UID:7}]);
test.deepEqual(dict['$top']['root'], {UID:1});
test.done();
});
},
'int64': function (test) {
var file = path.join(__dirname, "int64.bplist");
var startTime = new Date();
bplist.parseFile(file, function (err, dicts) {
if (err) {
throw err;
}
var endTime = new Date();
console.log('Parsed "' + file + '" in ' + (endTime - startTime) + 'ms');
var dict = dicts[0];
test.equal(dict['zero'], '0');
test.equal(dict['int64item'], '12345678901234567890');
test.done();
});
}
};
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
spec/fixtures/*
+10
View File
@@ -0,0 +1,10 @@
root: true
extends: semistandard
rules:
indent:
- error
- 4
camelcase: off
no-unused-vars:
- error
- args: after-used
@@ -0,0 +1,42 @@
<!--
Please have a look at the issue templates you get when you click "New issue" in the GitHub UI.
We very much prefer issues created by using one of these templates.
-->
### Issue Type
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] Bug Report
- [ ] Feature Request
- [ ] Support Question
## Description
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an `x` in the `[ ]` like so: `[x]` -->
- [ ] I searched for already existing GitHub issues about this
- [ ] I updated all Cordova tooling to their most recent version
- [ ] I included all the necessary information above
@@ -0,0 +1,50 @@
---
name: 🐛 Bug Report
about: If something isn't working as expected.
---
# Bug Report
## Problem
### What is expected to happen?
### What does actually happen?
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] I searched for existing GitHub issues
- [ ] I updated all Cordova tooling to most recent version
- [ ] I included all the necessary information above
@@ -0,0 +1,29 @@
---
name: 🚀 Feature Request
about: A suggestion for a new functionality
---
# Feature Request
## Motivation Behind Feature
<!-- Why should this feature be implemented? What problem does it solve? -->
## Feature Description
<!--
Describe your feature request in detail
Please provide any code examples or screenshots of what this feature would look like
Are there any drawbacks? Will this break anything for existing users?
-->
## Alternatives or Workarounds
<!--
Describe alternatives or workarounds you are currently using
Are there ways to do this with existing functionality?
-->
@@ -0,0 +1,27 @@
---
name: 💬 Support Question
about: If you have a question, please check out our Slack or StackOverflow!
---
<!------------^ Click "Preview" for a nicer view! -->
Apache Cordova uses GitHub Issues as a feature request and bug tracker _only_.
For usage and support questions, please check out the resources below. Thanks!
---
You can get answers to your usage and support questions about **Apache Cordova** on:
* Slack Community Chat: https://cordova.slack.com (you can sign-up at http://slack.cordova.io/)
* StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova`
---
If you are using a tool that uses Cordova internally, like e.g. Ionic, check their support channels:
* **Ionic Framework**
* [Ionic Community Forum](https://forum.ionicframework.com/)
* [Ionic Worldwide Slack](https://ionicworldwide.herokuapp.com/)
* **PhoneGap**
* [PhoneGap Developer Community](https://forums.adobe.com/community/phonegap)
@@ -0,0 +1,35 @@
<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist is intended as a quick reference, for complete details please see our Contributor Guidelines:
http://cordova.apache.org/contribute/contribute_guidelines.html
Thanks!
-->
### Platforms affected
### Motivation and Context
<!-- Why is this change required? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here. -->
### Description
<!-- Describe your changes in detail -->
### Testing
<!-- Please describe in detail how you tested your changes. -->
### Checklist
- [ ] I've run the tests to see all new and existing tests pass
- [ ] I added automated test coverage as appropriate for this change
- [ ] Commit is prefixed with `(platform)` if this change only applies to one platform (e.g. `(android)`)
- [ ] If this Pull Request resolves an issue, I linked to the issue in the text above (and used the correct [keyword to close issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/))
- [ ] I've updated the documentation if necessary
+5
View File
@@ -0,0 +1,5 @@
fixtures
coverage
jasmine.json
appveyor.yml
package-lock.json
+22
View File
@@ -0,0 +1,22 @@
language: node_js
sudo: false
git:
depth: 10
node_js:
- 6
- 8
- 10
- 12
install:
- npm install
- npm install -g codecov
script:
- npm test
- npm run cover
after_script:
- codecov
+155
View File
@@ -0,0 +1,155 @@
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
[![Build status](https://ci.appveyor.com/api/projects/status/wxkmo0jalsr8gane?svg=true)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-common/branch/master)
[![Build Status](https://travis-ci.org/apache/cordova-common.svg?branch=master)](https://travis-ci.org/apache/cordova-common)
[![NPM](https://nodei.co/npm/cordova-common.png)](https://nodei.co/npm/cordova-common/)
# cordova-common
Exposes shared functionality used by [cordova-lib](https://github.com/apache/cordova-lib/) and Cordova platforms.
## Exposed APIs
### `events`
Represents special instance of NodeJS EventEmitter which is intended to be used to post events to cordova-lib and cordova-cli
Usage:
```js
var events = require('cordova-common').events;
events.emit('warn', 'Some warning message')
```
There are the following events supported by cordova-cli: `verbose`, `log`, `info`, `warn`, `error`.
### `CordovaError`
An error class used by Cordova to throw cordova-specific errors. The CordovaError class is inherited from Error, so CordovaError instances is also valid Error instances (`instanceof` check succeeds).
Usage:
```js
var CordovaError = require('cordova-common').CordovaError;
throw new CordovaError('Some error message', SOME_ERR_CODE);
```
See [CordovaError](src/CordovaError/CordovaError.js) for supported error codes.
### `ConfigParser`
Exposes functionality to deal with cordova project `config.xml` files. For ConfigParser API reference check [ConfigParser Readme](src/ConfigParser/README.md).
Usage:
```js
var ConfigParser = require('cordova-common').ConfigParser;
var appConfig = new ConfigParser('path/to/cordova-app/config.xml');
console.log(appconfig.name() + ':' + appConfig.version());
```
### `PluginInfoProvider` and `PluginInfo`
`PluginInfo` is a wrapper for cordova plugins' `plugin.xml` files. This class may be instantiated directly or via `PluginInfoProvider`. The difference is that `PluginInfoProvider` caches `PluginInfo` instances based on plugin source directory.
Usage:
```js
var PluginInfo: require('cordova-common').PluginInfo;
var PluginInfoProvider: require('cordova-common').PluginInfoProvider;
// The following instances are equal
var plugin1 = new PluginInfo('path/to/plugin_directory');
var plugin2 = new PluginInfoProvider().get('path/to/plugin_directory');
console.log('The plugin ' + plugin1.id + ' has version ' + plugin1.version)
```
### `ActionStack`
Utility module for dealing with sequential tasks. Provides a set of tasks that are needed to be done and reverts all tasks that are already completed if one of those tasks fail to complete. Used internally by cordova-lib and platform's plugin installation routines.
Usage:
```js
var ActionStack = require('cordova-common').ActionStack;
var stack = new ActionStack()
var action1 = stack.createAction(task1, [<task parameters>], task1_reverter, [<reverter_parameters>]);
var action2 = stack.createAction(task2, [<task parameters>], task2_reverter, [<reverter_parameters>]);
stack.push(action1);
stack.push(action2);
stack.process()
.then(function() {
// all actions succeded
})
.catch(function(error){
// One of actions failed with error
})
```
### `superspawn`
Module for spawning child processes with some advanced logic.
Usage:
```js
var superspawn = require('cordova-common').superspawn;
superspawn.spawn('adb', ['devices'])
.progress(function(data){
if (data.stderr)
console.error('"adb devices" raised an error: ' + data.stderr);
})
.then(function(devices){
// Do something...
})
```
### `xmlHelpers`
A set of utility methods for dealing with XML files.
Usage:
```js
var xml = require('cordova-common').xmlHelpers;
var xmlDoc1 = xml.parseElementtreeSync('some/xml/file');
var xmlDoc2 = xml.parseElementtreeSync('another/xml/file');
xml.mergeXml(doc1, doc2); // doc2 now contains all the nodes from doc1
```
### Other APIs
The APIs listed below are also exposed but are intended to be only used internally by cordova plugin installation routines.
```
PlatformJson
ConfigChanges
ConfigKeeper
ConfigFile
mungeUtil
```
## Setup
* Clone this repository onto your local machine
`git clone https://github.com/apache/cordova-common.git`
* Navigate to cordova-common directory, install dependencies and npm-link
`cd cordova-common && npm install && npm link`
* Navigate to cordova-lib directory and link cordova-common
`cd <cordova-lib directory> && npm link cordova-common && npm install`
+175
View File
@@ -0,0 +1,175 @@
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Cordova-common Release Notes
### 3.2.1 (Oct 28, 2019)
* [GH-78](https://github.com/apache/cordova-common/pull/78) (windows) Add `.jsproj` as file extension for XML files ([GH-62](https://github.com/apache/cordova-common/pull/62))
* [GH-89](https://github.com/apache/cordova-common/pull/89) revert: ([GH-24](https://github.com/apache/cordova-common/pull/24)) [CB-14108](https://issues.apache.org/jira/browse/CB-14108) fix incorrect count in `config_munge`
* [GH-82](https://github.com/apache/cordova-common/pull/82) General cleanup with eslint updates
* [GH-86](https://github.com/apache/cordova-common/pull/86) eslint cleanup fixes: `operator-linebreak`
* [GH-81](https://github.com/apache/cordova-common/pull/81) remove `no-throw-literal` lint exception not needed
* [GH-83](https://github.com/apache/cordova-common/pull/83) Fix ESLint violations where applicable
* [GH-80](https://github.com/apache/cordova-common/pull/80) Update to jasmine 3.4 & fix resulting spec failures
* [GH-79](https://github.com/apache/cordova-common/pull/79) Promise handling cleanup in specs
* [GH-77](https://github.com/apache/cordova-common/pull/77) Do not ignore AppVeyor failures on Node.js 12
### 3.2.0 (Jun 12, 2019)
* (ios) plist document not indented with tabs ([#69](https://github.com/apache/cordova-common/pull/69))
* Update fs-extra to v8 ([#70](https://github.com/apache/cordova-common/pull/70))
* Add example usage of podspec declarations ([#67](https://github.com/apache/cordova-common/pull/67))
* implement setPreference and setPlatformPreference ([#63](https://github.com/apache/cordova-common/pull/63))
* Catch leaked exceptions in superspawn and convert them to rejections ([#66](https://github.com/apache/cordova-common/pull/66))
### 3.1.0 (Dec 24, 2018)
* Update Cordova events into a real singleton class ([#60](https://github.com/apache/cordova-common/pull/60))
* Refactor CordovaLogger to singleton class ([#53](https://github.com/apache/cordova-common/pull/53))
### 3.0.0 (Nov 05, 2018)
* [CB-14166](https://issues.apache.org/jira/browse/CB-14166) Use `cross-spawn` for platform-independent spawning
* add `PluginInfo.getPodSpecs` method
* [CB-13496](https://issues.apache.org/jira/browse/CB-13496) Fix greedy regex in plist-helpers
* [CB-14108](https://issues.apache.org/jira/browse/CB-14108) fix incorrect count in config_munge in ios.json and android.json
* [CB-13685](https://issues.apache.org/jira/browse/CB-13685) **Android**: Update ConfigParser for Adaptive Icons
* [CB-10071](https://issues.apache.org/jira/browse/CB-10071) Add BridgingHeader type attributes for header-file
* [CB-12016](https://issues.apache.org/jira/browse/CB-12016) Removed cordova-registry-mapper dependency
* [CB-14099](https://issues.apache.org/jira/browse/CB-14099) **osx**: Fixed Resolve Config Path for OSX
* [CB-14140](https://issues.apache.org/jira/browse/CB-14140) Replace shelljs calls with fs-extra & which
### 2.2.2 (May 30, 2018)
* [CB-13979](https://issues.apache.org/jira/browse/CB-13979) More consistency for `config.xml` lookups
* [CB-14064](https://issues.apache.org/jira/browse/CB-14064) Remove Node 4 from CI matrix
* [CB-14088](https://issues.apache.org/jira/browse/CB-14088) Update dependencies
* [CB-11691](https://issues.apache.org/jira/browse/CB-11691) Fix for modifying binary plists
* [CB-13770](https://issues.apache.org/jira/browse/CB-13770) Warn when <edit-config> or <config-file> not found
* [CB-13471](https://issues.apache.org/jira/browse/CB-13471) Fix tests and path issues for **Windows**
* [CB-13471](https://issues.apache.org/jira/browse/CB-13471) added unit test for config file provider
* [CB-13744](https://issues.apache.org/jira/browse/CB-13744) Recognize storyboards as XML files
* [CB-13674](https://issues.apache.org/jira/browse/CB-13674) Incremented package version to -dev
### 2.2.1 (Dec 14, 2017)
* [CB-13674](https://issues.apache.org/jira/browse/CB-13674): updated dependencies
### 2.2.0 (Nov 22, 2017)
* [CB-13471](https://issues.apache.org/jira/browse/CB-13471) File Provider fix belongs in cordova-common
* [CB-11244](https://issues.apache.org/jira/browse/CB-11244) Spot fix for upcoming `cordova-android@7` changes. https://github.com/apache/cordova-android/pull/389
### 2.1.1 (Oct 04, 2017)
* [CB-13145](https://issues.apache.org/jira/browse/CB-13145) added `getFrameworks` to unit tests
* [CB-13145](https://issues.apache.org/jira/browse/CB-13145) added variable replacing to framework tag
### 2.1.0 (August 30, 2017)
* [CB-13145](https://issues.apache.org/jira/browse/CB-13145) added variable replacing to `framework` tag
* [CB-13211](https://issues.apache.org/jira/browse/CB-13211) Add `allows-arbitrary-loads-for-media` attribute parsing for `getAccesses`
* [CB-11968](https://issues.apache.org/jira/browse/CB-11968) Added support for `<config-file>` in `config.xml`
* [CB-12895](https://issues.apache.org/jira/browse/CB-12895) set up `eslint` and removed `jshint`
* [CB-12785](https://issues.apache.org/jira/browse/CB-12785) added `.gitignore`, `travis`, and `appveyor` support
* [CB-12250](https://issues.apache.org/jira/browse/CB-12250) & [CB-12409](https://issues.apache.org/jira/browse/CB-12409) *iOS*: Fix bug with escaping properties from `plist` file
* [CB-12762](https://issues.apache.org/jira/browse/CB-12762) updated `common`, `fetch`, and `serve` `pkgJson` to point `pkgJson` repo items to github mirrors
* [CB-12766](https://issues.apache.org/jira/browse/CB-12766) Consistently write `JSON` with 2 spaces indentation
### 2.0.3 (May 02, 2017)
* [CB-8978](https://issues.apache.org/jira/browse/CB-8978) Add option to get `resource-file` from `root`
* [CB-11908](https://issues.apache.org/jira/browse/CB-11908) Add tests for `edit-config` in `config.xml`
* [CB-12665](https://issues.apache.org/jira/browse/CB-12665) removed `enginestrict` since it is deprecated
### 2.0.2 (Apr 14, 2017)
* [CB-11233](https://issues.apache.org/jira/browse/CB-11233) - Support installing frameworks into 'Embedded Binaries' section of the Xcode project
* [CB-10438](https://issues.apache.org/jira/browse/CB-10438) - Install correct dependency version. Removed shell.remove, added pkg.json to dependency tests 1-3, and updated install.js (.replace) to fix tests in uninstall.spec.js and update to workw with jasmine 2.0
* [CB-11120](https://issues.apache.org/jira/browse/CB-11120) - Allow short/display name in config.xml
* [CB-11346](https://issues.apache.org/jira/browse/CB-11346) - Remove known platforms check
* [CB-11977](https://issues.apache.org/jira/browse/CB-11977) - updated engines and enginescript for common, fetch, and serve
### 2.0.1 (Mar 09, 2017)
* [CB-12557](https://issues.apache.org/jira/browse/CB-12557) add both stdout and stderr properties to the error object passed to superspawn reject handler.
### 2.0.0 (Jan 17, 2017)
* [CB-8978](https://issues.apache.org/jira/browse/CB-8978) Add `resource-file` parsing to `config.xml`
* [CB-12018](https://issues.apache.org/jira/browse/CB-12018): updated `jshint` and updated tests to work with `jasmine@2` instead of `jasmine-node`
* [CB-12163](https://issues.apache.org/jira/browse/CB-12163) Add reference attrib to `resource-file` for **Windows**
* Move windows-specific logic to `cordova-windows`
* [CB-12189](https://issues.apache.org/jira/browse/CB-12189) Add implementation attribute to framework
### 1.5.1 (Oct 12, 2016)
* [CB-12002](https://issues.apache.org/jira/browse/CB-12002) Add `getAllowIntents()` to `ConfigParser`
* [CB-11998](https://issues.apache.org/jira/browse/CB-11998) `cordova platform add` error with `cordova-common@1.5.0`
### 1.5.0 (Oct 06, 2016)
* [CB-11776](https://issues.apache.org/jira/browse/CB-11776) Add test case for different `edit-config` targets
* [CB-11908](https://issues.apache.org/jira/browse/CB-11908) Add `edit-config` to `config.xml`
* [CB-11936](https://issues.apache.org/jira/browse/CB-11936) Support four new **App Transport Security (ATS)** keys
* update `config.xml` location if it is a **Android Studio** project.
* use `array` methods and `object.keys` for iterating. avoiding `for-in` loops
* [CB-11517](https://issues.apache.org/jira/browse/CB-11517) Allow `.folder` matches
* [CB-11776](https://issues.apache.org/jira/browse/CB-11776) check `edit-config` target exists
### 1.4.1 (Aug 09, 2016)
* Add general purpose `ConfigParser.getAttribute` API
* [CB-11653](https://issues.apache.org/jira/browse/CB-11653) moved `findProjectRoot` from `cordova-lib` to `cordova-common`
* [CB-11636](https://issues.apache.org/jira/browse/CB-11636) Handle attributes with quotes correctly
* [CB-11645](https://issues.apache.org/jira/browse/CB-11645) added check to see if `getEditConfig` exists before trying to use it
* [CB-9825](https://issues.apache.org/jira/browse/CB-9825) framework tag spec parsing
### 1.4.0 (Jul 12, 2016)
* [CB-11023](https://issues.apache.org/jira/browse/CB-11023) Add edit-config functionality
### 1.3.0 (May 12, 2016)
* [CB-11259](https://issues.apache.org/jira/browse/CB-11259): Improving prepare and build logging
* [CB-11194](https://issues.apache.org/jira/browse/CB-11194) Improve cordova load time
* [CB-1117](https://issues.apache.org/jira/browse/CB-1117) Add `FileUpdater` module to `cordova-common`.
* [CB-11131](https://issues.apache.org/jira/browse/CB-11131) Fix `TypeError: message.toUpperCase` is not a function in `CordovaLogger`
### 1.2.0 (Apr 18, 2016)
* [CB-11022](https://issues.apache.org/jira/browse/CB-11022) Save modulesMetadata to both www and platform_www when necessary
* [CB-10833](https://issues.apache.org/jira/browse/CB-10833) Deduplicate common logic for plugin installation/uninstallation
* [CB-10822](https://issues.apache.org/jira/browse/CB-10822) Manage plugins/modules metadata using PlatformJson
* [CB-10940](https://issues.apache.org/jira/browse/CB-10940) Can't add Android platform from path
* [CB-10965](https://issues.apache.org/jira/browse/CB-10965) xml helper allows multiple instances to be merge in config.xml
### 1.1.1 (Mar 18, 2016)
* [CB-10694](https://issues.apache.org/jira/browse/CB-10694) Update test to reflect merging of [CB-9264](https://issues.apache.org/jira/browse/CB-9264) fix
* [CB-10694](https://issues.apache.org/jira/browse/CB-10694) Platform-specific configuration preferences don't override global settings
* [CB-9264](https://issues.apache.org/jira/browse/CB-9264) Duplicate entries in `config.xml`
* [CB-10791](https://issues.apache.org/jira/browse/CB-10791) Add `adjustLoggerLevel` to `cordova-common.CordovaLogger`
* [CB-10662](https://issues.apache.org/jira/browse/CB-10662) Add tests for `ConfigParser.getStaticResources`
* [CB-10622](https://issues.apache.org/jira/browse/CB-10622) fix target attribute being ignored for images in `config.xml`.
* [CB-10583](https://issues.apache.org/jira/browse/CB-10583) Protect plugin preferences from adding extra Array properties.
### 1.1.0 (Feb 16, 2016)
* [CB-10482](https://issues.apache.org/jira/browse/CB-10482) Remove references to windows8 from cordova-lib/cli
* [CB-10430](https://issues.apache.org/jira/browse/CB-10430) Adds forwardEvents method to easily connect two EventEmitters
* [CB-10176](https://issues.apache.org/jira/browse/CB-10176) Adds CordovaLogger class, based on logger module from cordova-cli
* [CB-10052](https://issues.apache.org/jira/browse/CB-10052) Expose child process' io streams via promise progress notification
* [CB-10497](https://issues.apache.org/jira/browse/CB-10497) Prefer .bat over .cmd on windows platform
* [CB-9984](https://issues.apache.org/jira/browse/CB-9984) Bumps plist version and fixes failing cordova-common test
### 1.0.0 (Oct 29, 2015)
* [CB-9890](https://issues.apache.org/jira/browse/CB-9890) Documents cordova-common
* [CB-9598](https://issues.apache.org/jira/browse/CB-9598) Correct cordova-lib -> cordova-common in README
* Pick ConfigParser changes from apache@0c3614e
* [CB-9743](https://issues.apache.org/jira/browse/CB-9743) Removes system frameworks handling from ConfigChanges
* [CB-9598](https://issues.apache.org/jira/browse/CB-9598) Cleans out code which has been moved to `cordova-common`
* Pick ConfigParser changes from apache@ddb027b
* Picking CordovaError changes from apache@a3b1fca
* [CB-9598](https://issues.apache.org/jira/browse/CB-9598) Adds tests and fixtures based on existing cordova-lib ones
* [CB-9598](https://issues.apache.org/jira/browse/CB-9598) Initial implementation for cordova-common
+22
View File
@@ -0,0 +1,22 @@
# appveyor file
# http://www.appveyor.com/docs/appveyor-yml
shallow_clone: true
environment:
matrix:
- nodejs_version: 6
- nodejs_version: 8
- nodejs_version: 10
- nodejs_version: 12
install:
- ps: Install-Product node $env:nodejs_version
- npm install
build: off
test_script:
- node --version
- npm --version
- npm test
@@ -0,0 +1,47 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var addProperty = require('./src/util/addProperty');
module.exports = { };
addProperty(module, 'events', './src/events');
addProperty(module, 'superspawn', './src/superspawn');
addProperty(module, 'ActionStack', './src/ActionStack');
addProperty(module, 'CordovaError', './src/CordovaError/CordovaError');
addProperty(module, 'CordovaLogger', './src/CordovaLogger');
addProperty(module, 'CordovaCheck', './src/CordovaCheck');
addProperty(module, 'CordovaExternalToolErrorContext', './src/CordovaError/CordovaExternalToolErrorContext');
addProperty(module, 'PlatformJson', './src/PlatformJson');
addProperty(module, 'ConfigParser', './src/ConfigParser/ConfigParser');
addProperty(module, 'FileUpdater', './src/FileUpdater');
addProperty(module, 'PluginInfo', './src/PluginInfo/PluginInfo');
addProperty(module, 'PluginInfoProvider', './src/PluginInfo/PluginInfoProvider');
addProperty(module, 'PluginManager', './src/PluginManager');
addProperty(module, 'ConfigChanges', './src/ConfigChanges/ConfigChanges');
addProperty(module, 'ConfigKeeper', './src/ConfigChanges/ConfigKeeper');
addProperty(module, 'ConfigFile', './src/ConfigChanges/ConfigFile');
addProperty(module, 'mungeUtil', './src/ConfigChanges/munge-util');
addProperty(module, 'xmlHelpers', './src/util/xml-helpers');
+88
View File
@@ -0,0 +1,88 @@
{
"_args": [
[
"cordova-common@3.2.1",
"C:\\Users\\tiago.kayaya\\development\\gabinete-digital"
]
],
"_development": true,
"_from": "cordova-common@3.2.1",
"_id": "cordova-common@3.2.1",
"_inBundle": false,
"_integrity": "sha512-xg0EnjnA6EipxXG8cupdlYQYeDA6+ghbN+Pjq88xN1LInwP6Bo7IyGBdSV5QnfjOvzShF9BBwSxBAv0FOO0C2Q==",
"_location": "/cordova-browser/cordova-common",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "cordova-common@3.2.1",
"name": "cordova-common",
"escapedName": "cordova-common",
"rawSpec": "3.2.1",
"saveSpec": null,
"fetchSpec": "3.2.1"
},
"_requiredBy": [
"/cordova-browser"
],
"_resolved": "https://registry.npmjs.org/cordova-common/-/cordova-common-3.2.1.tgz",
"_spec": "3.2.1",
"_where": "C:\\Users\\tiago.kayaya\\development\\gabinete-digital",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://issues.apache.org/jira/browse/CB",
"email": "dev@cordova.apache.org"
},
"contributors": [],
"dependencies": {
"ansi": "^0.3.1",
"bplist-parser": "^0.1.0",
"cross-spawn": "^6.0.5",
"elementtree": "0.1.7",
"endent": "^1.1.1",
"fs-extra": "^8.0.0",
"glob": "^7.1.2",
"minimatch": "^3.0.0",
"plist": "^3.0.1",
"q": "^1.4.1",
"strip-bom": "^3.0.0",
"underscore": "^1.8.3",
"which": "^1.3.0"
},
"description": "Apache Cordova tools and platforms shared routines",
"devDependencies": {
"eslint": "^5.0.0",
"eslint-config-semistandard": "^14.0.0",
"eslint-config-standard": "^13.0.1",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-promise": "^4.0.0",
"eslint-plugin-standard": "^4.0.0",
"istanbul": "^0.4.5",
"jasmine": "^3.4.0",
"jasmine-spec-reporter": "^4.2.1",
"osenv": "^0.1.3",
"promise-matchers": "^0.9.6",
"rewire": "^4.0.1"
},
"engines": {
"node": ">=6.0.0"
},
"homepage": "https://github.com/apache/cordova-common#readme",
"license": "Apache-2.0",
"main": "cordova-common.js",
"name": "cordova-common",
"repository": {
"type": "git",
"url": "git+https://github.com/apache/cordova-common.git"
},
"scripts": {
"cover": "istanbul cover --root src --print detail jasmine",
"eslint": "eslint src spec",
"jasmine": "jasmine JASMINE_CONFIG_PATH=spec/support/jasmine.json",
"test": "npm run eslint && npm run jasmine"
},
"version": "3.2.1"
}
@@ -0,0 +1,85 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/* jshint quotmark:false */
var events = require('./events');
var Q = require('q');
function ActionStack () {
this.stack = [];
this.completed = [];
}
ActionStack.prototype = {
createAction: function (handler, action_params, reverter, revert_params) {
return {
handler: {
run: handler,
params: action_params
},
reverter: {
run: reverter,
params: revert_params
}
};
},
push: function (tx) {
this.stack.push(tx);
},
// Returns a promise.
process: function (platform) {
events.emit('verbose', 'Beginning processing of action stack for ' + platform + ' project...');
while (this.stack.length) {
var action = this.stack.shift();
var handler = action.handler.run;
var action_params = action.handler.params;
try {
handler.apply(null, action_params);
} catch (e) {
events.emit('warn', 'Error during processing of action! Attempting to revert...');
this.stack.unshift(action);
var issue = 'Uh oh!\n';
// revert completed tasks
while (this.completed.length) {
var undo = this.completed.shift();
var revert = undo.reverter.run;
var revert_params = undo.reverter.params;
try {
revert.apply(null, revert_params);
} catch (err) {
events.emit('warn', 'Error during reversion of action! We probably really messed up your project now, sorry! D:');
issue += 'A reversion action failed: ' + err.message + '\n';
}
}
e.message = issue + e.message;
return Q.reject(e);
}
this.completed.push(action);
}
events.emit('verbose', 'Action stack processing complete.');
return Q();
}
};
module.exports = ActionStack;
@@ -0,0 +1,426 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
* This module deals with shared configuration / dependency "stuff". That is:
* - XML configuration files such as config.xml, AndroidManifest.xml or WMAppManifest.xml.
* - plist files in iOS
* Essentially, any type of shared resources that we need to handle with awareness
* of how potentially multiple plugins depend on a single shared resource, should be
* handled in this module.
*
* The implementation uses an object as a hash table, with "leaves" of the table tracking
* reference counts.
*/
var path = require('path');
var et = require('elementtree');
var ConfigKeeper = require('./ConfigKeeper');
var events = require('../events');
var mungeutil = require('./munge-util');
var xml_helpers = require('../util/xml-helpers');
exports.PlatformMunger = PlatformMunger;
exports.process = function (plugins_dir, project_dir, platform, platformJson, pluginInfoProvider) {
var munger = new PlatformMunger(platform, project_dir, platformJson, pluginInfoProvider);
munger.process(plugins_dir);
munger.save_all();
};
/******************************************************************************
* PlatformMunger class
*
* Can deal with config file of a single project.
* Parsed config files are cached in a ConfigKeeper object.
******************************************************************************/
function PlatformMunger (platform, project_dir, platformJson, pluginInfoProvider) {
this.platform = platform;
this.project_dir = project_dir;
this.config_keeper = new ConfigKeeper(project_dir);
this.platformJson = platformJson;
this.pluginInfoProvider = pluginInfoProvider;
}
// Write out all unsaved files.
PlatformMunger.prototype.save_all = PlatformMunger_save_all;
function PlatformMunger_save_all () {
this.config_keeper.save_all();
this.platformJson.save();
}
// Apply a munge object to a single config file.
// The remove parameter tells whether to add the change or remove it.
PlatformMunger.prototype.apply_file_munge = PlatformMunger_apply_file_munge;
function PlatformMunger_apply_file_munge (file, munge, remove) {
var self = this;
for (var selector in munge.parents) {
for (var xml_child in munge.parents[selector]) {
// this xml child is new, graft it (only if config file exists)
var config_file = self.config_keeper.get(self.project_dir, self.platform, file);
if (config_file.exists) {
if (remove) config_file.prune_child(selector, munge.parents[selector][xml_child]);
else config_file.graft_child(selector, munge.parents[selector][xml_child]);
} else {
events.emit('warn', 'config file ' + file + ' requested for changes not found at ' + config_file.filepath + ', ignoring');
}
}
}
}
PlatformMunger.prototype.remove_plugin_changes = remove_plugin_changes;
function remove_plugin_changes (pluginInfo, is_top_level) {
var self = this;
var platform_config = self.platformJson.root;
var plugin_vars = is_top_level
? platform_config.installed_plugins[pluginInfo.id]
: platform_config.dependent_plugins[pluginInfo.id];
var edit_config_changes = null;
if (pluginInfo.getEditConfigs) {
edit_config_changes = pluginInfo.getEditConfigs(self.platform);
}
// get config munge, aka how did this plugin change various config files
var config_munge = self.generate_plugin_config_munge(pluginInfo, plugin_vars, edit_config_changes);
// global munge looks at all plugins' changes to config files
var global_munge = platform_config.config_munge;
var munge = mungeutil.decrement_munge(global_munge, config_munge);
for (var file in munge.files) {
self.apply_file_munge(file, munge.files[file], /* remove = */ true);
}
// Remove from installed_plugins
self.platformJson.removePlugin(pluginInfo.id, is_top_level);
return self;
}
PlatformMunger.prototype.add_plugin_changes = add_plugin_changes;
function add_plugin_changes (pluginInfo, plugin_vars, is_top_level, should_increment, plugin_force) {
var self = this;
var platform_config = self.platformJson.root;
var edit_config_changes = null;
if (pluginInfo.getEditConfigs) {
edit_config_changes = pluginInfo.getEditConfigs(self.platform);
}
var config_munge;
if (!edit_config_changes || edit_config_changes.length === 0) {
// get config munge, aka how should this plugin change various config files
config_munge = self.generate_plugin_config_munge(pluginInfo, plugin_vars);
} else {
var isConflictingInfo = is_conflicting(edit_config_changes, platform_config.config_munge, self, plugin_force);
if (isConflictingInfo.conflictWithConfigxml) {
throw new Error(pluginInfo.id +
' cannot be added. <edit-config> changes in this plugin conflicts with <edit-config> changes in config.xml. Conflicts must be resolved before plugin can be added.');
}
if (plugin_force) {
events.emit('warn', '--force is used. edit-config will overwrite conflicts if any. Conflicting plugins may not work as expected.');
// remove conflicting munges
var conflict_munge = mungeutil.decrement_munge(platform_config.config_munge, isConflictingInfo.conflictingMunge);
for (var conflict_file in conflict_munge.files) {
self.apply_file_munge(conflict_file, conflict_munge.files[conflict_file], /* remove = */ true);
}
// force add new munges
config_munge = self.generate_plugin_config_munge(pluginInfo, plugin_vars, edit_config_changes);
} else if (isConflictingInfo.conflictFound) {
throw new Error('There was a conflict trying to modify attributes with <edit-config> in plugin ' + pluginInfo.id +
'. The conflicting plugin, ' + isConflictingInfo.conflictingPlugin + ', already modified the same attributes. The conflict must be resolved before ' +
pluginInfo.id + ' can be added. You may use --force to add the plugin and overwrite the conflicting attributes.');
} else {
// no conflicts, will handle edit-config
config_munge = self.generate_plugin_config_munge(pluginInfo, plugin_vars, edit_config_changes);
}
}
self = munge_helper(should_increment, self, platform_config, config_munge);
// Move to installed/dependent_plugins
self.platformJson.addPlugin(pluginInfo.id, plugin_vars || {}, is_top_level);
return self;
}
// Handle edit-config changes from config.xml
PlatformMunger.prototype.add_config_changes = add_config_changes;
function add_config_changes (config, should_increment) {
var self = this;
var platform_config = self.platformJson.root;
var config_munge;
var changes = [];
if (config.getEditConfigs) {
var edit_config_changes = config.getEditConfigs(self.platform);
if (edit_config_changes) {
changes = changes.concat(edit_config_changes);
}
}
if (config.getConfigFiles) {
var config_files_changes = config.getConfigFiles(self.platform);
if (config_files_changes) {
changes = changes.concat(config_files_changes);
}
}
if (changes && changes.length > 0) {
var isConflictingInfo = is_conflicting(changes, platform_config.config_munge, self, true /* always force overwrite other edit-config */);
if (isConflictingInfo.conflictFound) {
var conflict_munge;
var conflict_file;
if (Object.keys(isConflictingInfo.configxmlMunge.files).length !== 0) {
// silently remove conflicting config.xml munges so new munges can be added
conflict_munge = mungeutil.decrement_munge(platform_config.config_munge, isConflictingInfo.configxmlMunge);
for (conflict_file in conflict_munge.files) {
self.apply_file_munge(conflict_file, conflict_munge.files[conflict_file], /* remove = */ true);
}
}
if (Object.keys(isConflictingInfo.conflictingMunge.files).length !== 0) {
events.emit('warn', 'Conflict found, edit-config changes from config.xml will overwrite plugin.xml changes');
// remove conflicting plugin.xml munges
conflict_munge = mungeutil.decrement_munge(platform_config.config_munge, isConflictingInfo.conflictingMunge);
for (conflict_file in conflict_munge.files) {
self.apply_file_munge(conflict_file, conflict_munge.files[conflict_file], /* remove = */ true);
}
}
}
}
// Add config.xml edit-config and config-file munges
config_munge = self.generate_config_xml_munge(config, changes, 'config.xml');
self = munge_helper(should_increment, self, platform_config, config_munge);
// Move to installed/dependent_plugins
return self;
}
function munge_helper (should_increment, self, platform_config, config_munge) {
// global munge looks at all changes to config files
// TODO: The should_increment param is only used by cordova-cli and is going away soon.
// If should_increment is set to false, avoid modifying the global_munge (use clone)
// and apply the entire config_munge because it's already a proper subset of the global_munge.
var munge, global_munge;
if (should_increment) {
global_munge = platform_config.config_munge;
munge = mungeutil.increment_munge(global_munge, config_munge);
} else {
global_munge = mungeutil.clone_munge(platform_config.config_munge);
munge = config_munge;
}
for (var file in munge.files) {
self.apply_file_munge(file, munge.files[file]);
}
return self;
}
// Load the global munge from platform json and apply all of it.
// Used by cordova prepare to re-generate some config file from platform
// defaults and the global munge.
PlatformMunger.prototype.reapply_global_munge = reapply_global_munge;
function reapply_global_munge () {
var self = this;
var platform_config = self.platformJson.root;
var global_munge = platform_config.config_munge;
for (var file in global_munge.files) {
self.apply_file_munge(file, global_munge.files[file]);
}
return self;
}
// generate_plugin_config_munge
// Generate the munge object from config.xml
PlatformMunger.prototype.generate_config_xml_munge = generate_config_xml_munge;
function generate_config_xml_munge (config, config_changes, type) {
var munge = { files: {} };
var id;
if (!config_changes) {
return munge;
}
if (type === 'config.xml') {
id = type;
} else {
id = config.id;
}
config_changes.forEach(function (change) {
change.xmls.forEach(function (xml) {
// 1. stringify each xml
var stringified = (new et.ElementTree(xml)).write({ xml_declaration: false });
// 2. add into munge
if (change.mode) {
mungeutil.deep_add(munge, change.file, change.target, { xml: stringified, count: 1, mode: change.mode, id: id });
} else {
mungeutil.deep_add(munge, change.target, change.parent, { xml: stringified, count: 1, after: change.after });
}
});
});
return munge;
}
// generate_plugin_config_munge
// Generate the munge object from plugin.xml + vars
PlatformMunger.prototype.generate_plugin_config_munge = generate_plugin_config_munge;
function generate_plugin_config_munge (pluginInfo, vars, edit_config_changes) {
var self = this;
vars = vars || {};
var munge = { files: {} };
var changes = pluginInfo.getConfigFiles(self.platform);
if (edit_config_changes) {
Array.prototype.push.apply(changes, edit_config_changes);
}
changes.forEach(function (change) {
change.xmls.forEach(function (xml) {
// 1. stringify each xml
var stringified = (new et.ElementTree(xml)).write({ xml_declaration: false });
// interp vars
if (vars) {
Object.keys(vars).forEach(function (key) {
var regExp = new RegExp('\\$' + key, 'g');
stringified = stringified.replace(regExp, vars[key]);
});
}
// 2. add into munge
if (change.mode) {
if (change.mode !== 'remove') {
mungeutil.deep_add(munge, change.file, change.target, { xml: stringified, count: 1, mode: change.mode, plugin: pluginInfo.id });
}
} else {
mungeutil.deep_add(munge, change.target, change.parent, { xml: stringified, count: 1, after: change.after });
}
});
});
return munge;
}
function is_conflicting (editchanges, config_munge, self, force) {
var files = config_munge.files;
var conflictFound = false;
var conflictWithConfigxml = false;
var conflictingMunge = { files: {} };
var configxmlMunge = { files: {} };
var conflictingParent;
var conflictingPlugin;
editchanges.forEach(function (editchange) {
if (files[editchange.file]) {
var parents = files[editchange.file].parents;
var target = parents[editchange.target];
// Check if the edit target will resolve to an existing target
if (!target || target.length === 0) {
var file_xml = self.config_keeper.get(self.project_dir, self.platform, editchange.file).data;
var resolveEditTarget = xml_helpers.resolveParent(file_xml, editchange.target);
var resolveTarget;
if (resolveEditTarget) {
for (var parent in parents) {
resolveTarget = xml_helpers.resolveParent(file_xml, parent);
if (resolveEditTarget === resolveTarget) {
conflictingParent = parent;
target = parents[parent];
break;
}
}
}
} else {
conflictingParent = editchange.target;
}
if (target && target.length !== 0) {
// conflict has been found
conflictFound = true;
if (editchange.id === 'config.xml') {
if (target[0].id === 'config.xml') {
// Keep track of config.xml/config.xml edit-config conflicts
mungeutil.deep_add(configxmlMunge, editchange.file, conflictingParent, target[0]);
} else {
// Keep track of config.xml x plugin.xml edit-config conflicts
mungeutil.deep_add(conflictingMunge, editchange.file, conflictingParent, target[0]);
}
} else {
if (target[0].id === 'config.xml') {
// plugin.xml cannot overwrite config.xml changes even if --force is used
conflictWithConfigxml = true;
return;
}
if (force) {
// Need to find all conflicts when --force is used, track conflicting munges
mungeutil.deep_add(conflictingMunge, editchange.file, conflictingParent, target[0]);
} else {
// plugin cannot overwrite other plugin changes without --force
conflictingPlugin = target[0].plugin;
}
}
}
}
});
return { conflictFound: conflictFound,
conflictingPlugin: conflictingPlugin,
conflictingMunge: conflictingMunge,
configxmlMunge: configxmlMunge,
conflictWithConfigxml: conflictWithConfigxml
};
}
// Go over the prepare queue and apply the config munges for each plugin
// that has been (un)installed.
PlatformMunger.prototype.process = PlatformMunger_process;
function PlatformMunger_process (plugins_dir) {
var self = this;
var platform_config = self.platformJson.root;
// Uninstallation first
platform_config.prepare_queue.uninstalled.forEach(function (u) {
var pluginInfo = self.pluginInfoProvider.get(path.join(plugins_dir, u.plugin));
self.remove_plugin_changes(pluginInfo, u.topLevel);
});
// Now handle installation
platform_config.prepare_queue.installed.forEach(function (u) {
var pluginInfo = self.pluginInfoProvider.get(path.join(plugins_dir, u.plugin));
self.add_plugin_changes(pluginInfo, u.vars, u.topLevel, true, u.force);
});
// Empty out installed/ uninstalled queues.
platform_config.prepare_queue.uninstalled = [];
platform_config.prepare_queue.installed = [];
}
/** ** END of PlatformMunger ****/
@@ -0,0 +1,265 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var fs = require('fs-extra');
var path = require('path');
var modules = {};
var addProperty = require('../util/addProperty');
// Use delay loading to ensure plist and other node modules to not get loaded
// on Android, Windows platforms
addProperty(module, 'bplist', 'bplist-parser', modules);
addProperty(module, 'et', 'elementtree', modules);
addProperty(module, 'glob', 'glob', modules);
addProperty(module, 'plist', 'plist', modules);
addProperty(module, 'plist_helpers', '../util/plist-helpers', modules);
addProperty(module, 'xml_helpers', '../util/xml-helpers', modules);
/******************************************************************************
* ConfigFile class
*
* Can load and keep various types of config files. Provides some functionality
* specific to some file types such as grafting XML children. In most cases it
* should be instantiated by ConfigKeeper.
*
* For plugin.xml files use as:
* plugin_config = self.config_keeper.get(plugin_dir, '', 'plugin.xml');
*
* TODO: Consider moving it out to a separate file and maybe partially with
* overrides in platform handlers.
******************************************************************************/
function ConfigFile (project_dir, platform, file_tag) {
this.project_dir = project_dir;
this.platform = platform;
this.file_tag = file_tag;
this.is_changed = false;
this.load();
}
// ConfigFile.load()
ConfigFile.prototype.load = ConfigFile_load;
function ConfigFile_load () {
var self = this;
// config file may be in a place not exactly specified in the target
var filepath = self.filepath = resolveConfigFilePath(self.project_dir, self.platform, self.file_tag);
if (!filepath || !fs.existsSync(filepath)) {
self.exists = false;
return;
}
self.exists = true;
self.mtime = fs.statSync(self.filepath).mtime;
var ext = path.extname(filepath);
// Windows8 uses an appxmanifest, and wp8 will likely use
// the same in a future release
if (ext === '.xml' || ext === '.appxmanifest' || ext === '.storyboard' || ext === '.jsproj') {
self.type = 'xml';
self.data = modules.xml_helpers.parseElementtreeSync(filepath);
} else {
// plist file
self.type = 'plist';
// TODO: isBinaryPlist() reads the file and then parse re-reads it again.
// We always write out text plist, not binary.
// Do we still need to support binary plist?
// If yes, use plist.parseStringSync() and read the file once.
self.data = isBinaryPlist(filepath)
? modules.bplist.parseBuffer(fs.readFileSync(filepath))[0]
: modules.plist.parse(fs.readFileSync(filepath, 'utf8'));
}
}
ConfigFile.prototype.save = function ConfigFile_save () {
var self = this;
if (self.type === 'xml') {
fs.writeFileSync(self.filepath, self.data.write({ indent: 4 }), 'utf-8');
} else {
// plist
var regExp = /<string>[ \t\r\n]+?<\/string>/g;
fs.writeFileSync(self.filepath, modules.plist.build(self.data, { indent: '\t', offset: -1 }).replace(regExp, '<string></string>'));
}
self.is_changed = false;
};
ConfigFile.prototype.graft_child = function ConfigFile_graft_child (selector, xml_child) {
var self = this;
var filepath = self.filepath;
var result;
if (self.type === 'xml') {
var xml_to_graft = [modules.et.XML(xml_child.xml)];
switch (xml_child.mode) {
case 'merge':
result = modules.xml_helpers.graftXMLMerge(self.data, xml_to_graft, selector, xml_child);
break;
case 'overwrite':
result = modules.xml_helpers.graftXMLOverwrite(self.data, xml_to_graft, selector, xml_child);
break;
case 'remove':
result = modules.xml_helpers.pruneXMLRemove(self.data, selector, xml_to_graft);
break;
default:
result = modules.xml_helpers.graftXML(self.data, xml_to_graft, selector, xml_child.after);
}
if (!result) {
throw new Error('Unable to graft xml at selector "' + selector + '" from "' + filepath + '" during config install');
}
} else {
// plist file
result = modules.plist_helpers.graftPLIST(self.data, xml_child.xml, selector);
if (!result) {
throw new Error('Unable to graft plist "' + filepath + '" during config install');
}
}
self.is_changed = true;
};
ConfigFile.prototype.prune_child = function ConfigFile_prune_child (selector, xml_child) {
var self = this;
var filepath = self.filepath;
var result;
if (self.type === 'xml') {
var xml_to_graft = [modules.et.XML(xml_child.xml)];
switch (xml_child.mode) {
case 'merge':
case 'overwrite':
result = modules.xml_helpers.pruneXMLRestore(self.data, selector, xml_child);
break;
case 'remove':
result = modules.xml_helpers.pruneXMLRemove(self.data, selector, xml_to_graft);
break;
default:
result = modules.xml_helpers.pruneXML(self.data, xml_to_graft, selector);
}
} else {
// plist file
result = modules.plist_helpers.prunePLIST(self.data, xml_child.xml, selector);
}
if (!result) {
var err_msg = 'Pruning at selector "' + selector + '" from "' + filepath + '" went bad.';
throw new Error(err_msg);
}
self.is_changed = true;
};
// Some config-file target attributes are not qualified with a full leading directory, or contain wildcards.
// Resolve to a real path in this function.
// TODO: getIOSProjectname is slow because of glob, try to avoid calling it several times per project.
function resolveConfigFilePath (project_dir, platform, file) {
var filepath = path.join(project_dir, file);
var matches;
file = path.normalize(file);
if (file.includes('*')) {
// handle wildcards in targets using glob.
matches = modules.glob.sync(path.join(project_dir, '**', file));
if (matches.length) filepath = matches[0];
// [CB-5989] multiple Info.plist files may exist. default to $PROJECT_NAME-Info.plist
if (matches.length > 1 && file.includes('-Info.plist')) {
var plistName = getIOSProjectname(project_dir) + '-Info.plist';
for (var i = 0; i < matches.length; i++) {
if (matches[i].includes(plistName)) {
filepath = matches[i];
break;
}
}
}
return filepath;
}
// XXX this checks for android studio projects
// only if none of the options above are satisfied does this get called
// TODO: Move this out of cordova-common and into the platforms somehow
if (platform === 'android' && !fs.existsSync(filepath)) {
var config_file;
if (file === 'AndroidManifest.xml') {
filepath = path.join(project_dir, 'app', 'src', 'main', 'AndroidManifest.xml');
} else if (file.endsWith('config.xml')) {
filepath = path.join(project_dir, 'app', 'src', 'main', 'res', 'xml', 'config.xml');
} else if (file.endsWith('strings.xml')) {
// Plugins really shouldn't mess with strings.xml, since it's able to be localized
filepath = path.join(project_dir, 'app', 'src', 'main', 'res', 'values', 'strings.xml');
} else if (file.includes(path.join('res', 'values'))) {
config_file = path.basename(file);
filepath = path.join(project_dir, 'app', 'src', 'main', 'res', 'values', config_file);
} else if (file.includes(path.join('res', 'xml'))) {
// Catch-all for all other stored XML configuration in legacy plugins
config_file = path.basename(file);
filepath = path.join(project_dir, 'app', 'src', 'main', 'res', 'xml', config_file);
}
return filepath;
}
// special-case config.xml target that is just "config.xml" for other platforms. This should
// be resolved to the real location of the file.
// TODO: Move this out of cordova-common into platforms
if (file === 'config.xml') {
if (platform === 'ubuntu') {
filepath = path.join(project_dir, 'config.xml');
} else if (platform === 'ios' || platform === 'osx') {
filepath = path.join(
project_dir,
module.exports.getIOSProjectname(project_dir),
'config.xml'
);
} else {
matches = modules.glob.sync(path.join(project_dir, '**', 'config.xml'));
if (matches.length) filepath = matches[0];
}
return filepath;
}
// None of the special cases matched, returning project_dir/file.
return filepath;
}
// Find out the real name of an iOS or OSX project
// TODO: glob is slow, need a better way or caching, or avoid using more than once.
function getIOSProjectname (project_dir) {
var matches = modules.glob.sync(path.join(project_dir, '*.xcodeproj'));
var iospath;
if (matches.length === 1) {
iospath = path.basename(matches[0], '.xcodeproj');
} else {
var msg;
if (matches.length === 0) {
msg = 'Does not appear to be an xcode project, no xcode project file in ' + project_dir;
} else {
msg = 'There are multiple *.xcodeproj dirs in ' + project_dir;
}
throw new Error(msg);
}
return iospath;
}
// determine if a plist file is binary
function isBinaryPlist (filename) {
// I wish there was a synchronous way to read only the first 6 bytes of a
// file. This is wasteful :/
var buf = '' + fs.readFileSync(filename, 'utf8');
// binary plists start with a magic header, "bplist"
return buf.substring(0, 6) === 'bplist';
}
module.exports = ConfigFile;
module.exports.isBinaryPlist = isBinaryPlist;
module.exports.getIOSProjectname = getIOSProjectname;
module.exports.resolveConfigFilePath = resolveConfigFilePath;
@@ -0,0 +1,64 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* jshint sub:true */
var path = require('path');
var ConfigFile = require('./ConfigFile');
/******************************************************************************
* ConfigKeeper class
*
* Used to load and store config files to avoid re-parsing and writing them out
* multiple times.
*
* The config files are referred to by a fake path constructed as
* project_dir/platform/file
* where file is the name used for the file in config munges.
******************************************************************************/
function ConfigKeeper (project_dir, plugins_dir) {
this.project_dir = project_dir;
this.plugins_dir = plugins_dir;
this._cached = {};
}
ConfigKeeper.prototype.get = function ConfigKeeper_get (project_dir, platform, file) {
var self = this;
// This fixes a bug with older plugins - when specifying config xml instead of res/xml/config.xml
// https://issues.apache.org/jira/browse/CB-6414
if (file === 'config.xml' && platform === 'android') {
file = 'res/xml/config.xml';
}
var fake_path = path.join(project_dir, platform, file);
if (self._cached[fake_path]) {
return self._cached[fake_path];
}
// File was not cached, need to load.
var config_file = new ConfigFile(project_dir, platform, file);
self._cached[fake_path] = config_file;
return config_file;
};
ConfigKeeper.prototype.save_all = function ConfigKeeper_save_all () {
var self = this;
Object.keys(self._cached).forEach(function (fake_path) {
var config_file = self._cached[fake_path];
if (config_file.is_changed) config_file.save();
});
};
module.exports = ConfigKeeper;
@@ -0,0 +1,162 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* jshint sub:true */
var _ = require('underscore');
// add the count of [key1][key2]...[keyN] to obj
// return true if it didn't exist before
exports.deep_add = function deep_add (obj, keys /* or key1, key2 .... */) {
if (!Array.isArray(keys)) {
keys = Array.prototype.slice.call(arguments, 1);
}
return exports.process_munge(obj, true/* createParents */, function (parentArray, k) {
var found = _.find(parentArray, function (element) {
return element.xml === k.xml;
});
if (found) {
found.after = found.after || k.after;
found.count += k.count;
} else {
parentArray.push(k);
}
return !found;
}, keys);
};
// decrement the count of [key1][key2]...[keyN] from obj and remove if it reaches 0
// return true if it was removed or not found
exports.deep_remove = function deep_remove (obj, keys /* or key1, key2 .... */) {
if (!Array.isArray(keys)) {
keys = Array.prototype.slice.call(arguments, 1);
}
var result = exports.process_munge(obj, false/* createParents */, function (parentArray, k) {
var index = -1;
var found = _.find(parentArray, function (element) {
index++;
return element.xml === k.xml;
});
if (found) {
if (parentArray[index].oldAttrib) {
k.oldAttrib = _.extend({}, parentArray[index].oldAttrib);
}
found.count -= k.count;
if (found.count > 0) {
return false;
} else {
parentArray.splice(index, 1);
}
}
return undefined;
}, keys);
return typeof result === 'undefined' ? true : result;
};
// search for [key1][key2]...[keyN]
// return the object or undefined if not found
exports.deep_find = function deep_find (obj, keys /* or key1, key2 .... */) {
if (!Array.isArray(keys)) {
keys = Array.prototype.slice.call(arguments, 1);
}
return exports.process_munge(obj, false/* createParents? */, function (parentArray, k) {
return _.find(parentArray, function (element) {
return element.xml === (k.xml || k);
});
}, keys);
};
// Execute func passing it the parent array and the xmlChild key.
// When createParents is true, add the file and parent items they are missing
// When createParents is false, stop and return undefined if the file and/or parent items are missing
exports.process_munge = function process_munge (obj, createParents, func, keys /* or key1, key2 .... */) {
if (!Array.isArray(keys)) {
keys = Array.prototype.slice.call(arguments, 1);
}
var k = keys[0];
if (keys.length === 1) {
return func(obj, k);
} else if (keys.length === 2) {
if (!obj.parents[k] && !createParents) {
return undefined;
}
obj.parents[k] = obj.parents[k] || [];
return exports.process_munge(obj.parents[k], createParents, func, keys.slice(1));
} else if (keys.length === 3) {
if (!obj.files[k] && !createParents) {
return undefined;
}
obj.files[k] = obj.files[k] || { parents: {} };
return exports.process_munge(obj.files[k], createParents, func, keys.slice(1));
} else {
throw new Error('Invalid key format. Must contain at most 3 elements (file, parent, xmlChild).');
}
};
// All values from munge are added to base as
// base[file][selector][child] += munge[file][selector][child]
// Returns a munge object containing values that exist in munge
// but not in base.
exports.increment_munge = function increment_munge (base, munge) {
var diff = { files: {} };
for (var file in munge.files) {
for (var selector in munge.files[file].parents) {
for (var xml_child in munge.files[file].parents[selector]) {
var val = munge.files[file].parents[selector][xml_child];
// if node not in base, add it to diff and base
// else increment it's value in base without adding to diff
var newlyAdded = exports.deep_add(base, [file, selector, val]);
if (newlyAdded) {
exports.deep_add(diff, file, selector, val);
}
}
}
}
return diff;
};
// Update the base munge object as
// base[file][selector][child] -= munge[file][selector][child]
// nodes that reached zero value are removed from base and added to the returned munge
// object.
exports.decrement_munge = function decrement_munge (base, munge) {
var zeroed = { files: {} };
for (var file in munge.files) {
for (var selector in munge.files[file].parents) {
for (var xml_child in munge.files[file].parents[selector]) {
var val = munge.files[file].parents[selector][xml_child];
// if node not in base, add it to diff and base
// else increment it's value in base without adding to diff
var removed = exports.deep_remove(base, [file, selector, val]);
if (removed) {
exports.deep_add(zeroed, file, selector, val);
}
}
}
}
return zeroed;
};
// For better readability where used
exports.clone_munge = function clone_munge (munge) {
return exports.increment_munge({}, munge);
};
@@ -0,0 +1,630 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var et = require('elementtree');
var xml = require('../util/xml-helpers');
var CordovaError = require('../CordovaError/CordovaError');
var fs = require('fs-extra');
var events = require('../events');
/** Wraps a config.xml file */
function ConfigParser (path) {
this.path = path;
try {
this.doc = xml.parseElementtreeSync(path);
this.cdvNamespacePrefix = getCordovaNamespacePrefix(this.doc);
et.register_namespace(this.cdvNamespacePrefix, 'http://cordova.apache.org/ns/1.0');
} catch (e) {
events.emit('error', 'Parsing ' + path + ' failed');
throw e;
}
var r = this.doc.getroot();
if (r.tag !== 'widget') {
throw new CordovaError(path + ' has incorrect root node name (expected "widget", was "' + r.tag + '")');
}
}
function getNodeTextSafe (el) {
return el && el.text && el.text.trim();
}
function findOrCreate (doc, name) {
var ret = doc.find(name);
if (!ret) {
ret = new et.Element(name);
doc.getroot().append(ret);
}
return ret;
}
function getCordovaNamespacePrefix (doc) {
var rootAtribs = Object.getOwnPropertyNames(doc.getroot().attrib);
var prefix = 'cdv';
for (var j = 0; j < rootAtribs.length; j++) {
if (rootAtribs[j].startsWith('xmlns:') &&
doc.getroot().attrib[rootAtribs[j]] === 'http://cordova.apache.org/ns/1.0') {
var strings = rootAtribs[j].split(':');
prefix = strings[1];
break;
}
}
return prefix;
}
/**
* Finds the value of an element's attribute
* @param {String} attributeName Name of the attribute to search for
* @param {Array} elems An array of ElementTree nodes
* @return {String}
*/
function findElementAttributeValue (attributeName, elems) {
elems = Array.isArray(elems) ? elems : [elems];
var value = elems.filter(function (elem) {
return elem.attrib.name.toLowerCase() === attributeName.toLowerCase();
}).map(function (filteredElems) {
return filteredElems.attrib.value;
}).pop();
return value || '';
}
function removeChildren (el, selector) {
const matches = el.findall(selector);
matches.forEach(child => el.remove(child));
}
ConfigParser.prototype = {
getAttribute: function (attr) {
return this.doc.getroot().attrib[attr];
},
packageName: function () {
return this.getAttribute('id');
},
setPackageName: function (id) {
this.doc.getroot().attrib['id'] = id;
},
android_packageName: function () {
return this.getAttribute('android-packageName');
},
android_activityName: function () {
return this.getAttribute('android-activityName');
},
ios_CFBundleIdentifier: function () {
return this.getAttribute('ios-CFBundleIdentifier');
},
name: function () {
return getNodeTextSafe(this.doc.find('name'));
},
setName: function (name) {
var el = findOrCreate(this.doc, 'name');
el.text = name;
},
shortName: function () {
return this.doc.find('name').attrib['short'] || this.name();
},
setShortName: function (shortname) {
var el = findOrCreate(this.doc, 'name');
if (!el.text) {
el.text = shortname;
}
el.attrib['short'] = shortname;
},
description: function () {
return getNodeTextSafe(this.doc.find('description'));
},
setDescription: function (text) {
var el = findOrCreate(this.doc, 'description');
el.text = text;
},
version: function () {
return this.getAttribute('version');
},
windows_packageVersion: function () {
return this.getAttribute('windows-packageVersion');
},
android_versionCode: function () {
return this.getAttribute('android-versionCode');
},
ios_CFBundleVersion: function () {
return this.getAttribute('ios-CFBundleVersion');
},
setVersion: function (value) {
this.doc.getroot().attrib['version'] = value;
},
author: function () {
return getNodeTextSafe(this.doc.find('author'));
},
getGlobalPreference: function (name) {
return findElementAttributeValue(name, this.doc.findall('preference'));
},
setGlobalPreference: function (name, value) {
var pref = this.doc.find('preference[@name="' + name + '"]');
if (!pref) {
pref = new et.Element('preference');
pref.attrib.name = name;
this.doc.getroot().append(pref);
}
pref.attrib.value = value;
},
getPlatformPreference: function (name, platform) {
return findElementAttributeValue(name, this.doc.findall('./platform[@name="' + platform + '"]/preference'));
},
setPlatformPreference: function (name, platform, value) {
const platformEl = this.doc.find('./platform[@name="' + platform + '"]');
if (!platformEl) {
throw new CordovaError('platform does not exist (received platform: ' + platform + ')');
}
const elems = this.doc.findall('./platform[@name="' + platform + '"]/preference');
let pref = elems.filter(function (elem) {
return elem.attrib.name.toLowerCase() === name.toLowerCase();
}).pop();
if (!pref) {
pref = new et.Element('preference');
pref.attrib.name = name;
platformEl.append(pref);
}
pref.attrib.value = value;
},
getPreference: function (name, platform) {
var platformPreference = '';
if (platform) {
platformPreference = this.getPlatformPreference(name, platform);
}
return platformPreference || this.getGlobalPreference(name);
},
setPreference: function (name, platform, value) {
if (!value) {
value = platform;
platform = undefined;
}
if (platform) {
this.setPlatformPreference(name, platform, value);
} else {
this.setGlobalPreference(name, value);
}
},
/**
* Returns all resources for the platform specified.
* @param {String} platform The platform.
* @param {string} resourceName Type of static resources to return.
* "icon" and "splash" currently supported.
* @return {Array} Resources for the platform specified.
*/
getStaticResources: function (platform, resourceName) {
var ret = [];
var staticResources = [];
if (platform) { // platform specific icons
this.doc.findall('./platform[@name="' + platform + '"]/' + resourceName).forEach(function (elt) {
elt.platform = platform; // mark as platform specific resource
staticResources.push(elt);
});
}
// root level resources
staticResources = staticResources.concat(this.doc.findall(resourceName));
// parse resource elements
var that = this;
staticResources.forEach(function (elt) {
var res = {};
res.src = elt.attrib.src;
res.target = elt.attrib.target || undefined;
res.density = elt.attrib['density'] || elt.attrib[that.cdvNamespacePrefix + ':density'] || elt.attrib['gap:density'];
res.platform = elt.platform || null; // null means icon represents default icon (shared between platforms)
res.width = +elt.attrib.width || undefined;
res.height = +elt.attrib.height || undefined;
res.background = elt.attrib.background || undefined;
res.foreground = elt.attrib.foreground || undefined;
// default icon
if (!res.width && !res.height && !res.density) {
ret.defaultResource = res;
}
ret.push(res);
});
/**
* Returns resource with specified width and/or height.
* @param {number} width Width of resource.
* @param {number} height Height of resource.
* @return {Resource} Resource object or null if not found.
*/
ret.getBySize = function (width, height) {
return ret.filter(function (res) {
if (!res.width && !res.height) {
return false;
}
return ((!res.width || (width === res.width)) &&
(!res.height || (height === res.height)));
})[0] || null;
};
/**
* Returns resource with specified density.
* @param {string} density Density of resource.
* @return {Resource} Resource object or null if not found.
*/
ret.getByDensity = function (density) {
return ret.filter(function (res) {
return res.density === density;
})[0] || null;
};
/** Returns default icons */
ret.getDefault = function () {
return ret.defaultResource;
};
return ret;
},
/**
* Returns all icons for specific platform.
* @param {string} platform Platform name
* @return {Resource[]} Array of icon objects.
*/
getIcons: function (platform) {
return this.getStaticResources(platform, 'icon');
},
/**
* Returns all splash images for specific platform.
* @param {string} platform Platform name
* @return {Resource[]} Array of Splash objects.
*/
getSplashScreens: function (platform) {
return this.getStaticResources(platform, 'splash');
},
/**
* Returns all resource-files for a specific platform.
* @param {string} platform Platform name
* @param {boolean} includeGlobal Whether to return resource-files at the
* root level.
* @return {Resource[]} Array of resource file objects.
*/
getFileResources: function (platform, includeGlobal) {
var fileResources = [];
if (platform) { // platform specific resources
fileResources = this.doc.findall('./platform[@name="' + platform + '"]/resource-file').map(function (tag) {
return {
platform: platform,
src: tag.attrib.src,
target: tag.attrib.target,
versions: tag.attrib.versions,
deviceTarget: tag.attrib['device-target'],
arch: tag.attrib.arch
};
});
}
if (includeGlobal) {
this.doc.findall('resource-file').forEach(function (tag) {
fileResources.push({
platform: platform || null,
src: tag.attrib.src,
target: tag.attrib.target,
versions: tag.attrib.versions,
deviceTarget: tag.attrib['device-target'],
arch: tag.attrib.arch
});
});
}
return fileResources;
},
/**
* Returns all hook scripts for the hook type specified.
* @param {String} hook The hook type.
* @param {Array} platforms Platforms to look for scripts into (root scripts will be included as well).
* @return {Array} Script elements.
*/
getHookScripts: function (hook, platforms) {
var self = this;
var scriptElements = self.doc.findall('./hook');
if (platforms) {
platforms.forEach(function (platform) {
scriptElements = scriptElements.concat(self.doc.findall('./platform[@name="' + platform + '"]/hook'));
});
}
function filterScriptByHookType (el) {
return el.attrib.src && el.attrib.type && el.attrib.type.toLowerCase() === hook;
}
return scriptElements.filter(filterScriptByHookType);
},
/**
* Returns a list of plugin (IDs).
*
* This function also returns any plugin's that
* were defined using the legacy <feature> tags.
* @return {string[]} Array of plugin IDs
*/
getPluginIdList: function () {
var plugins = this.doc.findall('plugin');
var result = plugins.map(function (plugin) {
return plugin.attrib.name;
});
var features = this.doc.findall('feature');
features.forEach(function (element) {
var idTag = element.find('./param[@name="id"]');
if (idTag) {
result.push(idTag.attrib.value);
}
});
return result;
},
getPlugins: function () {
return this.getPluginIdList().map(function (pluginId) {
return this.getPlugin(pluginId);
}, this);
},
/**
* Adds a plugin element. Does not check for duplicates.
* @name addPlugin
* @function
* @param {object} attributes name and spec are supported
* @param {Array|object} variables name, value or arbitary object
*/
addPlugin: function (attributes, variables) {
if (!attributes && !attributes.name) return;
var el = new et.Element('plugin');
el.attrib.name = attributes.name;
if (attributes.spec) {
el.attrib.spec = attributes.spec;
}
// support arbitrary object as variables source
if (variables && typeof variables === 'object' && !Array.isArray(variables)) {
variables = Object.keys(variables)
.map(function (variableName) {
return { name: variableName, value: variables[variableName] };
});
}
if (variables) {
variables.forEach(function (variable) {
el.append(new et.Element('variable', { name: variable.name, value: variable.value }));
});
}
this.doc.getroot().append(el);
},
/**
* Retrives the plugin with the given id or null if not found.
*
* This function also returns any plugin's that
* were defined using the legacy <feature> tags.
* @name getPlugin
* @function
* @param {String} id
* @returns {object} plugin including any variables
*/
getPlugin: function (id) {
if (!id) {
return undefined;
}
var pluginElement = this.doc.find('./plugin/[@name="' + id + '"]');
if (pluginElement === null) {
var legacyFeature = this.doc.find('./feature/param[@name="id"][@value="' + id + '"]/..');
if (legacyFeature) {
events.emit('log', 'Found deprecated feature entry for ' + id + ' in config.xml.');
return featureToPlugin(legacyFeature);
}
return undefined;
}
var plugin = {};
plugin.name = pluginElement.attrib.name;
plugin.spec = pluginElement.attrib.spec || pluginElement.attrib.src || pluginElement.attrib.version;
plugin.variables = {};
var variableElements = pluginElement.findall('variable');
variableElements.forEach(function (varElement) {
var name = varElement.attrib.name;
var value = varElement.attrib.value;
if (name) {
plugin.variables[name] = value;
}
});
return plugin;
},
/**
* Remove the plugin entry with give name (id).
*
* This function also operates on any plugin's that
* were defined using the legacy <feature> tags.
* @name removePlugin
* @function
* @param id name of the plugin
*/
removePlugin: function (id) {
if (!id) return;
const root = this.doc.getroot();
removeChildren(root, `./plugin/[@name="${id}"]`);
removeChildren(root, `./feature/param[@name="id"][@value="${id}"]/..`);
},
// Add any element to the root
addElement: function (name, attributes) {
var el = et.Element(name);
for (var a in attributes) {
el.attrib[a] = attributes[a];
}
this.doc.getroot().append(el);
},
/**
* Adds an engine. Does not check for duplicates.
* @param {String} name the engine name
* @param {String} spec engine source location or version (optional)
*/
addEngine: function (name, spec) {
if (!name) return;
var el = et.Element('engine');
el.attrib.name = name;
if (spec) {
el.attrib.spec = spec;
}
this.doc.getroot().append(el);
},
/**
* Removes all the engines with given name
* @param {String} name the engine name.
*/
removeEngine: function (name) {
removeChildren(this.doc.getroot(), `./engine/[@name="${name}"]`);
},
getEngines: function () {
var engines = this.doc.findall('./engine');
return engines.map(function (engine) {
var spec = engine.attrib.spec || engine.attrib.version;
return {
name: engine.attrib.name,
spec: spec || null
};
});
},
/* Get all the access tags */
getAccesses: function () {
var accesses = this.doc.findall('./access');
return accesses.map(function (access) {
var minimum_tls_version = access.attrib['minimum-tls-version']; /* String */
var requires_forward_secrecy = access.attrib['requires-forward-secrecy']; /* Boolean */
var requires_certificate_transparency = access.attrib['requires-certificate-transparency']; /* Boolean */
var allows_arbitrary_loads_in_web_content = access.attrib['allows-arbitrary-loads-in-web-content']; /* Boolean */
var allows_arbitrary_loads_in_media = access.attrib['allows-arbitrary-loads-in-media']; /* Boolean (DEPRECATED) */
var allows_arbitrary_loads_for_media = access.attrib['allows-arbitrary-loads-for-media']; /* Boolean */
var allows_local_networking = access.attrib['allows-local-networking']; /* Boolean */
return {
origin: access.attrib.origin,
minimum_tls_version: minimum_tls_version,
requires_forward_secrecy: requires_forward_secrecy,
requires_certificate_transparency: requires_certificate_transparency,
allows_arbitrary_loads_in_web_content: allows_arbitrary_loads_in_web_content,
allows_arbitrary_loads_in_media: allows_arbitrary_loads_in_media,
allows_arbitrary_loads_for_media: allows_arbitrary_loads_for_media,
allows_local_networking: allows_local_networking
};
});
},
/* Get all the allow-navigation tags */
getAllowNavigations: function () {
var allow_navigations = this.doc.findall('./allow-navigation');
return allow_navigations.map(function (allow_navigation) {
var minimum_tls_version = allow_navigation.attrib['minimum-tls-version']; /* String */
var requires_forward_secrecy = allow_navigation.attrib['requires-forward-secrecy']; /* Boolean */
var requires_certificate_transparency = allow_navigation.attrib['requires-certificate-transparency']; /* Boolean */
return {
href: allow_navigation.attrib.href,
minimum_tls_version: minimum_tls_version,
requires_forward_secrecy: requires_forward_secrecy,
requires_certificate_transparency: requires_certificate_transparency
};
});
},
/* Get all the allow-intent tags */
getAllowIntents: function () {
var allow_intents = this.doc.findall('./allow-intent');
return allow_intents.map(function (allow_intent) {
return {
href: allow_intent.attrib.href
};
});
},
/* Get all edit-config tags */
getEditConfigs: function (platform) {
var platform_edit_configs = this.doc.findall('./platform[@name="' + platform + '"]/edit-config');
var edit_configs = this.doc.findall('edit-config').concat(platform_edit_configs);
return edit_configs.map(function (tag) {
var editConfig =
{
file: tag.attrib['file'],
target: tag.attrib['target'],
mode: tag.attrib['mode'],
id: 'config.xml',
xmls: tag.getchildren()
};
return editConfig;
});
},
/* Get all config-file tags */
getConfigFiles: function (platform) {
var platform_config_files = this.doc.findall('./platform[@name="' + platform + '"]/config-file');
var config_files = this.doc.findall('config-file').concat(platform_config_files);
return config_files.map(function (tag) {
var configFile =
{
target: tag.attrib['target'],
parent: tag.attrib['parent'],
after: tag.attrib['after'],
xmls: tag.getchildren(),
// To support demuxing via versions
versions: tag.attrib['versions'],
deviceTarget: tag.attrib['device-target']
};
return configFile;
});
},
write: function () {
fs.writeFileSync(this.path, this.doc.write({ indent: 4 }), 'utf-8');
}
};
function featureToPlugin (featureElement) {
var plugin = {};
plugin.variables = [];
var pluginVersion,
pluginSrc;
var nodes = featureElement.findall('param');
nodes.forEach(function (element) {
var n = element.attrib.name;
var v = element.attrib.value;
if (n === 'id') {
plugin.name = v;
} else if (n === 'version') {
pluginVersion = v;
} else if (n === 'url' || n === 'installPath') {
pluginSrc = v;
} else {
plugin.variables[n] = v;
}
});
var spec = pluginSrc || pluginVersion;
if (spec) {
plugin.spec = spec;
}
return plugin;
}
module.exports = ConfigParser;
@@ -0,0 +1,76 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var fs = require('fs-extra');
var path = require('path');
function isRootDir (dir) {
if (fs.existsSync(path.join(dir, 'www'))) {
if (fs.existsSync(path.join(dir, 'config.xml'))) {
// For sure is.
if (fs.existsSync(path.join(dir, 'platforms'))) {
return 2;
} else {
return 1;
}
}
// Might be (or may be under platforms/).
if (fs.existsSync(path.join(dir, 'www', 'config.xml'))) {
return 1;
}
}
return 0;
}
// Runs up the directory chain looking for a .cordova directory.
// IF it is found we are in a Cordova project.
// Omit argument to use CWD.
function isCordova (dir) {
if (!dir) {
// Prefer PWD over cwd so that symlinked dirs within your PWD work correctly (CB-5687).
var pwd = process.env.PWD;
var cwd = process.cwd();
if (pwd && pwd !== cwd && pwd !== 'undefined') {
return isCordova(pwd) || isCordova(cwd);
}
return isCordova(cwd);
}
var bestReturnValueSoFar = false;
for (var i = 0; i < 1000; ++i) {
var result = isRootDir(dir);
if (result === 2) {
return dir;
}
if (result === 1) {
bestReturnValueSoFar = dir;
}
var parentDir = path.normalize(path.join(dir, '..'));
// Detect fs root.
if (parentDir === dir) {
return bestReturnValueSoFar;
}
dir = parentDir;
}
console.error('Hit an unhandled case in CordovaCheck.isCordova');
return false;
}
module.exports = {
findProjectRoot: isCordova
};
@@ -0,0 +1,91 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var EOL = require('os').EOL;
/**
* A derived exception class. See usage example in cli.js
* Based on:
* stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/8460753#8460753
* @param {String} message Error message
* @param {Number} [code=0] Error code
* @param {CordovaExternalToolErrorContext} [context] External tool error context object
* @constructor
*/
function CordovaError (message, code, context) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.code = code || CordovaError.UNKNOWN_ERROR;
this.context = context;
}
// FIXME __proto__ property has been deprecated as of ECMAScript 3.1
// eslint-disable-next-line no-proto
CordovaError.prototype.__proto__ = Error.prototype;
// TODO: Extend error codes according the projects specifics
CordovaError.UNKNOWN_ERROR = 0;
CordovaError.EXTERNAL_TOOL_ERROR = 1;
/**
* Translates instance's error code number into error code name, e.g. 0 -> UNKNOWN_ERROR
* @returns {string} Error code string name
*/
CordovaError.prototype.getErrorCodeName = function () {
for (const key of Object.keys(CordovaError)) {
if (CordovaError[key] === this.code) {
return key;
}
}
};
/**
* Converts CordovaError instance to string representation
* @param {Boolean} [isVerbose] Set up verbose mode. Used to provide more
* details including information about error code name and context
* @return {String} Stringified error representation
*/
CordovaError.prototype.toString = function (isVerbose) {
var message = '';
var codePrefix = '';
if (this.code !== CordovaError.UNKNOWN_ERROR) {
codePrefix = 'code: ' + this.code + (isVerbose ? (' (' + this.getErrorCodeName() + ')') : '') + ' ';
}
if (this.code === CordovaError.EXTERNAL_TOOL_ERROR) {
if (typeof this.context !== 'undefined') {
if (isVerbose) {
message = codePrefix + EOL + this.context.toString(isVerbose) + '\n failed with an error: ' +
this.message + EOL + 'Stack trace: ' + this.stack;
} else {
message = codePrefix + '\'' + this.context.toString(isVerbose) + '\' ' + this.message;
}
} else {
message = 'External tool failed with an error: ' + this.message;
}
} else {
message = isVerbose ? codePrefix + this.stack : codePrefix + this.message;
}
return message;
};
module.exports = CordovaError;
@@ -0,0 +1,48 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/* jshint proto:true */
var path = require('path');
/**
* @param {String} cmd Command full path
* @param {String[]} args Command args
* @param {String} [cwd] Command working directory
* @constructor
*/
function CordovaExternalToolErrorContext (cmd, args, cwd) {
this.cmd = cmd;
// Helper field for readability
this.cmdShortName = path.basename(cmd);
this.args = args;
this.cwd = cwd;
}
CordovaExternalToolErrorContext.prototype.toString = function (isVerbose) {
if (isVerbose) {
return 'External tool \'' + this.cmdShortName + '\'' +
'\nCommand full path: ' + this.cmd + '\nCommand args: ' + this.args +
(typeof this.cwd !== 'undefined' ? '\nCommand cwd: ' + this.cwd : '');
}
return this.cmdShortName;
};
module.exports = CordovaExternalToolErrorContext;
@@ -0,0 +1,228 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
const ansi = require('ansi');
const EventEmitter = require('events').EventEmitter;
const EOL = require('os').EOL;
const formatError = require('./util/formatError');
const INSTANCE_KEY = Symbol.for('org.apache.cordova.common.CordovaLogger');
/**
* @typedef {'verbose'|'normal'|'warn'|'info'|'error'|'results'} CordovaLoggerLevel
*/
/**
* Implements logging facility that anybody could use.
*
* Should not be instantiated directly! `CordovaLogger.get()` method should be
* used instead to acquire the logger instance.
*/
class CordovaLogger {
// Encapsulate the default logging level values with constants:
static get VERBOSE () { return 'verbose'; }
static get NORMAL () { return 'normal'; }
static get WARN () { return 'warn'; }
static get INFO () { return 'info'; }
static get ERROR () { return 'error'; }
static get RESULTS () { return 'results'; }
/**
* Static method to create new or acquire existing instance.
*
* @returns {CordovaLogger} Logger instance
*/
static get () {
// This singleton instance pattern is based on the ideas from
// https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/
if (Object.getOwnPropertySymbols(global).indexOf(INSTANCE_KEY) === -1) {
global[INSTANCE_KEY] = new CordovaLogger();
}
return global[INSTANCE_KEY];
}
constructor () {
/** @private */
this.levels = {};
/** @private */
this.colors = {};
/** @private */
this.stdout = process.stdout;
/** @private */
this.stderr = process.stderr;
/** @private */
this.stdoutCursor = ansi(this.stdout);
/** @private */
this.stderrCursor = ansi(this.stderr);
this.addLevel(CordovaLogger.VERBOSE, 1000, 'grey');
this.addLevel(CordovaLogger.NORMAL, 2000);
this.addLevel(CordovaLogger.WARN, 2000, 'yellow');
this.addLevel(CordovaLogger.INFO, 3000, 'blue');
this.addLevel(CordovaLogger.ERROR, 5000, 'red');
this.addLevel(CordovaLogger.RESULTS, 10000);
this.setLevel(CordovaLogger.NORMAL);
}
/**
* Emits log message to process' stdout/stderr depending on message's
* severity and current log level. If severity is less than current
* logger's level, then the message is ignored.
*
* @param {CordovaLoggerLevel} logLevel - The message's log level. The
* logger should have corresponding level added (via logger.addLevel),
* otherwise `CordovaLogger.NORMAL` level will be used.
*
* @param {string} message - The message, that should be logged to
* process's stdio.
*
* @returns {CordovaLogger} Return the current instance, to allow chaining.
*/
log (logLevel, message) {
// if there is no such logLevel defined, or provided level has
// less severity than active level, then just ignore this call and return
if (!this.levels[logLevel] || this.levels[logLevel] < this.levels[this.logLevel]) {
// return instance to allow to chain calls
return this;
}
var isVerbose = this.logLevel === CordovaLogger.VERBOSE;
var cursor = this.stdoutCursor;
if (message instanceof Error || logLevel === CordovaLogger.ERROR) {
message = formatError(message, isVerbose);
cursor = this.stderrCursor;
}
var color = this.colors[logLevel];
if (color) {
cursor.bold().fg[color]();
}
cursor.write(message).reset().write(EOL);
return this;
}
/**
* Adds a new level to logger instance.
*
* This method also creates a shortcut method to log events with the level
* provided.
* (i.e. after adding new level 'debug', the method `logger.debug(message)`
* will exist, equal to `logger.log('debug', message)`)
*
* @param {CordovaLoggerLevel} level - A log level name. The levels with
* the following names are added by default to every instance: 'verbose',
* 'normal', 'warn', 'info', 'error', 'results'.
*
* @param {number} severity - A number that represents level's severity.
*
* @param {string} color - A valid color name, that will be used to log
* messages with this level. Any CSS color code or RGB value is allowed
* (according to ansi documentation:
* https://github.com/TooTallNate/ansi.js#features).
*
* @returns {CordovaLogger} Return the current instance, to allow chaining.
*/
addLevel (level, severity, color) {
this.levels[level] = severity;
if (color) {
this.colors[level] = color;
}
// Define own method with corresponding name
if (!this[level]) {
Object.defineProperty(this, level, {
get () { return this.log.bind(this, level); }
});
}
return this;
}
/**
* Sets the current logger level to provided value.
*
* If logger doesn't have level with this name, `CordovaLogger.NORMAL` will
* be used.
*
* @param {CordovaLoggerLevel} logLevel - Level name. The level with this
* name should be added to logger before.
*
* @returns {CordovaLogger} Current instance, to allow chaining.
*/
setLevel (logLevel) {
this.logLevel = this.levels[logLevel] ? logLevel : CordovaLogger.NORMAL;
return this;
}
/**
* Adjusts the current logger level according to the passed options.
*
* @param {Object|Array<string>} opts - An object or args array with
* options.
*
* @returns {CordovaLogger} Current instance, to allow chaining.
*/
adjustLevel (opts) {
if (opts.verbose || (Array.isArray(opts) && opts.includes('--verbose'))) {
this.setLevel('verbose');
} else if (opts.silent || (Array.isArray(opts) && opts.includes('--silent'))) {
this.setLevel('error');
}
return this;
}
/**
* Attaches logger to EventEmitter instance provided.
*
* @param {EventEmitter} eventEmitter - An EventEmitter instance to attach
* the logger to.
*
* @returns {CordovaLogger} Current instance, to allow chaining.
*/
subscribe (eventEmitter) {
if (!(eventEmitter instanceof EventEmitter)) {
throw new Error('Subscribe method only accepts an EventEmitter instance as argument');
}
eventEmitter.on('verbose', this.verbose)
.on('log', this.normal)
.on('info', this.info)
.on('warn', this.warn)
.on('warning', this.warn)
// Set up event handlers for logging and results emitted as events.
.on('results', this.results);
return this;
}
}
module.exports = CordovaLogger;
@@ -0,0 +1,402 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
'use strict';
var fs = require('fs-extra');
var path = require('path');
var minimatch = require('minimatch');
/**
* Logging callback used in the FileUpdater methods.
* @callback loggingCallback
* @param {string} message A message describing a single file update operation.
*/
/**
* Updates a target file or directory with a source file or directory. (Directory updates are
* not recursive.) Stats for target and source items must be passed in. This is an internal
* helper function used by other methods in this module.
*
* @param {?string} sourcePath Source file or directory to be used to update the
* destination. If the source is null, then the destination is deleted if it exists.
* @param {?fs.Stats} sourceStats An instance of fs.Stats for the source path, or null if
* the source does not exist.
* @param {string} targetPath Required destination file or directory to be updated. If it does
* not exist, it will be created.
* @param {?fs.Stats} targetStats An instance of fs.Stats for the target path, or null if
* the target does not exist.
* @param {Object} [options] Optional additional parameters for the update.
* @param {string} [options.rootDir] Optional root directory (such as a project) to which target
* and source path parameters are relative; may be omitted if the paths are absolute. The
* rootDir is always omitted from any logged paths, to make the logs easier to read.
* @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.
* Otherwise, a file is copied if the source's last-modified time is greather than or
* equal to the target's last-modified time, or if the file sizes are different.
* @param {loggingCallback} [log] Optional logging callback that takes a string message
* describing any file operations that are performed.
* @return {boolean} true if any changes were made, or false if the force flag is not set
* and everything was up to date
*/
function updatePathWithStats (sourcePath, sourceStats, targetPath, targetStats, options, log) {
var updated = false;
var rootDir = (options && options.rootDir) || '';
var copyAll = (options && options.all) || false;
var targetFullPath = path.join(rootDir || '', targetPath);
if (sourceStats) {
var sourceFullPath = path.join(rootDir || '', sourcePath);
if (targetStats && (targetStats.isDirectory() !== sourceStats.isDirectory())) {
// The target exists. But if the directory status doesn't match the source, delete it.
log('delete ' + targetPath);
fs.removeSync(targetFullPath);
targetStats = null;
updated = true;
}
if (!targetStats) {
if (sourceStats.isDirectory()) {
// The target directory does not exist, so it should be created.
log('mkdir ' + targetPath);
fs.ensureDirSync(targetFullPath);
updated = true;
} else if (sourceStats.isFile()) {
// The target file does not exist, so it should be copied from the source.
log('copy ' + sourcePath + ' ' + targetPath + (copyAll ? '' : ' (new file)'));
fs.copySync(sourceFullPath, targetFullPath);
updated = true;
}
} else if (sourceStats.isFile() && targetStats.isFile()) {
// The source and target paths both exist and are files.
if (copyAll) {
// The caller specified all files should be copied.
log('copy ' + sourcePath + ' ' + targetPath);
fs.copySync(sourceFullPath, targetFullPath);
updated = true;
} else {
// Copy if the source has been modified since it was copied to the target, or if
// the file sizes are different. (The latter catches most cases in which something
// was done to the file after copying.) Comparison is >= rather than > to allow
// for timestamps lacking sub-second precision in some filesystems.
if (sourceStats.mtime.getTime() >= targetStats.mtime.getTime() ||
sourceStats.size !== targetStats.size) {
log('copy ' + sourcePath + ' ' + targetPath + ' (updated file)');
fs.copySync(sourceFullPath, targetFullPath);
updated = true;
}
}
}
} else if (targetStats) {
// The target exists but the source is null, so the target should be deleted.
log('delete ' + targetPath + (copyAll ? '' : ' (no source)'));
fs.removeSync(targetFullPath);
updated = true;
}
return updated;
}
/**
* Helper for updatePath and updatePaths functions. Queries stats for source and target
* and ensures target directory exists before copying a file.
*/
function updatePathInternal (sourcePath, targetPath, options, log) {
var rootDir = (options && options.rootDir) || '';
var targetFullPath = path.join(rootDir, targetPath);
var targetStats = fs.existsSync(targetFullPath) ? fs.statSync(targetFullPath) : null;
var sourceStats = null;
if (sourcePath) {
// A non-null source path was specified. It should exist.
var sourceFullPath = path.join(rootDir, sourcePath);
if (!fs.existsSync(sourceFullPath)) {
throw new Error('Source path does not exist: ' + sourcePath);
}
sourceStats = fs.statSync(sourceFullPath);
// Create the target's parent directory if it doesn't exist.
var parentDir = path.dirname(targetFullPath);
if (!fs.existsSync(parentDir)) {
fs.ensureDirSync(parentDir);
}
}
return updatePathWithStats(sourcePath, sourceStats, targetPath, targetStats, options, log);
}
/**
* Updates a target file or directory with a source file or directory. (Directory updates are
* not recursive.)
*
* @param {?string} sourcePath Source file or directory to be used to update the
* destination. If the source is null, then the destination is deleted if it exists.
* @param {string} targetPath Required destination file or directory to be updated. If it does
* not exist, it will be created.
* @param {Object} [options] Optional additional parameters for the update.
* @param {string} [options.rootDir] Optional root directory (such as a project) to which target
* and source path parameters are relative; may be omitted if the paths are absolute. The
* rootDir is always omitted from any logged paths, to make the logs easier to read.
* @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.
* Otherwise, a file is copied if the source's last-modified time is greather than or
* equal to the target's last-modified time, or if the file sizes are different.
* @param {loggingCallback} [log] Optional logging callback that takes a string message
* describing any file operations that are performed.
* @return {boolean} true if any changes were made, or false if the force flag is not set
* and everything was up to date
*/
function updatePath (sourcePath, targetPath, options, log) {
if (sourcePath !== null && typeof sourcePath !== 'string') {
throw new Error('A source path (or null) is required.');
}
if (!targetPath || typeof targetPath !== 'string') {
throw new Error('A target path is required.');
}
log = log || function () { };
return updatePathInternal(sourcePath, targetPath, options, log);
}
/**
* Updates files and directories based on a mapping from target paths to source paths. Targets
* with null sources in the map are deleted.
*
* @param {Object} pathMap A dictionary mapping from target paths to source paths.
* @param {Object} [options] Optional additional parameters for the update.
* @param {string} [options.rootDir] Optional root directory (such as a project) to which target
* and source path parameters are relative; may be omitted if the paths are absolute. The
* rootDir is always omitted from any logged paths, to make the logs easier to read.
* @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.
* Otherwise, a file is copied if the source's last-modified time is greather than or
* equal to the target's last-modified time, or if the file sizes are different.
* @param {loggingCallback} [log] Optional logging callback that takes a string message
* describing any file operations that are performed.
* @return {boolean} true if any changes were made, or false if the force flag is not set
* and everything was up to date
*/
function updatePaths (pathMap, options, log) {
if (!pathMap || typeof pathMap !== 'object' || Array.isArray(pathMap)) {
throw new Error('An object mapping from target paths to source paths is required.');
}
log = log || function () { };
var updated = false;
// Iterate in sorted order to ensure directories are created before files under them.
Object.keys(pathMap).sort().forEach(function (targetPath) {
var sourcePath = pathMap[targetPath];
updated = updatePathInternal(sourcePath, targetPath, options, log) || updated;
});
return updated;
}
/**
* Updates a target directory with merged files and subdirectories from source directories.
*
* @param {string|string[]} sourceDirs Required source directory or array of source directories
* to be merged into the target. The directories are listed in order of precedence; files in
* directories later in the array supersede files in directories earlier in the array
* (regardless of timestamps).
* @param {string} targetDir Required destination directory to be updated. If it does not exist,
* it will be created. If it exists, newer files from source directories will be copied over,
* and files missing in the source directories will be deleted.
* @param {Object} [options] Optional additional parameters for the update.
* @param {string} [options.rootDir] Optional root directory (such as a project) to which target
* and source path parameters are relative; may be omitted if the paths are absolute. The
* rootDir is always omitted from any logged paths, to make the logs easier to read.
* @param {boolean} [options.all] If true, all files are copied regardless of last-modified times.
* Otherwise, a file is copied if the source's last-modified time is greather than or
* equal to the target's last-modified time, or if the file sizes are different.
* @param {string|string[]} [options.include] Optional glob string or array of glob strings that
* are tested against both target and source relative paths to determine if they are included
* in the merge-and-update. If unspecified, all items are included.
* @param {string|string[]} [options.exclude] Optional glob string or array of glob strings that
* are tested against both target and source relative paths to determine if they are excluded
* from the merge-and-update. Exclusions override inclusions. If unspecified, no items are
* excluded.
* @param {loggingCallback} [log] Optional logging callback that takes a string message
* describing any file operations that are performed.
* @return {boolean} true if any changes were made, or false if the force flag is not set
* and everything was up to date
*/
function mergeAndUpdateDir (sourceDirs, targetDir, options, log) {
if (sourceDirs && typeof sourceDirs === 'string') {
sourceDirs = [sourceDirs];
} else if (!Array.isArray(sourceDirs)) {
throw new Error('A source directory path or array of paths is required.');
}
if (!targetDir || typeof targetDir !== 'string') {
throw new Error('A target directory path is required.');
}
log = log || function () { };
var rootDir = (options && options.rootDir) || '';
var include = (options && options.include) || ['**'];
if (typeof include === 'string') {
include = [include];
} else if (!Array.isArray(include)) {
throw new Error('Include parameter must be a glob string or array of glob strings.');
}
var exclude = (options && options.exclude) || [];
if (typeof exclude === 'string') {
exclude = [exclude];
} else if (!Array.isArray(exclude)) {
throw new Error('Exclude parameter must be a glob string or array of glob strings.');
}
// Scan the files in each of the source directories.
var sourceMaps = sourceDirs.map(function (sourceDir) {
return path.join(rootDir, sourceDir);
}).map(function (sourcePath) {
if (!fs.existsSync(sourcePath)) {
throw new Error('Source directory does not exist: ' + sourcePath);
}
return mapDirectory(rootDir, path.relative(rootDir, sourcePath), include, exclude);
});
// Scan the files in the target directory, if it exists.
var targetMap = {};
var targetFullPath = path.join(rootDir, targetDir);
if (fs.existsSync(targetFullPath)) {
targetMap = mapDirectory(rootDir, targetDir, include, exclude);
}
var pathMap = mergePathMaps(sourceMaps, targetMap, targetDir);
var updated = false;
// Iterate in sorted order to ensure directories are created before files under them.
Object.keys(pathMap).sort().forEach(function (subPath) {
var entry = pathMap[subPath];
updated = updatePathWithStats(
entry.sourcePath,
entry.sourceStats,
entry.targetPath,
entry.targetStats,
options,
log) || updated;
});
return updated;
}
/**
* Creates a dictionary map of all files and directories under a path.
*/
function mapDirectory (rootDir, subDir, include, exclude) {
var dirMap = { '': { subDir: subDir, stats: fs.statSync(path.join(rootDir, subDir)) } };
mapSubdirectory(rootDir, subDir, '', include, exclude, dirMap);
return dirMap;
function mapSubdirectory (rootDir, subDir, relativeDir, include, exclude, dirMap) {
var itemMapped = false;
var items = fs.readdirSync(path.join(rootDir, subDir, relativeDir));
items.forEach(function (item) {
var relativePath = path.join(relativeDir, item);
if (!matchGlobArray(relativePath, exclude)) {
// Stats obtained here (required at least to know where to recurse in directories)
// are saved for later, where the modified times may also be used. This minimizes
// the number of file I/O operations performed.
var fullPath = path.join(rootDir, subDir, relativePath);
var stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
// Directories are included if either something under them is included or they
// match an include glob.
if (mapSubdirectory(rootDir, subDir, relativePath, include, exclude, dirMap) ||
matchGlobArray(relativePath, include)) {
dirMap[relativePath] = { subDir: subDir, stats: stats };
itemMapped = true;
}
} else if (stats.isFile()) {
// Files are included only if they match an include glob.
if (matchGlobArray(relativePath, include)) {
dirMap[relativePath] = { subDir: subDir, stats: stats };
itemMapped = true;
}
}
}
});
return itemMapped;
}
function matchGlobArray (path, globs) {
return globs.some(function (elem) {
return minimatch(path, elem, { dot: true });
});
}
}
/**
* Merges together multiple source maps and a target map into a single mapping from
* relative paths to objects with target and source paths and stats.
*/
function mergePathMaps (sourceMaps, targetMap, targetDir) {
// Merge multiple source maps together, along with target path info.
// Entries in later source maps override those in earlier source maps.
// Target stats will be filled in below for targets that exist.
var pathMap = {};
sourceMaps.forEach(function (sourceMap) {
Object.keys(sourceMap).forEach(function (sourceSubPath) {
var sourceEntry = sourceMap[sourceSubPath];
pathMap[sourceSubPath] = {
targetPath: path.join(targetDir, sourceSubPath),
targetStats: null,
sourcePath: path.join(sourceEntry.subDir, sourceSubPath),
sourceStats: sourceEntry.stats
};
});
});
// Fill in target stats for targets that exist, and create entries
// for targets that don't have any corresponding sources.
Object.keys(targetMap).forEach(function (subPath) {
var entry = pathMap[subPath];
if (entry) {
entry.targetStats = targetMap[subPath].stats;
} else {
pathMap[subPath] = {
targetPath: path.join(targetDir, subPath),
targetStats: targetMap[subPath].stats,
sourcePath: null,
sourceStats: null
};
}
});
return pathMap;
}
module.exports = {
updatePath: updatePath,
updatePaths: updatePaths,
mergeAndUpdateDir: mergeAndUpdateDir
};
@@ -0,0 +1,262 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var fs = require('fs-extra');
var path = require('path');
var endent = require('endent');
var mungeutil = require('./ConfigChanges/munge-util');
function PlatformJson (filePath, platform, root) {
this.filePath = filePath;
this.platform = platform;
this.root = fix_munge(root || {});
}
PlatformJson.load = function (plugins_dir, platform) {
var filePath = path.join(plugins_dir, platform + '.json');
var root = null;
if (fs.existsSync(filePath)) {
root = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
return new PlatformJson(filePath, platform, root);
};
PlatformJson.prototype.save = function () {
fs.outputJsonSync(this.filePath, this.root, { spaces: 2 });
};
/**
* Indicates whether the specified plugin is installed as a top-level (not as
* dependency to others)
* @method function
* @param {String} pluginId A plugin id to check for.
* @return {Boolean} true if plugin installed as top-level, otherwise false.
*/
PlatformJson.prototype.isPluginTopLevel = function (pluginId) {
return this.root.installed_plugins[pluginId];
};
/**
* Indicates whether the specified plugin is installed as a dependency to other
* plugin.
* @method function
* @param {String} pluginId A plugin id to check for.
* @return {Boolean} true if plugin installed as a dependency, otherwise false.
*/
PlatformJson.prototype.isPluginDependent = function (pluginId) {
return this.root.dependent_plugins[pluginId];
};
/**
* Indicates whether plugin is installed either as top-level or as dependency.
* @method function
* @param {String} pluginId A plugin id to check for.
* @return {Boolean} true if plugin installed, otherwise false.
*/
PlatformJson.prototype.isPluginInstalled = function (pluginId) {
return this.isPluginTopLevel(pluginId) ||
this.isPluginDependent(pluginId);
};
PlatformJson.prototype.addPlugin = function (pluginId, variables, isTopLevel) {
var pluginsList = isTopLevel
? this.root.installed_plugins
: this.root.dependent_plugins;
pluginsList[pluginId] = variables;
return this;
};
/**
* @chaining
* Generates and adds metadata for provided plugin into associated <platform>.json file
*
* @param {PluginInfo} pluginInfo A pluginInfo instance to add metadata from
* @returns {this} Current PlatformJson instance to allow calls chaining
*/
PlatformJson.prototype.addPluginMetadata = function (pluginInfo) {
var installedModules = this.root.modules || [];
var installedPaths = installedModules.map(function (installedModule) {
return installedModule.file;
});
var modulesToInstall = pluginInfo.getJsModules(this.platform)
.map(function (module) {
return new ModuleMetadata(pluginInfo.id, module);
})
.filter(function (metadata) {
// Filter out modules which are already added to metadata
return !installedPaths.includes(metadata.file);
});
this.root.modules = installedModules.concat(modulesToInstall);
this.root.plugin_metadata = this.root.plugin_metadata || {};
this.root.plugin_metadata[pluginInfo.id] = pluginInfo.version;
return this;
};
PlatformJson.prototype.removePlugin = function (pluginId, isTopLevel) {
var pluginsList = isTopLevel
? this.root.installed_plugins
: this.root.dependent_plugins;
delete pluginsList[pluginId];
return this;
};
/**
* @chaining
* Removes metadata for provided plugin from associated file
*
* @param {PluginInfo} pluginInfo A PluginInfo instance to which modules' metadata
* we need to remove
*
* @returns {this} Current PlatformJson instance to allow calls chaining
*/
PlatformJson.prototype.removePluginMetadata = function (pluginInfo) {
var modulesToRemove = pluginInfo.getJsModules(this.platform)
.map(function (jsModule) {
return ['plugins', pluginInfo.id, jsModule.src].join('/');
});
var installedModules = this.root.modules || [];
this.root.modules = installedModules
.filter(function (installedModule) {
// Leave only those metadatas which 'file' is not in removed modules
return !modulesToRemove.includes(installedModule.file);
});
if (this.root.plugin_metadata) {
delete this.root.plugin_metadata[pluginInfo.id];
}
return this;
};
PlatformJson.prototype.addInstalledPluginToPrepareQueue = function (pluginDirName, vars, is_top_level, force) {
this.root.prepare_queue.installed.push({ plugin: pluginDirName, vars: vars, topLevel: is_top_level, force: force });
};
PlatformJson.prototype.addUninstalledPluginToPrepareQueue = function (pluginId, is_top_level) {
this.root.prepare_queue.uninstalled.push({ plugin: pluginId, id: pluginId, topLevel: is_top_level });
};
/**
* Moves plugin, specified by id to top-level plugins. If plugin is top-level
* already, then does nothing.
* @method function
* @param {String} pluginId A plugin id to make top-level.
* @return {PlatformJson} PlatformJson instance.
*/
PlatformJson.prototype.makeTopLevel = function (pluginId) {
var plugin = this.root.dependent_plugins[pluginId];
if (plugin) {
delete this.root.dependent_plugins[pluginId];
this.root.installed_plugins[pluginId] = plugin;
}
return this;
};
/**
* Generates a metadata for all installed plugins and js modules. The resultant
* string is ready to be written to 'cordova_plugins.js'
*
* @returns {String} cordova_plugins.js contents
*/
PlatformJson.prototype.generateMetadata = function () {
const stringify = o => JSON.stringify(o, null, 2);
return endent`
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = ${stringify(this.root.modules)};
module.exports.metadata = ${stringify(this.root.plugin_metadata)};
});
`;
};
/**
* @chaining
* Generates and then saves metadata to specified file. Doesn't check if file exists.
*
* @param {String} destination File metadata will be written to
* @return {PlatformJson} PlatformJson instance
*/
PlatformJson.prototype.generateAndSaveMetadata = function (destination) {
fs.outputFileSync(destination, this.generateMetadata());
return this;
};
// convert a munge from the old format ([file][parent][xml] = count) to the current one
function fix_munge (root) {
root.prepare_queue = root.prepare_queue || { installed: [], uninstalled: [] };
root.config_munge = root.config_munge || { files: {} };
root.installed_plugins = root.installed_plugins || {};
root.dependent_plugins = root.dependent_plugins || {};
var munge = root.config_munge;
if (!munge.files) {
var new_munge = { files: {} };
for (var file in munge) {
for (var selector in munge[file]) {
for (var xml_child in munge[file][selector]) {
var val = parseInt(munge[file][selector][xml_child]);
for (var i = 0; i < val; i++) {
mungeutil.deep_add(new_munge, [file, selector, { xml: xml_child, count: val }]);
}
}
}
}
root.config_munge = new_munge;
}
return root;
}
/**
* @constructor
* @class ModuleMetadata
*
* Creates a ModuleMetadata object that represents module entry in 'cordova_plugins.js'
* file at run time
*
* @param {String} pluginId Plugin id where this module installed from
* @param (JsModule|Object) jsModule A js-module entry from PluginInfo class to generate metadata for
*/
function ModuleMetadata (pluginId, jsModule) {
if (!pluginId) throw new TypeError('pluginId argument must be a valid plugin id');
if (!jsModule.src && !jsModule.name) throw new TypeError('jsModule argument must contain src or/and name properties');
this.id = pluginId + '.' + (jsModule.name || jsModule.src.match(/([^/]+)\.js/)[1]);
this.file = ['plugins', pluginId, jsModule.src].join('/');
this.pluginId = pluginId;
if (jsModule.clobbers && jsModule.clobbers.length > 0) {
this.clobbers = jsModule.clobbers.map(function (o) { return o.target; });
}
if (jsModule.merges && jsModule.merges.length > 0) {
this.merges = jsModule.merges.map(function (o) { return o.target; });
}
if (jsModule.runs) {
this.runs = true;
}
}
module.exports = PlatformJson;
@@ -0,0 +1,494 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
A class for holidng the information currently stored in plugin.xml
It should also be able to answer questions like whether the plugin
is compatible with a given engine version.
TODO (kamrik): refactor this to not use sync functions and return promises.
*/
var path = require('path');
var fs = require('fs-extra');
var xml_helpers = require('../util/xml-helpers');
var CordovaError = require('../CordovaError/CordovaError');
function PluginInfo (dirname) {
var self = this;
// METHODS
// Defined inside the constructor to avoid the "this" binding problems.
// <preference> tag
// Example: <preference name="API_KEY" />
// Used to require a variable to be specified via --variable when installing the plugin.
// returns { key : default | null}
self.getPreferences = getPreferences;
function getPreferences (platform) {
return _getTags(self._et, 'preference', platform, _parsePreference)
.reduce(function (preferences, pref) {
preferences[pref.preference] = pref.default;
return preferences;
}, {});
}
function _parsePreference (prefTag) {
var name = prefTag.attrib.name.toUpperCase();
var def = prefTag.attrib.default || null;
return { preference: name, default: def };
}
// <asset>
self.getAssets = getAssets;
function getAssets (platform) {
var assets = _getTags(self._et, 'asset', platform, _parseAsset);
return assets;
}
function _parseAsset (tag) {
var src = tag.attrib.src;
var target = tag.attrib.target;
if (!src || !target) {
var msg =
'Malformed <asset> tag. Both "src" and "target" attributes' +
'must be specified in\n' +
self.filepath
;
throw new Error(msg);
}
var asset = {
itemType: 'asset',
src: src,
target: target
};
return asset;
}
// <dependency>
// Example:
// <dependency id="com.plugin.id"
// url="https://github.com/myuser/someplugin"
// commit="428931ada3891801"
// subdir="some/path/here" />
self.getDependencies = getDependencies;
function getDependencies (platform) {
var deps = _getTags(
self._et,
'dependency',
platform,
_parseDependency
);
return deps;
}
function _parseDependency (tag) {
var dep =
{ id: tag.attrib.id,
version: tag.attrib.version || '',
url: tag.attrib.url || '',
subdir: tag.attrib.subdir || '',
commit: tag.attrib.commit
};
dep.git_ref = dep.commit;
if (!dep.id) {
var msg =
'<dependency> tag is missing id attribute in ' +
self.filepath
;
throw new CordovaError(msg);
}
return dep;
}
// <config-file> tag
self.getConfigFiles = getConfigFiles;
function getConfigFiles (platform) {
var configFiles = _getTags(self._et, 'config-file', platform, _parseConfigFile);
return configFiles;
}
function _parseConfigFile (tag) {
var configFile =
{ target: tag.attrib['target'],
parent: tag.attrib['parent'],
after: tag.attrib['after'],
xmls: tag.getchildren(),
// To support demuxing via versions
versions: tag.attrib['versions'],
deviceTarget: tag.attrib['device-target']
};
return configFile;
}
self.getEditConfigs = getEditConfigs;
function getEditConfigs (platform) {
var editConfigs = _getTags(self._et, 'edit-config', platform, _parseEditConfigs);
return editConfigs;
}
function _parseEditConfigs (tag) {
var editConfig =
{ file: tag.attrib['file'],
target: tag.attrib['target'],
mode: tag.attrib['mode'],
xmls: tag.getchildren()
};
return editConfig;
}
// <info> tags, both global and within a <platform>
// TODO (kamrik): Do we ever use <info> under <platform>? Example wanted.
self.getInfo = getInfo;
function getInfo (platform) {
var infos = _getTags(
self._et,
'info',
platform,
function (elem) { return elem.text; }
);
// Filter out any undefined or empty strings.
infos = infos.filter(Boolean);
return infos;
}
// <source-file>
// Examples:
// <source-file src="src/ios/someLib.a" framework="true" />
// <source-file src="src/ios/someLib.a" compiler-flags="-fno-objc-arc" />
self.getSourceFiles = getSourceFiles;
function getSourceFiles (platform) {
var sourceFiles = _getTagsInPlatform(self._et, 'source-file', platform, _parseSourceFile);
return sourceFiles;
}
function _parseSourceFile (tag) {
return {
itemType: 'source-file',
src: tag.attrib.src,
framework: isStrTrue(tag.attrib.framework),
weak: isStrTrue(tag.attrib.weak),
compilerFlags: tag.attrib['compiler-flags'],
targetDir: tag.attrib['target-dir']
};
}
// <header-file>
// Example:
// <header-file src="CDVFoo.h" />
self.getHeaderFiles = getHeaderFiles;
function getHeaderFiles (platform) {
var headerFiles = _getTagsInPlatform(self._et, 'header-file', platform, function (tag) {
return {
itemType: 'header-file',
src: tag.attrib.src,
targetDir: tag.attrib['target-dir'],
type: tag.attrib['type']
};
});
return headerFiles;
}
// <resource-file>
// Example:
// <resource-file src="FooPluginStrings.xml" target="res/values/FooPluginStrings.xml" device-target="win" arch="x86" versions="&gt;=8.1" />
self.getResourceFiles = getResourceFiles;
function getResourceFiles (platform) {
var resourceFiles = _getTagsInPlatform(self._et, 'resource-file', platform, function (tag) {
return {
itemType: 'resource-file',
src: tag.attrib.src,
target: tag.attrib.target,
versions: tag.attrib.versions,
deviceTarget: tag.attrib['device-target'],
arch: tag.attrib.arch,
reference: tag.attrib.reference
};
});
return resourceFiles;
}
// <lib-file>
// Example:
// <lib-file src="src/BlackBerry10/native/device/libfoo.so" arch="device" />
self.getLibFiles = getLibFiles;
function getLibFiles (platform) {
var libFiles = _getTagsInPlatform(self._et, 'lib-file', platform, function (tag) {
return {
itemType: 'lib-file',
src: tag.attrib.src,
arch: tag.attrib.arch,
Include: tag.attrib.Include,
versions: tag.attrib.versions,
deviceTarget: tag.attrib['device-target'] || tag.attrib.target
};
});
return libFiles;
}
// <podspec>
// Example:
// <podspec>
// <config>
// <source url="https://github.com/brightcove/BrightcoveSpecs.git" />
// <source url="https://github.com/CocoaPods/Specs.git"/>
// </config>
// <pods use-frameworks="true" inhibit-all-warnings="true">
// <pod name="PromiseKit" />
// <pod name="Foobar1" spec="~> 2.0.0" />
// <pod name="Foobar2" git="git@github.com:hoge/foobar1.git" />
// <pod name="Foobar3" git="git@github.com:hoge/foobar2.git" branch="next" />
// <pod name="Foobar4" swift-version="4.1" />
// <pod name="Foobar5" swift-version="3.0" />
// </pods>
// </podspec>
self.getPodSpecs = getPodSpecs;
function getPodSpecs (platform) {
var podSpecs = _getTagsInPlatform(self._et, 'podspec', platform, function (tag) {
var declarations = null;
var sources = null;
var libraries = null;
var config = tag.find('config');
var pods = tag.find('pods');
if (config != null) {
sources = config.findall('source').map(function (t) {
return {
url: t.attrib.url
};
}).reduce(function (acc, val) {
return Object.assign({}, acc, { [val.url]: { source: val.url } });
}, {});
}
if (pods != null) {
declarations = Object.keys(pods.attrib).reduce(function (acc, key) {
return pods.attrib[key] === undefined ? acc : Object.assign({}, acc, { [key]: pods.attrib[key] });
}, {});
libraries = pods.findall('pod').map(function (t) {
return Object.keys(t.attrib).reduce(function (acc, key) {
return t.attrib[key] === undefined ? acc : Object.assign({}, acc, { [key]: t.attrib[key] });
}, {});
}).reduce(function (acc, val) {
return Object.assign({}, acc, { [val.name]: val });
}, {});
}
return {
declarations: declarations,
sources: sources,
libraries: libraries
};
});
return podSpecs;
}
// <hook>
// Example:
// <hook type="before_build" src="scripts/beforeBuild.js" />
self.getHookScripts = getHookScripts;
function getHookScripts (hook, platforms) {
var scriptElements = self._et.findall('./hook');
if (platforms) {
platforms.forEach(function (platform) {
scriptElements = scriptElements.concat(self._et.findall('./platform[@name="' + platform + '"]/hook'));
});
}
function filterScriptByHookType (el) {
return el.attrib.src && el.attrib.type && el.attrib.type.toLowerCase() === hook;
}
return scriptElements.filter(filterScriptByHookType);
}
self.getJsModules = getJsModules;
function getJsModules (platform) {
var modules = _getTags(self._et, 'js-module', platform, _parseJsModule);
return modules;
}
function _parseJsModule (tag) {
var ret = {
itemType: 'js-module',
name: tag.attrib.name,
src: tag.attrib.src,
clobbers: tag.findall('clobbers').map(function (tag) { return { target: tag.attrib.target }; }),
merges: tag.findall('merges').map(function (tag) { return { target: tag.attrib.target }; }),
runs: tag.findall('runs').length > 0
};
return ret;
}
self.getEngines = function () {
return self._et.findall('engines/engine').map(function (n) {
return {
name: n.attrib.name,
version: n.attrib.version,
platform: n.attrib.platform,
scriptSrc: n.attrib.scriptSrc
};
});
};
self.getPlatforms = function () {
return self._et.findall('platform').map(function (n) {
return { name: n.attrib.name };
});
};
self.getPlatformsArray = function () {
return self._et.findall('platform').map(function (n) {
return n.attrib.name;
});
};
self.getFrameworks = function (platform, options) {
return _getTags(self._et, 'framework', platform, function (el) {
var src = el.attrib.src;
if (options) {
var vars = options.cli_variables || {};
if (Object.keys(vars).length === 0) {
// get variable defaults from plugin.xml for removal
vars = self.getPreferences(platform);
}
var regExp;
// Iterate over plugin variables.
// Replace them in framework src if they exist
Object.keys(vars).forEach(function (name) {
if (vars[name]) {
regExp = new RegExp('\\$' + name, 'g');
src = src.replace(regExp, vars[name]);
}
});
}
var ret = {
itemType: 'framework',
type: el.attrib.type,
parent: el.attrib.parent,
custom: isStrTrue(el.attrib.custom),
embed: isStrTrue(el.attrib.embed),
src: src,
spec: el.attrib.spec,
weak: isStrTrue(el.attrib.weak),
versions: el.attrib.versions,
targetDir: el.attrib['target-dir'],
deviceTarget: el.attrib['device-target'] || el.attrib.target,
arch: el.attrib.arch,
implementation: el.attrib.implementation
};
return ret;
});
};
self.getFilesAndFrameworks = getFilesAndFrameworks;
function getFilesAndFrameworks (platform, options) {
// Please avoid changing the order of the calls below, files will be
// installed in this order.
var items = [].concat(
self.getSourceFiles(platform),
self.getHeaderFiles(platform),
self.getResourceFiles(platform),
self.getFrameworks(platform, options),
self.getLibFiles(platform)
);
return items;
}
/// // End of PluginInfo methods /////
/// // PluginInfo Constructor logic /////
self.filepath = path.join(dirname, 'plugin.xml');
if (!fs.existsSync(self.filepath)) {
throw new CordovaError('Cannot find plugin.xml for plugin "' + path.basename(dirname) + '". Please try adding it again.');
}
self.dir = dirname;
var et = self._et = xml_helpers.parseElementtreeSync(self.filepath);
var pelem = et.getroot();
self.id = pelem.attrib.id;
self.version = pelem.attrib.version;
// Optional fields
self.name = pelem.findtext('name');
self.description = pelem.findtext('description');
self.license = pelem.findtext('license');
self.repo = pelem.findtext('repo');
self.issue = pelem.findtext('issue');
self.keywords = pelem.findtext('keywords');
self.info = pelem.findtext('info');
if (self.keywords) {
self.keywords = self.keywords.split(',').map(function (s) { return s.trim(); });
}
self.getKeywordsAndPlatforms = function () {
var ret = self.keywords || [];
return ret.concat('ecosystem:cordova').concat(addCordova(self.getPlatformsArray()));
};
} // End of PluginInfo constructor.
// Helper function used to prefix every element of an array with cordova-
// Useful when we want to modify platforms to be cordova-platform
function addCordova (someArray) {
var newArray = someArray.map(function (element) {
return 'cordova-' + element;
});
return newArray;
}
// Helper function used by most of the getSomething methods of PluginInfo.
// Get all elements of a given name. Both in root and in platform sections
// for the given platform. If transform is given and is a function, it is
// applied to each element.
function _getTags (pelem, tag, platform, transform) {
var platformTag = pelem.find('./platform[@name="' + platform + '"]');
var tagsInRoot = pelem.findall(tag);
tagsInRoot = tagsInRoot || [];
var tagsInPlatform = platformTag ? platformTag.findall(tag) : [];
var tags = tagsInRoot.concat(tagsInPlatform);
if (typeof transform === 'function') {
tags = tags.map(transform);
}
return tags;
}
// Same as _getTags() but only looks inside a platform section.
function _getTagsInPlatform (pelem, tag, platform, transform) {
var platformTag = pelem.find('./platform[@name="' + platform + '"]');
var tags = platformTag ? platformTag.findall(tag) : [];
if (typeof transform === 'function') {
tags = tags.map(transform);
}
return tags;
}
// Check if x is a string 'true'.
function isStrTrue (x) {
return String(x).toLowerCase() === 'true';
}
module.exports = PluginInfo;
// Backwards compat:
PluginInfo.PluginInfo = PluginInfo;
PluginInfo.loadPluginsDir = function (dir) {
var PluginInfoProvider = require('./PluginInfoProvider');
return new PluginInfoProvider().getAllWithinSearchPath(dir);
};
@@ -0,0 +1,82 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/* jshint sub:true, laxcomma:true, laxbreak:true */
var fs = require('fs-extra');
var path = require('path');
var PluginInfo = require('./PluginInfo');
var events = require('../events');
function PluginInfoProvider () {
this._cache = {};
this._getAllCache = {};
}
PluginInfoProvider.prototype.get = function (dirName) {
var absPath = path.resolve(dirName);
if (!this._cache[absPath]) {
this._cache[absPath] = new PluginInfo(dirName);
}
return this._cache[absPath];
};
// Normally you don't need to put() entries, but it's used
// when copying plugins, and in unit tests.
PluginInfoProvider.prototype.put = function (pluginInfo) {
var absPath = path.resolve(pluginInfo.dir);
this._cache[absPath] = pluginInfo;
};
// Used for plugin search path processing.
// Given a dir containing multiple plugins, create a PluginInfo object for
// each of them and return as array.
// Should load them all in parallel and return a promise, but not yet.
PluginInfoProvider.prototype.getAllWithinSearchPath = function (dirName) {
var absPath = path.resolve(dirName);
if (!this._getAllCache[absPath]) {
this._getAllCache[absPath] = getAllHelper(absPath, this);
}
return this._getAllCache[absPath];
};
function getAllHelper (absPath, provider) {
if (!fs.existsSync(absPath)) {
return [];
}
// If dir itself is a plugin, return it in an array with one element.
if (fs.existsSync(path.join(absPath, 'plugin.xml'))) {
return [provider.get(absPath)];
}
var subdirs = fs.readdirSync(absPath);
var plugins = [];
subdirs.forEach(function (subdir) {
var d = path.join(absPath, subdir);
if (fs.existsSync(path.join(d, 'plugin.xml'))) {
try {
plugins.push(provider.get(d));
} catch (e) {
events.emit('warn', 'Error parsing ' + path.join(d, 'plugin.xml.\n' + e.stack));
}
}
});
return plugins;
}
module.exports = PluginInfoProvider;
@@ -0,0 +1,149 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var Q = require('q');
var fs = require('fs-extra');
var path = require('path');
var ActionStack = require('./ActionStack');
var PlatformJson = require('./PlatformJson');
var CordovaError = require('./CordovaError/CordovaError');
var PlatformMunger = require('./ConfigChanges/ConfigChanges').PlatformMunger;
var PluginInfoProvider = require('./PluginInfo/PluginInfoProvider');
/**
* @constructor
* @class PluginManager
* Represents an entity for adding/removing plugins for platforms
*
* @param {String} platform Platform name
* @param {Object} locations - Platform files and directories
* @param {IDEProject} ideProject The IDE project to add/remove plugin changes to/from
*/
function PluginManager (platform, locations, ideProject) {
this.platform = platform;
this.locations = locations;
this.project = ideProject;
var platformJson = PlatformJson.load(locations.root, platform);
this.munger = new PlatformMunger(platform, locations.root, platformJson, new PluginInfoProvider());
}
/**
* @constructs PluginManager
* A convenience shortcut to new PluginManager(...)
*
* @param {String} platform Platform name
* @param {Object} locations - Platform files and directories
* @param {IDEProject} ideProject The IDE project to add/remove plugin changes to/from
* @returns new PluginManager instance
*/
PluginManager.get = function (platform, locations, ideProject) {
return new PluginManager(platform, locations, ideProject);
};
PluginManager.INSTALL = 'install';
PluginManager.UNINSTALL = 'uninstall';
module.exports = PluginManager;
/**
* Describes and implements common plugin installation/uninstallation routine. The flow is the following:
* * Validate and set defaults for options. Note that options are empty by default. Everything
* needed for platform IDE project must be passed from outside. Plugin variables (which
* are the part of the options) also must be already populated with 'PACKAGE_NAME' variable.
* * Collect all plugin's native and web files, get installers/uninstallers and process
* all these via ActionStack.
* * Save the IDE project, so the changes made by installers are persisted.
* * Generate config changes munge for plugin and apply it to all required files
* * Generate metadata for plugin and plugin modules and save it to 'cordova_plugins.js'
*
* @param {PluginInfo} plugin A PluginInfo structure representing plugin to install
* @param {Object} [options={}] An installation options. It is expected but is not necessary
* that options would contain 'variables' inner object with 'PACKAGE_NAME' field set by caller.
*
* @returns {Promise} Returns a Q promise, either resolved in case of success, rejected otherwise.
*/
PluginManager.prototype.doOperation = function (operation, plugin, options) {
if (operation !== PluginManager.INSTALL && operation !== PluginManager.UNINSTALL) { return Q.reject(new CordovaError('The parameter is incorrect. The opeation must be either "add" or "remove"')); }
if (!plugin || plugin.constructor.name !== 'PluginInfo') { return Q.reject(new CordovaError('The parameter is incorrect. The first parameter should be a PluginInfo instance')); }
// Set default to empty object to play safe when accesing properties
options = options || {};
var self = this;
var actions = new ActionStack();
// gather all files need to be handled during operation ...
plugin.getFilesAndFrameworks(this.platform, options)
.concat(plugin.getAssets(this.platform))
.concat(plugin.getJsModules(this.platform))
// ... put them into stack ...
.forEach(function (item) {
var installer = self.project.getInstaller(item.itemType);
var uninstaller = self.project.getUninstaller(item.itemType);
var actionArgs = [item, plugin, self.project, options];
var action;
if (operation === PluginManager.INSTALL) {
action = actions.createAction(installer, actionArgs, uninstaller, actionArgs);
} else /* op === PluginManager.UNINSTALL */{
action = actions.createAction(uninstaller, actionArgs, installer, actionArgs);
}
actions.push(action);
});
// ... and run through the action stack
return actions.process(this.platform)
.then(function () {
if (self.project.write) {
self.project.write();
}
if (operation === PluginManager.INSTALL) {
// Ignore passed `is_top_level` option since platform itself doesn't know
// anything about managing dependencies - it's responsibility of caller.
self.munger.add_plugin_changes(plugin, options.variables, /* is_top_level= */true, /* should_increment= */true, options.force);
self.munger.platformJson.addPluginMetadata(plugin);
} else {
self.munger.remove_plugin_changes(plugin, /* is_top_level= */true);
self.munger.platformJson.removePluginMetadata(plugin);
}
// Save everything (munge and plugin/modules metadata)
self.munger.save_all();
var metadata = self.munger.platformJson.generateMetadata();
fs.writeFileSync(path.join(self.locations.www, 'cordova_plugins.js'), metadata, 'utf-8');
// CB-11022 save plugin metadata to both www and platform_www if options.usePlatformWww is specified
if (options.usePlatformWww) {
fs.writeFileSync(path.join(self.locations.platformWww, 'cordova_plugins.js'), metadata, 'utf-8');
}
});
};
PluginManager.prototype.addPlugin = function (plugin, installOptions) {
return this.doOperation(PluginManager.INSTALL, plugin, installOptions);
};
PluginManager.prototype.removePlugin = function (plugin, uninstallOptions) {
return this.doOperation(PluginManager.UNINSTALL, plugin, uninstallOptions);
};
+81
View File
@@ -0,0 +1,81 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
const EventEmitter = require('events').EventEmitter;
const MAX_LISTENERS = 20;
const INSTANCE_KEY = Symbol.for('org.apache.cordova.common.CordovaEvents');
let EVENTS_RECEIVER = null;
class CordovaEventEmitter extends EventEmitter {
/**
* Sets up current instance to forward emitted events to another EventEmitter
* instance.
*
* @param {EventEmitter} [eventEmitter] The emitter instance to forward
* events to. Falsy value, when passed, disables forwarding.
*/
forwardEventsTo (eventEmitter) {
// If no argument is specified disable events forwarding
if (!eventEmitter) {
EVENTS_RECEIVER = undefined;
return;
}
if (!(eventEmitter instanceof EventEmitter)) {
throw new Error('Cordova events can be redirected to another EventEmitter instance only');
}
// CB-10940 Skipping forwarding to self to avoid infinite recursion.
// This is the case when the modules are npm-linked.
if (this !== eventEmitter) {
EVENTS_RECEIVER = eventEmitter;
} else {
// Reset forwarding if we are subscribing to self
EVENTS_RECEIVER = undefined;
}
}
/**
* Sets up current instance to forward emitted events to another EventEmitter
* instance.
*
* @param {EventEmitter} [eventEmitter] The emitter instance to forward
* events to. Falsy value, when passed, disables forwarding.
*/
emit (eventName, ...args) {
if (EVENTS_RECEIVER) {
EVENTS_RECEIVER.emit(eventName, ...args);
}
return super.emit(eventName, ...args);
}
}
// This singleton instance pattern is based on the ideas from
// https://derickbailey.com/2016/03/09/creating-a-true-singleton-in-node-js-with-es6-symbols/
if (Object.getOwnPropertySymbols(global).indexOf(INSTANCE_KEY) === -1) {
const events = new CordovaEventEmitter();
events.setMaxListeners(MAX_LISTENERS);
global[INSTANCE_KEY] = events;
}
module.exports = global[INSTANCE_KEY];
@@ -0,0 +1,155 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var crossSpawn = require('cross-spawn');
var fs = require('fs-extra');
var _ = require('underscore');
var Q = require('q');
var events = require('./events');
var iswin32 = process.platform === 'win32';
/**
* A special implementation for child_process.spawn that handles
* Windows-specific issues with batch files and spaces in paths. Returns a
* promise that succeeds only for return code 0. It is also possible to
* subscribe on spawned process' stdout and stderr streams using progress
* handler for resultant promise.
*
* @example spawn('mycommand', [], {stdio: 'pipe'}) .progress(function (stdio){
* if (stdio.stderr) { console.error(stdio.stderr); } })
* .then(function(result){ // do other stuff })
*
* @param {String} cmd A command to spawn
* @param {String[]} [args=[]] An array of arguments, passed to spawned
* process
* @param {Object} [opts={}] A configuration object
* @param {String|String[]|Object} opts.stdio Property that configures how
* spawned process' stdio will behave. Has the same meaning and possible
* values as 'stdio' options for child_process.spawn method
* (https://nodejs.org/api/child_process.html#child_process_options_stdio).
* @param {Object} [env={}] A map of extra environment variables
* @param {String} [cwd=process.cwd()] Working directory for the command
* @param {Boolean} [chmod=false] If truthy, will attempt to set the execute
* bit before executing on non-Windows platforms
*
* @return {Promise} A promise that is either fulfilled if the spawned
* process is exited with zero error code or rejected otherwise. If the
* 'stdio' option set to 'default' or 'pipe', the promise also emits progress
* messages with the following contents:
* {
* 'stdout': ...,
* 'stderr': ...
* }
*/
exports.spawn = function (cmd, args, opts) {
args = args || [];
opts = opts || {};
var spawnOpts = {};
var d = Q.defer();
if (opts.stdio !== 'default') {
// Ignore 'default' value for stdio because it corresponds to child_process's default 'pipe' option
spawnOpts.stdio = opts.stdio;
}
if (opts.cwd) {
spawnOpts.cwd = opts.cwd;
}
if (opts.env) {
spawnOpts.env = _.extend(_.extend({}, process.env), opts.env);
}
if (opts.chmod && !iswin32) {
try {
// This fails when module is installed in a system directory (e.g. via sudo npm install)
fs.chmodSync(cmd, '755');
} catch (e) {
// If the perms weren't set right, then this will come as an error upon execution.
}
}
events.emit(opts.printCommand ? 'log' : 'verbose', 'Running command: ' + cmd + ' ' + args.join(' '));
// At least until Node.js 8, child_process.spawn will throw exceptions
// instead of emitting error events in certain cases (like EACCES), Thus we
// have to wrap the execution in try/catch to convert them into rejections.
try {
var child = crossSpawn.spawn(cmd, args, spawnOpts);
} catch (e) {
whenDone(e);
return d.promise;
}
var capturedOut = '';
var capturedErr = '';
if (child.stdout) {
child.stdout.setEncoding('utf8');
child.stdout.on('data', function (data) {
capturedOut += data;
d.notify({ stdout: data });
});
}
if (child.stderr) {
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
capturedErr += data;
d.notify({ stderr: data });
});
}
child.on('close', whenDone);
child.on('error', whenDone);
function whenDone (arg) {
if (child) {
child.removeListener('close', whenDone);
child.removeListener('error', whenDone);
}
var code = typeof arg === 'number' ? arg : arg && arg.code;
events.emit('verbose', 'Command finished with error code ' + code + ': ' + cmd + ' ' + args);
if (code === 0) {
d.resolve(capturedOut.trim());
} else {
var errMsg = cmd + ': Command failed with exit code ' + code;
if (capturedErr) {
errMsg += ' Error output:\n' + capturedErr.trim();
}
var err = new Error(errMsg);
if (capturedErr) {
err.stderr = capturedErr;
}
if (capturedOut) {
err.stdout = capturedOut;
}
err.code = code;
d.reject(err);
}
}
return d.promise;
};
exports.maybeSpawn = function (cmd, args, opts) {
if (fs.existsSync(cmd)) {
return exports.spawn(cmd, args, opts);
}
return Q(null);
};
@@ -0,0 +1,31 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
module.exports = function addProperty (module, property, modulePath, obj) {
obj = obj || module.exports;
// Add properties as getter to delay load the modules on first invocation
Object.defineProperty(obj, property, {
configurable: true,
get: function () {
var delayLoadedModule = module.require(modulePath);
obj[property] = delayLoadedModule;
return delayLoadedModule;
}
});
};
@@ -0,0 +1,53 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
const CordovaError = require('../CordovaError/CordovaError');
/**
* Formats an error for logging.
*
* @param {Error} error - The error to be formatted.
* @param {boolean} isVerbose - Whether the include additional debugging
* information when formatting the error.
*
* @returns {string} The formatted error message.
*/
module.exports = function formatError (error, isVerbose) {
var message = '';
if (error instanceof CordovaError) {
message = error.toString(isVerbose);
} else if (error instanceof Error) {
if (isVerbose) {
message = error.stack;
} else {
message = error.message;
}
} else {
// Plain text error message
message = error;
}
if (typeof message === 'string' && !message.toUpperCase().startsWith('ERROR:')) {
// Needed for backward compatibility with external tools
message = 'Error: ' + message;
}
return message;
};
@@ -0,0 +1,95 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
// contains PLIST utility functions
var __ = require('underscore');
var plist = require('plist');
// adds node to doc at selector
module.exports.graftPLIST = graftPLIST;
function graftPLIST (doc, xml, selector) {
var obj = plist.parse('<plist>' + xml + '</plist>');
var node = doc[selector];
if (node && Array.isArray(node) && Array.isArray(obj)) {
node = node.concat(obj);
for (var i = 0; i < node.length; i++) {
for (var j = i + 1; j < node.length; ++j) {
if (nodeEqual(node[i], node[j])) { node.splice(j--, 1); }
}
}
doc[selector] = node;
} else {
// plist uses objects for <dict>. If we have two dicts we merge them instead of
// overriding the old one. See CB-6472
if (node && __.isObject(node) && __.isObject(obj) && !__.isDate(node) && !__.isDate(obj)) { // arrays checked above
__.extend(obj, node);
}
doc[selector] = obj;
}
return true;
}
// removes node from doc at selector
module.exports.prunePLIST = prunePLIST;
function prunePLIST (doc, xml, selector) {
var obj = plist.parse('<plist>' + xml + '</plist>');
pruneOBJECT(doc, selector, obj);
return true;
}
function pruneOBJECT (doc, selector, fragment) {
if (Array.isArray(fragment) && Array.isArray(doc[selector])) {
var empty = true;
for (var i in fragment) {
for (var j in doc[selector]) {
empty = pruneOBJECT(doc[selector], j, fragment[i]) && empty;
}
}
if (empty) {
delete doc[selector];
return true;
}
} else if (nodeEqual(doc[selector], fragment)) {
delete doc[selector];
return true;
}
return false;
}
function nodeEqual (node1, node2) {
if (typeof node1 !== typeof node2) { return false; } else if (typeof node1 === 'string') {
node2 = escapeRE(node2).replace(/\\\$\(\S+\)/gm, '(.*?)');
return new RegExp('^' + node2 + '$').test(node1);
} else {
for (var key in node2) {
if (!nodeEqual(node1[key], node2[key])) return false;
}
return true;
}
}
// escape string for use in regex
function escapeRE (str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
@@ -0,0 +1,339 @@
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/**
* contains XML utility functions, some of which are specific to elementtree
*/
var fs = require('fs-extra');
var path = require('path');
var _ = require('underscore');
var et = require('elementtree');
var stripBom = require('strip-bom');
var ROOT = /^\/([^/]*)/;
var ABSOLUTE = /^\/([^/]*)\/(.*)/;
module.exports = {
// compare two et.XML nodes, see if they match
// compares tagName, text, attributes and children (recursively)
equalNodes: function (one, two) {
if (one.tag !== two.tag) {
return false;
} else if (one.text.trim() !== two.text.trim()) {
return false;
} else if (one._children.length !== two._children.length) {
return false;
}
if (!attribMatch(one, two)) return false;
for (var i = 0; i < one._children.length; i++) {
if (!module.exports.equalNodes(one._children[i], two._children[i])) {
return false;
}
}
return true;
},
// adds node to doc at selector, creating parent if it doesn't exist
graftXML: function (doc, nodes, selector, after) {
var parent = module.exports.resolveParent(doc, selector);
if (!parent) {
// Try to create the parent recursively if necessary
try {
var parentToCreate = et.XML('<' + path.basename(selector) + '/>');
var parentSelector = path.dirname(selector);
this.graftXML(doc, [parentToCreate], parentSelector);
} catch (e) {
return false;
}
parent = module.exports.resolveParent(doc, selector);
if (!parent) return false;
}
nodes.forEach(function (node) {
// check if child is unique first
if (uniqueChild(node, parent)) {
var children = parent.getchildren();
var insertIdx = after ? findInsertIdx(children, after) : children.length;
// TODO: replace with parent.insert after the bug in ElementTree is fixed
parent.getchildren().splice(insertIdx, 0, node);
}
});
return true;
},
// adds new attributes to doc at selector
// Will only merge if attribute has not been modified already or --force is used
graftXMLMerge: function (doc, nodes, selector, xml) {
var target = module.exports.resolveParent(doc, selector);
if (!target) return false;
// saves the attributes of the original xml before making changes
xml.oldAttrib = _.extend({}, target.attrib);
nodes.forEach(function (node) {
var attributes = node.attrib;
for (var attribute in attributes) {
target.attrib[attribute] = node.attrib[attribute];
}
});
return true;
},
// overwrite all attributes to doc at selector with new attributes
// Will only overwrite if attribute has not been modified already or --force is used
graftXMLOverwrite: function (doc, nodes, selector, xml) {
var target = module.exports.resolveParent(doc, selector);
if (!target) return false;
// saves the attributes of the original xml before making changes
xml.oldAttrib = _.extend({}, target.attrib);
// remove old attributes from target
var targetAttributes = target.attrib;
for (var targetAttribute in targetAttributes) {
delete targetAttributes[targetAttribute];
}
// add new attributes to target
nodes.forEach(function (node) {
var attributes = node.attrib;
for (var attribute in attributes) {
target.attrib[attribute] = node.attrib[attribute];
}
});
return true;
},
// removes node from doc at selector
pruneXML: function (doc, nodes, selector) {
var parent = module.exports.resolveParent(doc, selector);
if (!parent) return false;
nodes.forEach(function (node) {
var matchingKid = findChild(node, parent);
if (matchingKid !== undefined) {
// stupid elementtree takes an index argument it doesn't use
// and does not conform to the python lib
parent.remove(matchingKid);
}
});
return true;
},
// restores attributes from doc at selector
pruneXMLRestore: function (doc, selector, xml) {
var target = module.exports.resolveParent(doc, selector);
if (!target) return false;
if (xml.oldAttrib) {
target.attrib = _.extend({}, xml.oldAttrib);
}
return true;
},
pruneXMLRemove: function (doc, selector, nodes) {
var target = module.exports.resolveParent(doc, selector);
if (!target) return false;
nodes.forEach(function (node) {
var attributes = node.attrib;
for (var attribute in attributes) {
if (target.attrib[attribute]) {
delete target.attrib[attribute];
}
}
});
return true;
},
parseElementtreeSync: function (filename) {
var contents = stripBom(fs.readFileSync(filename, 'utf-8'));
return new et.ElementTree(et.XML(contents));
},
resolveParent: function (doc, selector) {
var parent, tagName, subSelector;
// handle absolute selector (which elementtree doesn't like)
if (ROOT.test(selector)) {
tagName = selector.match(ROOT)[1];
// test for wildcard "any-tag" root selector
if (tagName === '*' || tagName === doc._root.tag) {
parent = doc._root;
// could be an absolute path, but not selecting the root
if (ABSOLUTE.test(selector)) {
subSelector = selector.match(ABSOLUTE)[2];
parent = parent.find(subSelector);
}
} else {
return false;
}
} else {
parent = doc.find(selector);
}
return parent;
}
};
function findChild (node, parent) {
const matches = parent.findall(node.tag);
return matches.find(m => module.exports.equalNodes(node, m));
}
function uniqueChild (node, parent) {
return !findChild(node, parent);
}
// Find the index at which to insert an entry. After is a ;-separated priority list
// of tags after which the insertion should be made. E.g. If we need to
// insert an element C, and the rule is that the order of children has to be
// As, Bs, Cs. After will be equal to "C;B;A".
function findInsertIdx (children, after) {
var childrenTags = children.map(function (child) { return child.tag; });
var afters = after.split(';');
var afterIndexes = afters.map(function (current) { return childrenTags.lastIndexOf(current); });
var foundIndex = _.find(afterIndexes, function (index) { return index !== -1; });
// add to the beginning if no matching nodes are found
return typeof foundIndex === 'undefined' ? 0 : foundIndex + 1;
}
var BLACKLIST = ['platform', 'feature', 'plugin', 'engine'];
var SINGLETONS = ['content', 'author', 'name'];
function mergeXml (src, dest, platform, clobber) {
// Do nothing for blacklisted tags.
if (BLACKLIST.includes(src.tag)) return;
// Handle attributes
Object.getOwnPropertyNames(src.attrib).forEach(function (attribute) {
if (clobber || !dest.attrib[attribute]) {
dest.attrib[attribute] = src.attrib[attribute];
}
});
// Handle text
if (src.text && (clobber || !dest.text)) {
dest.text = src.text;
}
// Handle children
src.getchildren().forEach(mergeChild);
// Handle platform
if (platform) {
src.findall('platform[@name="' + platform + '"]').forEach(function (platformElement) {
platformElement.getchildren().forEach(mergeChild);
});
}
// Handle duplicate preference tags (by name attribute)
removeDuplicatePreferences(dest);
function mergeChild (srcChild) {
var srcTag = srcChild.tag;
var destChild = new et.Element(srcTag);
var foundChild;
var query = srcTag + '';
var shouldMerge = true;
if (BLACKLIST.includes(srcTag)) return;
if (SINGLETONS.includes(srcTag)) {
foundChild = dest.find(query);
if (foundChild) {
destChild = foundChild;
dest.remove(destChild);
}
} else {
// Check for an exact match and if you find one don't add
var mergeCandidates = dest.findall(query)
.filter(function (foundChild) {
return foundChild && textMatch(srcChild, foundChild) && attribMatch(srcChild, foundChild);
});
if (mergeCandidates.length > 0) {
destChild = mergeCandidates[0];
dest.remove(destChild);
shouldMerge = false;
}
}
mergeXml(srcChild, destChild, platform, clobber && shouldMerge);
dest.append(destChild);
}
function removeDuplicatePreferences (xml) {
// reduce preference tags to a hashtable to remove dupes
var prefHash = xml.findall('preference[@name][@value]').reduce(function (previousValue, currentValue) {
previousValue[currentValue.attrib.name] = currentValue.attrib.value;
return previousValue;
}, {});
// remove all preferences
xml.findall('preference[@name][@value]').forEach(function (pref) {
xml.remove(pref);
});
// write new preferences
Object.keys(prefHash).forEach(function (key) {
var element = et.SubElement(xml, 'preference');
element.set('name', key);
element.set('value', this[key]);
}, prefHash);
}
}
// Expose for testing.
module.exports.mergeXml = mergeXml;
function textMatch (elm1, elm2) {
var text1 = elm1.text ? elm1.text.replace(/\s+/, '') : '';
var text2 = elm2.text ? elm2.text.replace(/\s+/, '') : '';
return (text1 === '' || text1 === text2);
}
function attribMatch (one, two) {
var oneAttribKeys = Object.keys(one.attrib);
var twoAttribKeys = Object.keys(two.attrib);
if (oneAttribKeys.length !== twoAttribKeys.length) {
return false;
}
for (var i = 0; i < oneAttribKeys.length; i++) {
var attribName = oneAttribKeys[i];
if (one.attrib[attribName] !== two.attrib[attribName]) {
return false;
}
}
return true;
}
+100
View File
@@ -0,0 +1,100 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="6.0.5"></a>
## [6.0.5](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.4...v6.0.5) (2018-03-02)
### Bug Fixes
* avoid using deprecated Buffer constructor ([#94](https://github.com/moxystudio/node-cross-spawn/issues/94)) ([d5770df](https://github.com/moxystudio/node-cross-spawn/commit/d5770df)), closes [/nodejs.org/api/deprecations.html#deprecations_dep0005](https://github.com//nodejs.org/api/deprecations.html/issues/deprecations_dep0005)
<a name="6.0.4"></a>
## [6.0.4](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.3...v6.0.4) (2018-01-31)
### Bug Fixes
* fix paths being incorrectly normalized on unix ([06ee3c6](https://github.com/moxystudio/node-cross-spawn/commit/06ee3c6)), closes [#90](https://github.com/moxystudio/node-cross-spawn/issues/90)
<a name="6.0.3"></a>
## [6.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.2...v6.0.3) (2018-01-23)
<a name="6.0.2"></a>
## [6.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.1...v6.0.2) (2018-01-23)
<a name="6.0.1"></a>
## [6.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.0...v6.0.1) (2018-01-23)
<a name="6.0.0"></a>
# [6.0.0](https://github.com/moxystudio/node-cross-spawn/compare/5.1.0...6.0.0) (2018-01-23)
### Bug Fixes
* fix certain arguments not being correctly escaped or causing batch syntax error ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)), closes [#82](https://github.com/moxystudio/node-cross-spawn/issues/82) [#51](https://github.com/moxystudio/node-cross-spawn/issues/51)
* fix commands as posix relatixe paths not working correctly, e.g.: `./my-command` ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
* fix `options` argument being mutated ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
* fix commands resolution when PATH was actually Path ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
### Features
* improve compliance with node's ENOENT errors ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
* improve detection of node's shell option support ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
### Chores
* upgrade tooling
* upgrate project to es6 (node v4)
### BREAKING CHANGES
* remove support for older nodejs versions, only `node >= 4` is supported
<a name="5.1.0"></a>
## [5.1.0](https://github.com/moxystudio/node-cross-spawn/compare/5.0.1...5.1.0) (2017-02-26)
### Bug Fixes
* fix `options.shell` support for NodeJS [v4.8](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V4.md#4.8.0)
<a name="5.0.1"></a>
## [5.0.1](https://github.com/moxystudio/node-cross-spawn/compare/5.0.0...5.0.1) (2016-11-04)
### Bug Fixes
* fix `options.shell` support for NodeJS v7
<a name="5.0.0"></a>
# [5.0.0](https://github.com/moxystudio/node-cross-spawn/compare/4.0.2...5.0.0) (2016-10-30)
## Features
* add support for `options.shell`
* improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module
## Chores
* refactor some code to make it more clear
* update README caveats
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+94
View File
@@ -0,0 +1,94 @@
# cross-spawn
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [![Greenkeeper badge][greenkeeper-image]][greenkeeper-url]
[npm-url]:https://npmjs.org/package/cross-spawn
[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg
[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg
[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn
[travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg
[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn
[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg
[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn
[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg
[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev
[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg
[greenkeeper-image]:https://badges.greenkeeper.io/moxystudio/node-cross-spawn.svg
[greenkeeper-url]:https://greenkeeper.io/
A cross platform solution to node's spawn and spawnSync.
## Installation
`$ npm install cross-spawn`
## Why
Node has issues when using spawn on Windows:
- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318)
- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix))
- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367)
- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`)
- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149)
- No `options.shell` support on node `<v4.8`
All these issues are handled correctly by `cross-spawn`.
There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments.
## Usage
Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement.
```js
const spawn = require('cross-spawn');
// Spawn NPM asynchronously
const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
// Spawn NPM synchronously
const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
```
## Caveats
### Using `options.shell` as an alternative to `cross-spawn`
Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves
the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but:
- It's not supported in node `<v4.8`
- You must manually escape the command and arguments which is very error prone, specially when passing user input
- There are a lot of other unresolved issues from the [Why](#why) section that you must take into account
If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned.
### `options.shell` support
While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled.
This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.
### Shebangs support
While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.
If you would like to have the shebang support improved, feel free to contribute via a pull-request.
Remember to always test your code on Windows!
## Tests
`$ npm test`
`$ npm test -- --watch` during development
## License
Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
+39
View File
@@ -0,0 +1,39 @@
'use strict';
const cp = require('child_process');
const parse = require('./lib/parse');
const enoent = require('./lib/enoent');
function spawn(command, args, options) {
// Parse the arguments
const parsed = parse(command, args, options);
// Spawn the child process
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
// Hook into child process "exit" event to emit an error if the command
// does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
function spawnSync(command, args, options) {
// Parse the arguments
const parsed = parse(command, args, options);
// Spawn the child process
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
// Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
module.exports = spawn;
module.exports.spawn = spawn;
module.exports.sync = spawnSync;
module.exports._parse = parse;
module.exports._enoent = enoent;
+59
View File
@@ -0,0 +1,59 @@
'use strict';
const isWin = process.platform === 'win32';
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: 'ENOENT',
errno: 'ENOENT',
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args,
});
}
function hookChildProcess(cp, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp.emit;
cp.emit = function (name, arg1) {
// If emitting "exit" event and exit code is 1, we need to check if
// the command exists and emit an "error" instead
// See https://github.com/IndigoUnited/node-cross-spawn/issues/16
if (name === 'exit') {
const err = verifyENOENT(arg1, parsed, 'spawn');
if (err) {
return originalEmit.call(cp, 'error', err);
}
}
return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
};
}
function verifyENOENT(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, 'spawn');
}
return null;
}
function verifyENOENTSync(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, 'spawnSync');
}
return null;
}
module.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError,
};
+125
View File
@@ -0,0 +1,125 @@
'use strict';
const path = require('path');
const niceTry = require('nice-try');
const resolveCommand = require('./util/resolveCommand');
const escape = require('./util/escape');
const readShebang = require('./util/readShebang');
const semver = require('semver');
const isWin = process.platform === 'win32';
const isExecutableRegExp = /\.(?:com|exe)$/i;
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0
const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
const shebang = parsed.file && readShebang(parsed.file);
if (shebang) {
parsed.args.unshift(parsed.file);
parsed.command = shebang;
return resolveCommand(parsed);
}
return parsed.file;
}
function parseNonShell(parsed) {
if (!isWin) {
return parsed;
}
// Detect & add support for shebangs
const commandFile = detectShebang(parsed);
// We don't need a shell if the command filename is an executable
const needsShell = !isExecutableRegExp.test(commandFile);
// If a shell is required, use cmd.exe and take care of escaping everything correctly
// Note that `forceShell` is an hidden option used only in tests
if (parsed.options.forceShell || needsShell) {
// Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
// The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
// Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
// we need to double escape them
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
// Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
// This is necessary otherwise it will always fail with ENOENT in those cases
parsed.command = path.normalize(parsed.command);
// Escape command & arguments
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
const shellCommand = [parsed.command].concat(parsed.args).join(' ');
parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
parsed.command = process.env.comspec || 'cmd.exe';
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
}
return parsed;
}
function parseShell(parsed) {
// If node supports the shell option, there's no need to mimic its behavior
if (supportsShellOption) {
return parsed;
}
// Mimic node shell option
// See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335
const shellCommand = [parsed.command].concat(parsed.args).join(' ');
if (isWin) {
parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe';
parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
} else {
if (typeof parsed.options.shell === 'string') {
parsed.command = parsed.options.shell;
} else if (process.platform === 'android') {
parsed.command = '/system/bin/sh';
} else {
parsed.command = '/bin/sh';
}
parsed.args = ['-c', shellCommand];
}
return parsed;
}
function parse(command, args, options) {
// Normalize arguments, similar to nodejs
if (args && !Array.isArray(args)) {
options = args;
args = null;
}
args = args ? args.slice(0) : []; // Clone array to avoid changing the original
options = Object.assign({}, options); // Clone object to avoid changing the original
// Build our parsed object
const parsed = {
command,
args,
options,
file: undefined,
original: {
command,
args,
},
};
// Delegate further parsing to shell or non-shell
return options.shell ? parseShell(parsed) : parseNonShell(parsed);
}
module.exports = parse;
+45
View File
@@ -0,0 +1,45 @@
'use strict';
// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
return arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
// Convert to string
arg = `${arg}`;
// Algorithm below is based on https://qntm.org/cmd
// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
arg = arg.replace(/(\\*)"/g, '$1$1\\"');
// Sequence of backslashes followed by the end of the string
// (which will become a double quote later):
// double up all the backslashes
arg = arg.replace(/(\\*)$/, '$1$1');
// All other backslashes occur literally
// Quote the whole thing:
arg = `"${arg}"`;
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
// Double escape meta chars if necessary
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, '^$1');
}
return arg;
}
module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
@@ -0,0 +1,32 @@
'use strict';
const fs = require('fs');
const shebangCommand = require('shebang-command');
function readShebang(command) {
// Read the first 150 bytes from the file
const size = 150;
let buffer;
if (Buffer.alloc) {
// Node.js v4.5+ / v5.10+
buffer = Buffer.alloc(size);
} else {
// Old Node.js API
buffer = new Buffer(size);
buffer.fill(0); // zero-fill
}
let fd;
try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) { /* Empty */ }
// Attempt to extract shebang (null is returned if not a shebang)
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
@@ -0,0 +1,47 @@
'use strict';
const path = require('path');
const which = require('which');
const pathKey = require('path-key')();
function resolveCommandAttempt(parsed, withoutPathExt) {
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
if (hasCustomCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err) {
/* Empty */
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: (parsed.options.env || process.env)[pathKey],
pathExt: withoutPathExt ? path.delimiter : undefined,
});
} catch (e) {
/* Empty */
} finally {
process.chdir(cwd);
}
// If we successfully resolved, ensure that an absolute path is returned
// Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
if (resolved) {
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
}
return resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
module.exports = resolveCommand;
+111
View File
@@ -0,0 +1,111 @@
{
"_args": [
[
"cross-spawn@6.0.5",
"C:\\Users\\tiago.kayaya\\development\\gabinete-digital"
]
],
"_development": true,
"_from": "cross-spawn@6.0.5",
"_id": "cross-spawn@6.0.5",
"_inBundle": false,
"_integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
"_location": "/cordova-browser/cross-spawn",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "cross-spawn@6.0.5",
"name": "cross-spawn",
"escapedName": "cross-spawn",
"rawSpec": "6.0.5",
"saveSpec": null,
"fetchSpec": "6.0.5"
},
"_requiredBy": [
"/cordova-browser/cordova-common"
],
"_resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
"_spec": "6.0.5",
"_where": "C:\\Users\\tiago.kayaya\\development\\gabinete-digital",
"author": {
"name": "André Cruz",
"email": "andre@moxy.studio"
},
"bugs": {
"url": "https://github.com/moxystudio/node-cross-spawn/issues"
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"dependencies": {
"nice-try": "^1.0.4",
"path-key": "^2.0.1",
"semver": "^5.5.0",
"shebang-command": "^1.2.0",
"which": "^1.2.9"
},
"description": "Cross platform child_process#spawn and child_process#spawnSync",
"devDependencies": {
"@commitlint/cli": "^6.0.0",
"@commitlint/config-conventional": "^6.0.2",
"babel-core": "^6.26.0",
"babel-jest": "^22.1.0",
"babel-preset-moxy": "^2.2.1",
"eslint": "^4.3.0",
"eslint-config-moxy": "^5.0.0",
"husky": "^0.14.3",
"jest": "^22.0.0",
"lint-staged": "^7.0.0",
"mkdirp": "^0.5.1",
"regenerator-runtime": "^0.11.1",
"rimraf": "^2.6.2",
"standard-version": "^4.2.0"
},
"engines": {
"node": ">=4.8"
},
"files": [
"lib"
],
"homepage": "https://github.com/moxystudio/node-cross-spawn",
"keywords": [
"spawn",
"spawnSync",
"windows",
"cross-platform",
"path-ext",
"shebang",
"cmd",
"execute"
],
"license": "MIT",
"lint-staged": {
"*.js": [
"eslint --fix",
"git add"
]
},
"main": "index.js",
"name": "cross-spawn",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/moxystudio/node-cross-spawn.git"
},
"scripts": {
"commitmsg": "commitlint -e $GIT_PARAMS",
"lint": "eslint .",
"precommit": "lint-staged",
"prerelease": "npm t && npm run lint",
"release": "standard-version",
"test": "jest --env node --coverage"
},
"standard-version": {
"scripts": {
"posttag": "git push --follow-tags origin master && npm publish"
}
},
"version": "6.0.5"
}
+864
View File
@@ -0,0 +1,864 @@
8.1.0 / 2019-06-28
------------------
- Add support for promisified `fs.realpath.native` in Node v9.2+ ([#650](https://github.com/jprichardson/node-fs-extra/issues/650), [#682](https://github.com/jprichardson/node-fs-extra/pull/682))
- Update `graceful-fs` dependency ([#700](https://github.com/jprichardson/node-fs-extra/pull/700))
- Use `graceful-fs` everywhere ([#700](https://github.com/jprichardson/node-fs-extra/pull/700))
8.0.1 / 2019-05-13
------------------
- Fix bug `Maximum call stack size exceeded` error in `util/stat` ([#679](https://github.com/jprichardson/node-fs-extra/pull/679))
8.0.0 / 2019-05-11
------------------
**NOTE:** Node.js v6 support is deprecated, and will be dropped in the next major release.
- Use `renameSync()` under the hood in `moveSync()`
- Fix bug with bind-mounted directories in `copy*()` ([#613](https://github.com/jprichardson/node-fs-extra/issues/613), [#618](https://github.com/jprichardson/node-fs-extra/pull/618))
- Fix bug in `move()` with case-insensitive file systems
- Use `fs.stat()`'s `bigint` option in `copy*()` & `move*()` where possible ([#657](https://github.com/jprichardson/node-fs-extra/issues/657))
7.0.1 / 2018-11-07
------------------
- Fix `removeSync()` on Windows, in some cases, it would error out with `ENOTEMPTY` ([#646](https://github.com/jprichardson/node-fs-extra/pull/646))
- Document `mode` option for `ensureDir*()` ([#587](https://github.com/jprichardson/node-fs-extra/pull/587))
- Don't include documentation files in npm package tarball ([#642](https://github.com/jprichardson/node-fs-extra/issues/642), [#643](https://github.com/jprichardson/node-fs-extra/pull/643))
7.0.0 / 2018-07-16
------------------
- **BREAKING:** Refine `copy*()` handling of symlinks to properly detect symlinks that point to the same file. ([#582](https://github.com/jprichardson/node-fs-extra/pull/582))
- Fix bug with copying write-protected directories ([#600](https://github.com/jprichardson/node-fs-extra/pull/600))
- Universalify `fs.lchmod()` ([#596](https://github.com/jprichardson/node-fs-extra/pull/596))
- Add `engines` field to `package.json` ([#580](https://github.com/jprichardson/node-fs-extra/pull/580))
6.0.1 / 2018-05-09
------------------
- Fix `fs.promises` `ExperimentalWarning` on Node v10.1.0 ([#578](https://github.com/jprichardson/node-fs-extra/pull/578))
6.0.0 / 2018-05-01
------------------
- Drop support for Node.js versions 4, 5, & 7 ([#564](https://github.com/jprichardson/node-fs-extra/pull/564))
- Rewrite `move` to use `fs.rename` where possible ([#549](https://github.com/jprichardson/node-fs-extra/pull/549))
- Don't convert relative paths to absolute paths for `filter` ([#554](https://github.com/jprichardson/node-fs-extra/pull/554))
- `copy*`'s behavior when `preserveTimestamps` is `false` has been OS-dependent since 5.0.0, but that's now explicitly noted in the docs ([#563](https://github.com/jprichardson/node-fs-extra/pull/563))
- Fix subdirectory detection for `copy*` & `move*` ([#541](https://github.com/jprichardson/node-fs-extra/pull/541))
- Handle case-insensitive paths correctly in `copy*` ([#568](https://github.com/jprichardson/node-fs-extra/pull/568))
5.0.0 / 2017-12-11
------------------
Significant refactor of `copy()` & `copySync()`, including breaking changes. No changes to other functions in this release.
Huge thanks to **[@manidlou](https://github.com/manidlou)** for doing most of the work on this release.
- The `filter` option can no longer be a RegExp (must be a function). This was deprecated since fs-extra v1.0.0. [#512](https://github.com/jprichardson/node-fs-extra/pull/512)
- `copy()`'s `filter` option can now be a function that returns a Promise. [#518](https://github.com/jprichardson/node-fs-extra/pull/518)
- `copy()` & `copySync()` now use `fs.copyFile()`/`fs.copyFileSync()` in environments that support it (currently Node 8.5.0+). Older Node versions still get the old implementation. [#505](https://github.com/jprichardson/node-fs-extra/pull/505)
- Don't allow copying a directory into itself. [#83](https://github.com/jprichardson/node-fs-extra/issues/83)
- Handle copying between identical files. [#198](https://github.com/jprichardson/node-fs-extra/issues/198)
- Error out when copying an empty folder to a path that already exists. [#464](https://github.com/jprichardson/node-fs-extra/issues/464)
- Don't create `dest`'s parent if the `filter` function aborts the `copy()` operation. [#517](https://github.com/jprichardson/node-fs-extra/pull/517)
- Fix `writeStream` not being closed if there was an error in `copy()`. [#516](https://github.com/jprichardson/node-fs-extra/pull/516)
4.0.3 / 2017-12-05
------------------
- Fix wrong `chmod` values in `fs.remove()` [#501](https://github.com/jprichardson/node-fs-extra/pull/501)
- Fix `TypeError` on systems that don't have some `fs` operations like `lchown` [#520](https://github.com/jprichardson/node-fs-extra/pull/520)
4.0.2 / 2017-09-12
------------------
- Added `EOL` option to `writeJson*` & `outputJson*` (via upgrade to jsonfile v4)
- Added promise support to [`fs.copyFile()`](https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback) in Node 8.5+
- Added `.js` extension to `main` field in `package.json` for better tooling compatibility. [#485](https://github.com/jprichardson/node-fs-extra/pull/485)
4.0.1 / 2017-07-31
------------------
### Fixed
- Previously, `ensureFile()` & `ensureFileSync()` would do nothing if the path was a directory. Now, they error out for consistency with `ensureDir()`. [#465](https://github.com/jprichardson/node-fs-extra/issues/465), [#466](https://github.com/jprichardson/node-fs-extra/pull/466), [#470](https://github.com/jprichardson/node-fs-extra/issues/470)
4.0.0 / 2017-07-14
------------------
### Changed
- **BREAKING:** The promisified versions of `fs.read()` & `fs.write()` now return objects. See [the docs](docs/fs-read-write.md) for details. [#436](https://github.com/jprichardson/node-fs-extra/issues/436), [#449](https://github.com/jprichardson/node-fs-extra/pull/449)
- `fs.move()` now errors out when destination is a subdirectory of source. [#458](https://github.com/jprichardson/node-fs-extra/pull/458)
- Applied upstream fixes from `rimraf` to `fs.remove()` & `fs.removeSync()`. [#459](https://github.com/jprichardson/node-fs-extra/pull/459)
### Fixed
- Got `fs.outputJSONSync()` working again; it was broken due to refactoring. [#428](https://github.com/jprichardson/node-fs-extra/pull/428)
Also clarified the docs in a few places.
3.0.1 / 2017-05-04
------------------
- Fix bug in `move()` & `moveSync()` when source and destination are the same, and source does not exist. [#415](https://github.com/jprichardson/node-fs-extra/pull/415)
3.0.0 / 2017-04-27
------------------
### Added
- **BREAKING:** Added Promise support. All asynchronous native fs methods and fs-extra methods now return a promise if the callback is not passed. [#403](https://github.com/jprichardson/node-fs-extra/pull/403)
- `pathExists()`, a replacement for the deprecated `fs.exists`. `pathExists` has a normal error-first callback signature. Also added `pathExistsSync`, an alias to `fs.existsSync`, for completeness. [#406](https://github.com/jprichardson/node-fs-extra/pull/406)
### Removed
- **BREAKING:** Removed support for setting the default spaces for `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()`. This was undocumented. [#402](https://github.com/jprichardson/node-fs-extra/pull/402)
### Changed
- Upgraded jsonfile dependency to v3.0.0:
- **BREAKING:** Changed behavior of `throws` option for `readJsonSync()`; now does not throw filesystem errors when `throws` is `false`.
- **BREAKING:** `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()` now output minified JSON by default for consistency with `JSON.stringify()`; set the `spaces` option to `2` to override this new behavior. [#402](https://github.com/jprichardson/node-fs-extra/pull/402)
- Use `Buffer.allocUnsafe()` instead of `new Buffer()` in environments that support it. [#394](https://github.com/jprichardson/node-fs-extra/pull/394)
### Fixed
- `removeSync()` silently failed on Windows in some cases. Now throws an `EBUSY` error. [#408](https://github.com/jprichardson/node-fs-extra/pull/408)
2.1.2 / 2017-03-16
------------------
### Fixed
- Weird windows bug that resulted in `ensureDir()`'s callback being called twice in some cases. This bug may have also affected `remove()`. See [#392](https://github.com/jprichardson/node-fs-extra/issues/392), [#393](https://github.com/jprichardson/node-fs-extra/pull/393)
2.1.1 / 2017-03-15
------------------
### Fixed
- Reverted [`5597bd`](https://github.com/jprichardson/node-fs-extra/commit/5597bd5b67f7d060f5f5bf26e9635be48330f5d7), this broke compatibility with Node.js versions v4+ but less than `v4.5.0`.
- Remove `Buffer.alloc()` usage in `moveSync()`.
2.1.0 / 2017-03-15
------------------
Thanks to [Mani Maghsoudlou (@manidlou)](https://github.com/manidlou) & [Jan Peer Stöcklmair (@JPeer264)](https://github.com/JPeer264) for their extraordinary help with this release!
### Added
- `moveSync()` See [#309], [#381](https://github.com/jprichardson/node-fs-extra/pull/381). ([@manidlou](https://github.com/manidlou))
- `copy()` and `copySync()`'s `filter` option now gets the destination path passed as the second parameter. [#366](https://github.com/jprichardson/node-fs-extra/pull/366) ([@manidlou](https://github.com/manidlou))
### Changed
- Use `Buffer.alloc()` instead of deprecated `new Buffer()` in `copySync()`. [#380](https://github.com/jprichardson/node-fs-extra/pull/380) ([@manidlou](https://github.com/manidlou))
- Refactored entire codebase to use ES6 features supported by Node.js v4+ [#355](https://github.com/jprichardson/node-fs-extra/issues/355). [(@JPeer264)](https://github.com/JPeer264)
- Refactored docs. ([@manidlou](https://github.com/manidlou))
### Fixed
- `move()` shouldn't error out when source and dest are the same. [#377](https://github.com/jprichardson/node-fs-extra/issues/377), [#378](https://github.com/jprichardson/node-fs-extra/pull/378) ([@jdalton](https://github.com/jdalton))
2.0.0 / 2017-01-16
------------------
### Removed
- **BREAKING:** Removed support for Node `v0.12`. The Node foundation stopped officially supporting it
on Jan 1st, 2017.
- **BREAKING:** Remove `walk()` and `walkSync()`. `walkSync()` was only part of `fs-extra` for a little
over two months. Use [klaw](https://github.com/jprichardson/node-klaw) instead of `walk()`, in fact, `walk()` was just
an alias to klaw. For `walkSync()` use [klaw-sync](https://github.com/mawni/node-klaw-sync). See: [#338], [#339]
### Changed
- **BREAKING:** Renamed `clobber` to `overwrite`. This affects `copy()`, `copySync()`, and `move()`. [#330], [#333]
- Moved docs, to `docs/`. [#340]
### Fixed
- Apply filters to directories in `copySync()` like in `copy()`. [#324]
- A specific condition when disk is under heavy use, `copy()` can fail. [#326]
1.0.0 / 2016-11-01
------------------
After five years of development, we finally have reach the 1.0.0 milestone! Big thanks goes
to [Ryan Zim](https://github.com/RyanZim) for leading the charge on this release!
### Added
- `walkSync()`
### Changed
- **BREAKING**: dropped Node v0.10 support.
- disabled `rimaf` globbing, wasn't used. [#280]
- deprecate `copy()/copySync()` option `filter` if it's a `RegExp`. `filter` should now be a function.
- inline `rimraf`. This is temporary and was done because `rimraf` depended upon the beefy `glob` which `fs-extra` does not use. [#300]
### Fixed
- bug fix proper closing of file handle on `utimesMillis()` [#271]
- proper escaping of files with dollar signs [#291]
- `copySync()` failed if user didn't own file. [#199], [#301]
0.30.0 / 2016-04-28
-------------------
- Brought back Node v0.10 support. I didn't realize there was still demand. Official support will end **2016-10-01**.
0.29.0 / 2016-04-27
-------------------
- **BREAKING**: removed support for Node v0.10. If you still want to use Node v0.10, everything should work except for `ensureLink()/ensureSymlink()`. Node v0.12 is still supported but will be dropped in the near future as well.
0.28.0 / 2016-04-17
-------------------
- **BREAKING**: removed `createOutputStream()`. Use https://www.npmjs.com/package/create-output-stream. See: [#192][#192]
- `mkdirs()/mkdirsSync()` check for invalid win32 path chars. See: [#209][#209], [#237][#237]
- `mkdirs()/mkdirsSync()` if drive not mounted, error. See: [#93][#93]
0.27.0 / 2016-04-15
-------------------
- add `dereference` option to `copySync()`. [#235][#235]
0.26.7 / 2016-03-16
-------------------
- fixed `copy()` if source and dest are the same. [#230][#230]
0.26.6 / 2016-03-15
-------------------
- fixed if `emptyDir()` does not have a callback: [#229][#229]
0.26.5 / 2016-01-27
-------------------
- `copy()` with two arguments (w/o callback) was broken. See: [#215][#215]
0.26.4 / 2016-01-05
-------------------
- `copySync()` made `preserveTimestamps` default consistent with `copy()` which is `false`. See: [#208][#208]
0.26.3 / 2015-12-17
-------------------
- fixed `copy()` hangup in copying blockDevice / characterDevice / `/dev/null`. See: [#193][#193]
0.26.2 / 2015-11-02
-------------------
- fixed `outputJson{Sync}()` spacing adherence to `fs.spaces`
0.26.1 / 2015-11-02
-------------------
- fixed `copySync()` when `clogger=true` and the destination is read only. See: [#190][#190]
0.26.0 / 2015-10-25
-------------------
- extracted the `walk()` function into its own module [`klaw`](https://github.com/jprichardson/node-klaw).
0.25.0 / 2015-10-24
-------------------
- now has a file walker `walk()`
0.24.0 / 2015-08-28
-------------------
- removed alias `delete()` and `deleteSync()`. See: [#171][#171]
0.23.1 / 2015-08-07
-------------------
- Better handling of errors for `move()` when moving across devices. [#170][#170]
- `ensureSymlink()` and `ensureLink()` should not throw errors if link exists. [#169][#169]
0.23.0 / 2015-08-06
-------------------
- added `ensureLink{Sync}()` and `ensureSymlink{Sync}()`. See: [#165][#165]
0.22.1 / 2015-07-09
-------------------
- Prevent calling `hasMillisResSync()` on module load. See: [#149][#149].
Fixes regression that was introduced in `0.21.0`.
0.22.0 / 2015-07-09
-------------------
- preserve permissions / ownership in `copy()`. See: [#54][#54]
0.21.0 / 2015-07-04
-------------------
- add option to preserve timestamps in `copy()` and `copySync()`. See: [#141][#141]
- updated `graceful-fs@3.x` to `4.x`. This brings in features from `amazing-graceful-fs` (much cleaner code / less hacks)
0.20.1 / 2015-06-23
-------------------
- fixed regression caused by latest jsonfile update: See: https://github.com/jprichardson/node-jsonfile/issues/26
0.20.0 / 2015-06-19
-------------------
- removed `jsonfile` aliases with `File` in the name, they weren't documented and probably weren't in use e.g.
this package had both `fs.readJsonFile` and `fs.readJson` that were aliases to each other, now use `fs.readJson`.
- preliminary walker created. Intentionally not documented. If you use it, it will almost certainly change and break your code.
- started moving tests inline
- upgraded to `jsonfile@2.1.0`, can now pass JSON revivers/replacers to `readJson()`, `writeJson()`, `outputJson()`
0.19.0 / 2015-06-08
-------------------
- `fs.copy()` had support for Node v0.8, dropped support
0.18.4 / 2015-05-22
-------------------
- fixed license field according to this: [#136][#136] and https://github.com/npm/npm/releases/tag/v2.10.0
0.18.3 / 2015-05-08
-------------------
- bugfix: handle `EEXIST` when clobbering on some Linux systems. [#134][#134]
0.18.2 / 2015-04-17
-------------------
- bugfix: allow `F_OK` ([#120][#120])
0.18.1 / 2015-04-15
-------------------
- improved windows support for `move()` a bit. https://github.com/jprichardson/node-fs-extra/commit/92838980f25dc2ee4ec46b43ee14d3c4a1d30c1b
- fixed a lot of tests for Windows (appveyor)
0.18.0 / 2015-03-31
-------------------
- added `emptyDir()` and `emptyDirSync()`
0.17.0 / 2015-03-28
-------------------
- `copySync` added `clobber` option (before always would clobber, now if `clobber` is `false` it throws an error if the destination exists).
**Only works with files at the moment.**
- `createOutputStream()` added. See: [#118][#118]
0.16.5 / 2015-03-08
-------------------
- fixed `fs.move` when `clobber` is `true` and destination is a directory, it should clobber. [#114][#114]
0.16.4 / 2015-03-01
-------------------
- `fs.mkdirs` fix infinite loop on Windows. See: See https://github.com/substack/node-mkdirp/pull/74 and https://github.com/substack/node-mkdirp/issues/66
0.16.3 / 2015-01-28
-------------------
- reverted https://github.com/jprichardson/node-fs-extra/commit/1ee77c8a805eba5b99382a2591ff99667847c9c9
0.16.2 / 2015-01-28
-------------------
- fixed `fs.copy` for Node v0.8 (support is temporary and will be removed in the near future)
0.16.1 / 2015-01-28
-------------------
- if `setImmediate` is not available, fall back to `process.nextTick`
0.16.0 / 2015-01-28
-------------------
- bugfix `fs.move()` into itself. Closes [#104]
- bugfix `fs.move()` moving directory across device. Closes [#108]
- added coveralls support
- bugfix: nasty multiple callback `fs.copy()` bug. Closes [#98]
- misc fs.copy code cleanups
0.15.0 / 2015-01-21
-------------------
- dropped `ncp`, imported code in
- because of previous, now supports `io.js`
- `graceful-fs` is now a dependency
0.14.0 / 2015-01-05
-------------------
- changed `copy`/`copySync` from `fs.copy(src, dest, [filters], callback)` to `fs.copy(src, dest, [options], callback)` [#100][#100]
- removed mockfs tests for mkdirp (this may be temporary, but was getting in the way of other tests)
0.13.0 / 2014-12-10
-------------------
- removed `touch` and `touchSync` methods (they didn't handle permissions like UNIX touch)
- updated `"ncp": "^0.6.0"` to `"ncp": "^1.0.1"`
- imported `mkdirp` => `minimist` and `mkdirp` are no longer dependences, should now appease people who wanted `mkdirp` to be `--use_strict` safe. See [#59]([#59][#59])
0.12.0 / 2014-09-22
-------------------
- copy symlinks in `copySync()` [#85][#85]
0.11.1 / 2014-09-02
-------------------
- bugfix `copySync()` preserve file permissions [#80][#80]
0.11.0 / 2014-08-11
-------------------
- upgraded `"ncp": "^0.5.1"` to `"ncp": "^0.6.0"`
- upgrade `jsonfile": "^1.2.0"` to `jsonfile": "^2.0.0"` => on write, json files now have `\n` at end. Also adds `options.throws` to `readJsonSync()`
see https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options for more details.
0.10.0 / 2014-06-29
------------------
* bugfix: upgaded `"jsonfile": "~1.1.0"` to `"jsonfile": "^1.2.0"`, bumped minor because of `jsonfile` dep change
from `~` to `^`. [#67]
0.9.1 / 2014-05-22
------------------
* removed Node.js `0.8.x` support, `0.9.0` was published moments ago and should have been done there
0.9.0 / 2014-05-22
------------------
* upgraded `ncp` from `~0.4.2` to `^0.5.1`, [#58]
* upgraded `rimraf` from `~2.2.6` to `^2.2.8`
* upgraded `mkdirp` from `0.3.x` to `^0.5.0`
* added methods `ensureFile()`, `ensureFileSync()`
* added methods `ensureDir()`, `ensureDirSync()` [#31]
* added `move()` method. From: https://github.com/andrewrk/node-mv
0.8.1 / 2013-10-24
------------------
* copy failed to return an error to the callback if a file doesn't exist (ulikoehler [#38], [#39])
0.8.0 / 2013-10-14
------------------
* `filter` implemented on `copy()` and `copySync()`. (Srirangan / [#36])
0.7.1 / 2013-10-12
------------------
* `copySync()` implemented (Srirangan / [#33])
* updated to the latest `jsonfile` version `1.1.0` which gives `options` params for the JSON methods. Closes [#32]
0.7.0 / 2013-10-07
------------------
* update readme conventions
* `copy()` now works if destination directory does not exist. Closes [#29]
0.6.4 / 2013-09-05
------------------
* changed `homepage` field in package.json to remove NPM warning
0.6.3 / 2013-06-28
------------------
* changed JSON spacing default from `4` to `2` to follow Node conventions
* updated `jsonfile` dep
* updated `rimraf` dep
0.6.2 / 2013-06-28
------------------
* added .npmignore, [#25]
0.6.1 / 2013-05-14
------------------
* modified for `strict` mode, closes [#24]
* added `outputJson()/outputJsonSync()`, closes [#23]
0.6.0 / 2013-03-18
------------------
* removed node 0.6 support
* added node 0.10 support
* upgraded to latest `ncp` and `rimraf`.
* optional `graceful-fs` support. Closes [#17]
0.5.0 / 2013-02-03
------------------
* Removed `readTextFile`.
* Renamed `readJSONFile` to `readJSON` and `readJson`, same with write.
* Restructured documentation a bit. Added roadmap.
0.4.0 / 2013-01-28
------------------
* Set default spaces in `jsonfile` from 4 to 2.
* Updated `testutil` deps for tests.
* Renamed `touch()` to `createFile()`
* Added `outputFile()` and `outputFileSync()`
* Changed creation of testing diretories so the /tmp dir is not littered.
* Added `readTextFile()` and `readTextFileSync()`.
0.3.2 / 2012-11-01
------------------
* Added `touch()` and `touchSync()` methods.
0.3.1 / 2012-10-11
------------------
* Fixed some stray globals.
0.3.0 / 2012-10-09
------------------
* Removed all CoffeeScript from tests.
* Renamed `mkdir` to `mkdirs`/`mkdirp`.
0.2.1 / 2012-09-11
------------------
* Updated `rimraf` dep.
0.2.0 / 2012-09-10
------------------
* Rewrote module into JavaScript. (Must still rewrite tests into JavaScript)
* Added all methods of [jsonfile](https://github.com/jprichardson/node-jsonfile)
* Added Travis-CI.
0.1.3 / 2012-08-13
------------------
* Added method `readJSONFile`.
0.1.2 / 2012-06-15
------------------
* Bug fix: `deleteSync()` didn't exist.
* Verified Node v0.8 compatibility.
0.1.1 / 2012-06-15
------------------
* Fixed bug in `remove()`/`delete()` that wouldn't execute the function if a callback wasn't passed.
0.1.0 / 2012-05-31
------------------
* Renamed `copyFile()` to `copy()`. `copy()` can now copy directories (recursively) too.
* Renamed `rmrf()` to `remove()`.
* `remove()` aliased with `delete()`.
* Added `mkdirp` capabilities. Named: `mkdir()`. Hides Node.js native `mkdir()`.
* Instead of exporting the native `fs` module with new functions, I now copy over the native methods to a new object and export that instead.
0.0.4 / 2012-03-14
------------------
* Removed CoffeeScript dependency
0.0.3 / 2012-01-11
------------------
* Added methods rmrf and rmrfSync
* Moved tests from Jasmine to Mocha
[#344]: https://github.com/jprichardson/node-fs-extra/issues/344 "Licence Year"
[#343]: https://github.com/jprichardson/node-fs-extra/pull/343 "Add klaw-sync link to readme"
[#342]: https://github.com/jprichardson/node-fs-extra/pull/342 "allow preserveTimestamps when use move"
[#341]: https://github.com/jprichardson/node-fs-extra/issues/341 "mkdirp(path.dirname(dest) in move() logic needs cleaning up [question]"
[#340]: https://github.com/jprichardson/node-fs-extra/pull/340 "Move docs to seperate docs folder [documentation]"
[#339]: https://github.com/jprichardson/node-fs-extra/pull/339 "Remove walk() & walkSync() [feature-walk]"
[#338]: https://github.com/jprichardson/node-fs-extra/issues/338 "Remove walk() and walkSync() [feature-walk]"
[#337]: https://github.com/jprichardson/node-fs-extra/issues/337 "copy doesn't return a yieldable value"
[#336]: https://github.com/jprichardson/node-fs-extra/pull/336 "Docs enhanced walk sync [documentation, feature-walk]"
[#335]: https://github.com/jprichardson/node-fs-extra/pull/335 "Refactor move() tests [feature-move]"
[#334]: https://github.com/jprichardson/node-fs-extra/pull/334 "Cleanup lib/move/index.js [feature-move]"
[#333]: https://github.com/jprichardson/node-fs-extra/pull/333 "Rename clobber to overwrite [feature-copy, feature-move]"
[#332]: https://github.com/jprichardson/node-fs-extra/pull/332 "BREAKING: Drop Node v0.12 & io.js support"
[#331]: https://github.com/jprichardson/node-fs-extra/issues/331 "Add support for chmodr [enhancement, future]"
[#330]: https://github.com/jprichardson/node-fs-extra/pull/330 "BREAKING: Do not error when copy destination exists & clobber: false [feature-copy]"
[#329]: https://github.com/jprichardson/node-fs-extra/issues/329 "Does .walk() scale to large directories? [question]"
[#328]: https://github.com/jprichardson/node-fs-extra/issues/328 "Copying files corrupts [feature-copy, needs-confirmed]"
[#327]: https://github.com/jprichardson/node-fs-extra/pull/327 "Use writeStream 'finish' event instead of 'close' [bug, feature-copy]"
[#326]: https://github.com/jprichardson/node-fs-extra/issues/326 "fs.copy fails with chmod error when disk under heavy use [bug, feature-copy]"
[#325]: https://github.com/jprichardson/node-fs-extra/issues/325 "ensureDir is difficult to promisify [enhancement]"
[#324]: https://github.com/jprichardson/node-fs-extra/pull/324 "copySync() should apply filter to directories like copy() [bug, feature-copy]"
[#323]: https://github.com/jprichardson/node-fs-extra/issues/323 "Support for `dest` being a directory when using `copy*()`?"
[#322]: https://github.com/jprichardson/node-fs-extra/pull/322 "Add fs-promise as fs-extra-promise alternative"
[#321]: https://github.com/jprichardson/node-fs-extra/issues/321 "fs.copy() with clobber set to false return EEXIST error [feature-copy]"
[#320]: https://github.com/jprichardson/node-fs-extra/issues/320 "fs.copySync: Error: EPERM: operation not permitted, unlink "
[#319]: https://github.com/jprichardson/node-fs-extra/issues/319 "Create directory if not exists"
[#318]: https://github.com/jprichardson/node-fs-extra/issues/318 "Support glob patterns [enhancement, future]"
[#317]: https://github.com/jprichardson/node-fs-extra/pull/317 "Adding copy sync test for src file without write perms"
[#316]: https://github.com/jprichardson/node-fs-extra/pull/316 "Remove move()'s broken limit option [feature-move]"
[#315]: https://github.com/jprichardson/node-fs-extra/pull/315 "Fix move clobber tests to work around graceful-fs bug."
[#314]: https://github.com/jprichardson/node-fs-extra/issues/314 "move() limit option [documentation, enhancement, feature-move]"
[#313]: https://github.com/jprichardson/node-fs-extra/pull/313 "Test that remove() ignores glob characters."
[#312]: https://github.com/jprichardson/node-fs-extra/pull/312 "Enhance walkSync() to return items with path and stats [feature-walk]"
[#311]: https://github.com/jprichardson/node-fs-extra/issues/311 "move() not work when dest name not provided [feature-move]"
[#310]: https://github.com/jprichardson/node-fs-extra/issues/310 "Edit walkSync to return items like what walk emits [documentation, enhancement, feature-walk]"
[#309]: https://github.com/jprichardson/node-fs-extra/issues/309 "moveSync support [enhancement, feature-move]"
[#308]: https://github.com/jprichardson/node-fs-extra/pull/308 "Fix incorrect anchor link"
[#307]: https://github.com/jprichardson/node-fs-extra/pull/307 "Fix coverage"
[#306]: https://github.com/jprichardson/node-fs-extra/pull/306 "Update devDeps, fix lint error"
[#305]: https://github.com/jprichardson/node-fs-extra/pull/305 "Re-add Coveralls"
[#304]: https://github.com/jprichardson/node-fs-extra/pull/304 "Remove path-is-absolute [enhancement]"
[#303]: https://github.com/jprichardson/node-fs-extra/pull/303 "Document copySync filter inconsistency [documentation, feature-copy]"
[#302]: https://github.com/jprichardson/node-fs-extra/pull/302 "fix(console): depreciated -> deprecated"
[#301]: https://github.com/jprichardson/node-fs-extra/pull/301 "Remove chmod call from copySync [feature-copy]"
[#300]: https://github.com/jprichardson/node-fs-extra/pull/300 "Inline Rimraf [enhancement, feature-move, feature-remove]"
[#299]: https://github.com/jprichardson/node-fs-extra/pull/299 "Warn when filter is a RegExp [feature-copy]"
[#298]: https://github.com/jprichardson/node-fs-extra/issues/298 "API Docs [documentation]"
[#297]: https://github.com/jprichardson/node-fs-extra/pull/297 "Warn about using preserveTimestamps on 32-bit node"
[#296]: https://github.com/jprichardson/node-fs-extra/pull/296 "Improve EEXIST error message for copySync [enhancement]"
[#295]: https://github.com/jprichardson/node-fs-extra/pull/295 "Depreciate using regular expressions for copy's filter option [documentation]"
[#294]: https://github.com/jprichardson/node-fs-extra/pull/294 "BREAKING: Refactor lib/copy/ncp.js [feature-copy]"
[#293]: https://github.com/jprichardson/node-fs-extra/pull/293 "Update CI configs"
[#292]: https://github.com/jprichardson/node-fs-extra/issues/292 "Rewrite lib/copy/ncp.js [enhancement, feature-copy]"
[#291]: https://github.com/jprichardson/node-fs-extra/pull/291 "Escape '$' in replacement string for async file copying"
[#290]: https://github.com/jprichardson/node-fs-extra/issues/290 "Exclude files pattern while copying using copy.config.js [question]"
[#289]: https://github.com/jprichardson/node-fs-extra/pull/289 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error"
[#288]: https://github.com/jprichardson/node-fs-extra/pull/288 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error"
[#287]: https://github.com/jprichardson/node-fs-extra/issues/287 "emptyDir() callback arguments are inconsistent [enhancement, feature-remove]"
[#286]: https://github.com/jprichardson/node-fs-extra/pull/286 "Added walkSync function"
[#285]: https://github.com/jprichardson/node-fs-extra/issues/285 "CITGM test failing on s390"
[#284]: https://github.com/jprichardson/node-fs-extra/issues/284 "outputFile method is missing a check to determine if existing item is a folder or not"
[#283]: https://github.com/jprichardson/node-fs-extra/pull/283 "Apply filter also on directories and symlinks for copySync()"
[#282]: https://github.com/jprichardson/node-fs-extra/pull/282 "Apply filter also on directories and symlinks for copySync()"
[#281]: https://github.com/jprichardson/node-fs-extra/issues/281 "remove function executes 'successfully' but doesn't do anything?"
[#280]: https://github.com/jprichardson/node-fs-extra/pull/280 "Disable rimraf globbing"
[#279]: https://github.com/jprichardson/node-fs-extra/issues/279 "Some code is vendored instead of included [awaiting-reply]"
[#278]: https://github.com/jprichardson/node-fs-extra/issues/278 "copy() does not preserve file/directory ownership"
[#277]: https://github.com/jprichardson/node-fs-extra/pull/277 "Mention defaults for clobber and dereference options"
[#276]: https://github.com/jprichardson/node-fs-extra/issues/276 "Cannot connect to Shared Folder [awaiting-reply]"
[#275]: https://github.com/jprichardson/node-fs-extra/issues/275 "EMFILE, too many open files on Mac OS with JSON API"
[#274]: https://github.com/jprichardson/node-fs-extra/issues/274 "Use with memory-fs? [enhancement, future]"
[#273]: https://github.com/jprichardson/node-fs-extra/pull/273 "tests: rename `remote.test.js` to `remove.test.js`"
[#272]: https://github.com/jprichardson/node-fs-extra/issues/272 "Copy clobber flag never err even when true [bug, feature-copy]"
[#271]: https://github.com/jprichardson/node-fs-extra/issues/271 "Unclosed file handle on futimes error"
[#270]: https://github.com/jprichardson/node-fs-extra/issues/270 "copy not working as desired on Windows [feature-copy, platform-windows]"
[#269]: https://github.com/jprichardson/node-fs-extra/issues/269 "Copying with preserveTimeStamps: true is inaccurate using 32bit node [feature-copy]"
[#268]: https://github.com/jprichardson/node-fs-extra/pull/268 "port fix for mkdirp issue #111"
[#267]: https://github.com/jprichardson/node-fs-extra/issues/267 "WARN deprecated wrench@1.5.9: wrench.js is deprecated!"
[#266]: https://github.com/jprichardson/node-fs-extra/issues/266 "fs-extra"
[#265]: https://github.com/jprichardson/node-fs-extra/issues/265 "Link the `fs.stat fs.exists` etc. methods for replace the `fs` module forever?"
[#264]: https://github.com/jprichardson/node-fs-extra/issues/264 "Renaming a file using move fails when a file inside is open (at least on windows) [wont-fix]"
[#263]: https://github.com/jprichardson/node-fs-extra/issues/263 "ENOSYS: function not implemented, link [needs-confirmed]"
[#262]: https://github.com/jprichardson/node-fs-extra/issues/262 "Add .exists() and .existsSync()"
[#261]: https://github.com/jprichardson/node-fs-extra/issues/261 "Cannot read property 'prototype' of undefined"
[#260]: https://github.com/jprichardson/node-fs-extra/pull/260 "use more specific path for method require"
[#259]: https://github.com/jprichardson/node-fs-extra/issues/259 "Feature Request: isEmpty"
[#258]: https://github.com/jprichardson/node-fs-extra/issues/258 "copy files does not preserve file timestamp"
[#257]: https://github.com/jprichardson/node-fs-extra/issues/257 "Copying a file on windows fails"
[#256]: https://github.com/jprichardson/node-fs-extra/pull/256 "Updated Readme "
[#255]: https://github.com/jprichardson/node-fs-extra/issues/255 "Update rimraf required version"
[#254]: https://github.com/jprichardson/node-fs-extra/issues/254 "request for readTree, readTreeSync, walkSync method"
[#253]: https://github.com/jprichardson/node-fs-extra/issues/253 "outputFile does not touch mtime when file exists"
[#252]: https://github.com/jprichardson/node-fs-extra/pull/252 "Fixing problem when copying file with no write permission"
[#251]: https://github.com/jprichardson/node-fs-extra/issues/251 "Just wanted to say thank you"
[#250]: https://github.com/jprichardson/node-fs-extra/issues/250 "`fs.remove()` not removing files (works with `rm -rf`)"
[#249]: https://github.com/jprichardson/node-fs-extra/issues/249 "Just a Question ... Remove Servers"
[#248]: https://github.com/jprichardson/node-fs-extra/issues/248 "Allow option to not preserve permissions for copy"
[#247]: https://github.com/jprichardson/node-fs-extra/issues/247 "Add TypeScript typing directly in the fs-extra package"
[#246]: https://github.com/jprichardson/node-fs-extra/issues/246 "fse.remove() && fse.removeSync() don't throw error on ENOENT file"
[#245]: https://github.com/jprichardson/node-fs-extra/issues/245 "filter for empty dir [enhancement]"
[#244]: https://github.com/jprichardson/node-fs-extra/issues/244 "copySync doesn't apply the filter to directories"
[#243]: https://github.com/jprichardson/node-fs-extra/issues/243 "Can I request fs.walk() to be synchronous?"
[#242]: https://github.com/jprichardson/node-fs-extra/issues/242 "Accidentally truncates file names ending with $$ [bug, feature-copy]"
[#241]: https://github.com/jprichardson/node-fs-extra/pull/241 "Remove link to createOutputStream"
[#240]: https://github.com/jprichardson/node-fs-extra/issues/240 "walkSync request"
[#239]: https://github.com/jprichardson/node-fs-extra/issues/239 "Depreciate regular expressions for copy's filter [documentation, feature-copy]"
[#238]: https://github.com/jprichardson/node-fs-extra/issues/238 "Can't write to files while in a worker thread."
[#237]: https://github.com/jprichardson/node-fs-extra/issues/237 ".ensureDir(..) fails silently when passed an invalid path..."
[#236]: https://github.com/jprichardson/node-fs-extra/issues/236 "[Removed] Filed under wrong repo"
[#235]: https://github.com/jprichardson/node-fs-extra/pull/235 "Adds symlink dereference option to `fse.copySync` (#191)"
[#234]: https://github.com/jprichardson/node-fs-extra/issues/234 "ensureDirSync fails silent when EACCES: permission denied on travis-ci"
[#233]: https://github.com/jprichardson/node-fs-extra/issues/233 "please make sure the first argument in callback is error object [feature-copy]"
[#232]: https://github.com/jprichardson/node-fs-extra/issues/232 "Copy a folder content to its child folder. "
[#231]: https://github.com/jprichardson/node-fs-extra/issues/231 "Adding read/write/output functions for YAML"
[#230]: https://github.com/jprichardson/node-fs-extra/pull/230 "throw error if src and dest are the same to avoid zeroing out + test"
[#229]: https://github.com/jprichardson/node-fs-extra/pull/229 "fix 'TypeError: callback is not a function' in emptyDir"
[#228]: https://github.com/jprichardson/node-fs-extra/pull/228 "Throw error when target is empty so file is not accidentally zeroed out"
[#227]: https://github.com/jprichardson/node-fs-extra/issues/227 "Uncatchable errors when there are invalid arguments [feature-move]"
[#226]: https://github.com/jprichardson/node-fs-extra/issues/226 "Moving to the current directory"
[#225]: https://github.com/jprichardson/node-fs-extra/issues/225 "EBUSY: resource busy or locked, unlink"
[#224]: https://github.com/jprichardson/node-fs-extra/issues/224 "fse.copy ENOENT error"
[#223]: https://github.com/jprichardson/node-fs-extra/issues/223 "Suspicious behavior of fs.existsSync"
[#222]: https://github.com/jprichardson/node-fs-extra/pull/222 "A clearer description of emtpyDir function"
[#221]: https://github.com/jprichardson/node-fs-extra/pull/221 "Update README.md"
[#220]: https://github.com/jprichardson/node-fs-extra/pull/220 "Non-breaking feature: add option 'passStats' to copy methods."
[#219]: https://github.com/jprichardson/node-fs-extra/pull/219 "Add closing parenthesis in copySync example"
[#218]: https://github.com/jprichardson/node-fs-extra/pull/218 "fix #187 #70 options.filter bug"
[#217]: https://github.com/jprichardson/node-fs-extra/pull/217 "fix #187 #70 options.filter bug"
[#216]: https://github.com/jprichardson/node-fs-extra/pull/216 "fix #187 #70 options.filter bug"
[#215]: https://github.com/jprichardson/node-fs-extra/pull/215 "fse.copy throws error when only src and dest provided [bug, documentation, feature-copy]"
[#214]: https://github.com/jprichardson/node-fs-extra/pull/214 "Fixing copySync anchor tag"
[#213]: https://github.com/jprichardson/node-fs-extra/issues/213 "Merge extfs with this repo"
[#212]: https://github.com/jprichardson/node-fs-extra/pull/212 "Update year to 2016 in README.md and LICENSE"
[#211]: https://github.com/jprichardson/node-fs-extra/issues/211 "Not copying all files"
[#210]: https://github.com/jprichardson/node-fs-extra/issues/210 "copy/copySync behave differently when copying a symbolic file [bug, documentation, feature-copy]"
[#209]: https://github.com/jprichardson/node-fs-extra/issues/209 "In Windows invalid directory name causes infinite loop in ensureDir(). [bug]"
[#208]: https://github.com/jprichardson/node-fs-extra/pull/208 "fix options.preserveTimestamps to false in copy-sync by default [feature-copy]"
[#207]: https://github.com/jprichardson/node-fs-extra/issues/207 "Add `compare` suite of functions"
[#206]: https://github.com/jprichardson/node-fs-extra/issues/206 "outputFileSync"
[#205]: https://github.com/jprichardson/node-fs-extra/issues/205 "fix documents about copy/copySync [documentation, feature-copy]"
[#204]: https://github.com/jprichardson/node-fs-extra/pull/204 "allow copy of block and character device files"
[#203]: https://github.com/jprichardson/node-fs-extra/issues/203 "copy method's argument options couldn't be undefined [bug, feature-copy]"
[#202]: https://github.com/jprichardson/node-fs-extra/issues/202 "why there is not a walkSync method?"
[#201]: https://github.com/jprichardson/node-fs-extra/issues/201 "clobber for directories [feature-copy, future]"
[#200]: https://github.com/jprichardson/node-fs-extra/issues/200 "'copySync' doesn't work in sync"
[#199]: https://github.com/jprichardson/node-fs-extra/issues/199 "fs.copySync fails if user does not own file [bug, feature-copy]"
[#198]: https://github.com/jprichardson/node-fs-extra/issues/198 "handle copying between identical files [feature-copy]"
[#197]: https://github.com/jprichardson/node-fs-extra/issues/197 "Missing documentation for `outputFile` `options` 3rd parameter [documentation]"
[#196]: https://github.com/jprichardson/node-fs-extra/issues/196 "copy filter: async function and/or function called with `fs.stat` result [future]"
[#195]: https://github.com/jprichardson/node-fs-extra/issues/195 "How to override with outputFile?"
[#194]: https://github.com/jprichardson/node-fs-extra/pull/194 "allow ensureFile(Sync) to provide data to be written to created file"
[#193]: https://github.com/jprichardson/node-fs-extra/issues/193 "`fs.copy` fails silently if source file is /dev/null [bug, feature-copy]"
[#192]: https://github.com/jprichardson/node-fs-extra/issues/192 "Remove fs.createOutputStream()"
[#191]: https://github.com/jprichardson/node-fs-extra/issues/191 "How to copy symlinks to target as normal folders [feature-copy]"
[#190]: https://github.com/jprichardson/node-fs-extra/pull/190 "copySync to overwrite destination file if readonly and clobber true"
[#189]: https://github.com/jprichardson/node-fs-extra/pull/189 "move.test fix to support CRLF on Windows"
[#188]: https://github.com/jprichardson/node-fs-extra/issues/188 "move.test failing on windows platform"
[#187]: https://github.com/jprichardson/node-fs-extra/issues/187 "Not filter each file, stops on first false [feature-copy]"
[#186]: https://github.com/jprichardson/node-fs-extra/issues/186 "Do you need a .size() function in this module? [future]"
[#185]: https://github.com/jprichardson/node-fs-extra/issues/185 "Doesn't work on NodeJS v4.x"
[#184]: https://github.com/jprichardson/node-fs-extra/issues/184 "CLI equivalent for fs-extra"
[#183]: https://github.com/jprichardson/node-fs-extra/issues/183 "with clobber true, copy and copySync behave differently if destination file is read only [bug, feature-copy]"
[#182]: https://github.com/jprichardson/node-fs-extra/issues/182 "ensureDir(dir, callback) second callback parameter not specified"
[#181]: https://github.com/jprichardson/node-fs-extra/issues/181 "Add ability to remove file securely [enhancement, wont-fix]"
[#180]: https://github.com/jprichardson/node-fs-extra/issues/180 "Filter option doesn't work the same way in copy and copySync [bug, feature-copy]"
[#179]: https://github.com/jprichardson/node-fs-extra/issues/179 "Include opendir"
[#178]: https://github.com/jprichardson/node-fs-extra/issues/178 "ENOTEMPTY is thrown on removeSync "
[#177]: https://github.com/jprichardson/node-fs-extra/issues/177 "fix `remove()` wildcards (introduced by rimraf) [feature-remove]"
[#176]: https://github.com/jprichardson/node-fs-extra/issues/176 "createOutputStream doesn't emit 'end' event"
[#175]: https://github.com/jprichardson/node-fs-extra/issues/175 "[Feature Request].moveSync support [feature-move, future]"
[#174]: https://github.com/jprichardson/node-fs-extra/pull/174 "Fix copy formatting and document options.filter"
[#173]: https://github.com/jprichardson/node-fs-extra/issues/173 "Feature Request: writeJson should mkdirs"
[#172]: https://github.com/jprichardson/node-fs-extra/issues/172 "rename `clobber` flags to `overwrite`"
[#171]: https://github.com/jprichardson/node-fs-extra/issues/171 "remove unnecessary aliases"
[#170]: https://github.com/jprichardson/node-fs-extra/pull/170 "More robust handling of errors moving across virtual drives"
[#169]: https://github.com/jprichardson/node-fs-extra/pull/169 "suppress ensureLink & ensureSymlink dest exists error"
[#168]: https://github.com/jprichardson/node-fs-extra/pull/168 "suppress ensurelink dest exists error"
[#167]: https://github.com/jprichardson/node-fs-extra/pull/167 "Adds basic (string, buffer) support for ensureFile content [future]"
[#166]: https://github.com/jprichardson/node-fs-extra/pull/166 "Adds basic (string, buffer) support for ensureFile content"
[#165]: https://github.com/jprichardson/node-fs-extra/pull/165 "ensure for link & symlink"
[#164]: https://github.com/jprichardson/node-fs-extra/issues/164 "Feature Request: ensureFile to take optional argument for file content"
[#163]: https://github.com/jprichardson/node-fs-extra/issues/163 "ouputJson not formatted out of the box [bug]"
[#162]: https://github.com/jprichardson/node-fs-extra/pull/162 "ensure symlink & link"
[#161]: https://github.com/jprichardson/node-fs-extra/pull/161 "ensure symlink & link"
[#160]: https://github.com/jprichardson/node-fs-extra/pull/160 "ensure symlink & link"
[#159]: https://github.com/jprichardson/node-fs-extra/pull/159 "ensure symlink & link"
[#158]: https://github.com/jprichardson/node-fs-extra/issues/158 "Feature Request: ensureLink and ensureSymlink methods"
[#157]: https://github.com/jprichardson/node-fs-extra/issues/157 "writeJson isn't formatted"
[#156]: https://github.com/jprichardson/node-fs-extra/issues/156 "Promise.promisifyAll doesn't work for some methods"
[#155]: https://github.com/jprichardson/node-fs-extra/issues/155 "Readme"
[#154]: https://github.com/jprichardson/node-fs-extra/issues/154 "/tmp/millis-test-sync"
[#153]: https://github.com/jprichardson/node-fs-extra/pull/153 "Make preserveTimes also work on read-only files. Closes #152"
[#152]: https://github.com/jprichardson/node-fs-extra/issues/152 "fs.copy fails for read-only files with preserveTimestamp=true [feature-copy]"
[#151]: https://github.com/jprichardson/node-fs-extra/issues/151 "TOC does not work correctly on npm [documentation]"
[#150]: https://github.com/jprichardson/node-fs-extra/issues/150 "Remove test file fixtures, create with code."
[#149]: https://github.com/jprichardson/node-fs-extra/issues/149 "/tmp/millis-test-sync"
[#148]: https://github.com/jprichardson/node-fs-extra/issues/148 "split out `Sync` methods in documentation"
[#147]: https://github.com/jprichardson/node-fs-extra/issues/147 "Adding rmdirIfEmpty"
[#146]: https://github.com/jprichardson/node-fs-extra/pull/146 "ensure test.js works"
[#145]: https://github.com/jprichardson/node-fs-extra/issues/145 "Add `fs.exists` and `fs.existsSync` if it doesn't exist."
[#144]: https://github.com/jprichardson/node-fs-extra/issues/144 "tests failing"
[#143]: https://github.com/jprichardson/node-fs-extra/issues/143 "update graceful-fs"
[#142]: https://github.com/jprichardson/node-fs-extra/issues/142 "PrependFile Feature"
[#141]: https://github.com/jprichardson/node-fs-extra/pull/141 "Add option to preserve timestamps"
[#140]: https://github.com/jprichardson/node-fs-extra/issues/140 "Json file reading fails with 'utf8'"
[#139]: https://github.com/jprichardson/node-fs-extra/pull/139 "Preserve file timestamp on copy. Closes #138"
[#138]: https://github.com/jprichardson/node-fs-extra/issues/138 "Preserve timestamps on copying files"
[#137]: https://github.com/jprichardson/node-fs-extra/issues/137 "outputFile/outputJson: Unexpected end of input"
[#136]: https://github.com/jprichardson/node-fs-extra/pull/136 "Update license attribute"
[#135]: https://github.com/jprichardson/node-fs-extra/issues/135 "emptyDir throws Error if no callback is provided"
[#134]: https://github.com/jprichardson/node-fs-extra/pull/134 "Handle EEXIST error when clobbering dir"
[#133]: https://github.com/jprichardson/node-fs-extra/pull/133 "Travis runs with `sudo: false`"
[#132]: https://github.com/jprichardson/node-fs-extra/pull/132 "isDirectory method"
[#131]: https://github.com/jprichardson/node-fs-extra/issues/131 "copySync is not working iojs 1.8.4 on linux [feature-copy]"
[#130]: https://github.com/jprichardson/node-fs-extra/pull/130 "Please review additional features."
[#129]: https://github.com/jprichardson/node-fs-extra/pull/129 "can you review this feature?"
[#128]: https://github.com/jprichardson/node-fs-extra/issues/128 "fsExtra.move(filepath, newPath) broken;"
[#127]: https://github.com/jprichardson/node-fs-extra/issues/127 "consider using fs.access to remove deprecated warnings for fs.exists"
[#126]: https://github.com/jprichardson/node-fs-extra/issues/126 " TypeError: Object #<Object> has no method 'access'"
[#125]: https://github.com/jprichardson/node-fs-extra/issues/125 "Question: What do the *Sync function do different from non-sync"
[#124]: https://github.com/jprichardson/node-fs-extra/issues/124 "move with clobber option 'ENOTEMPTY'"
[#123]: https://github.com/jprichardson/node-fs-extra/issues/123 "Only copy the content of a directory"
[#122]: https://github.com/jprichardson/node-fs-extra/pull/122 "Update section links in README to match current section ids."
[#121]: https://github.com/jprichardson/node-fs-extra/issues/121 "emptyDir is undefined"
[#120]: https://github.com/jprichardson/node-fs-extra/issues/120 "usage bug caused by shallow cloning methods of 'graceful-fs'"
[#119]: https://github.com/jprichardson/node-fs-extra/issues/119 "mkdirs and ensureDir never invoke callback and consume CPU indefinitely if provided a path with invalid characters on Windows"
[#118]: https://github.com/jprichardson/node-fs-extra/pull/118 "createOutputStream"
[#117]: https://github.com/jprichardson/node-fs-extra/pull/117 "Fixed issue with slash separated paths on windows"
[#116]: https://github.com/jprichardson/node-fs-extra/issues/116 "copySync can only copy directories not files [documentation, feature-copy]"
[#115]: https://github.com/jprichardson/node-fs-extra/issues/115 ".Copy & .CopySync [feature-copy]"
[#114]: https://github.com/jprichardson/node-fs-extra/issues/114 "Fails to move (rename) directory to non-empty directory even with clobber: true"
[#113]: https://github.com/jprichardson/node-fs-extra/issues/113 "fs.copy seems to callback early if the destination file already exists"
[#112]: https://github.com/jprichardson/node-fs-extra/pull/112 "Copying a file into an existing directory"
[#111]: https://github.com/jprichardson/node-fs-extra/pull/111 "Moving a file into an existing directory "
[#110]: https://github.com/jprichardson/node-fs-extra/pull/110 "Moving a file into an existing directory"
[#109]: https://github.com/jprichardson/node-fs-extra/issues/109 "fs.move across windows drives fails"
[#108]: https://github.com/jprichardson/node-fs-extra/issues/108 "fse.move directories across multiple devices doesn't work"
[#107]: https://github.com/jprichardson/node-fs-extra/pull/107 "Check if dest path is an existing dir and copy or move source in it"
[#106]: https://github.com/jprichardson/node-fs-extra/issues/106 "fse.copySync crashes while copying across devices D: [feature-copy]"
[#105]: https://github.com/jprichardson/node-fs-extra/issues/105 "fs.copy hangs on iojs"
[#104]: https://github.com/jprichardson/node-fs-extra/issues/104 "fse.move deletes folders [bug]"
[#103]: https://github.com/jprichardson/node-fs-extra/issues/103 "Error: EMFILE with copy"
[#102]: https://github.com/jprichardson/node-fs-extra/issues/102 "touch / touchSync was removed ?"
[#101]: https://github.com/jprichardson/node-fs-extra/issues/101 "fs-extra promisified"
[#100]: https://github.com/jprichardson/node-fs-extra/pull/100 "copy: options object or filter to pass to ncp"
[#99]: https://github.com/jprichardson/node-fs-extra/issues/99 "ensureDir() modes [future]"
[#98]: https://github.com/jprichardson/node-fs-extra/issues/98 "fs.copy() incorrect async behavior [bug]"
[#97]: https://github.com/jprichardson/node-fs-extra/pull/97 "use path.join; fix copySync bug"
[#96]: https://github.com/jprichardson/node-fs-extra/issues/96 "destFolderExists in copySync is always undefined."
[#95]: https://github.com/jprichardson/node-fs-extra/pull/95 "Using graceful-ncp instead of ncp"
[#94]: https://github.com/jprichardson/node-fs-extra/issues/94 "Error: EEXIST, file already exists '../mkdirp/bin/cmd.js' on fs.copySync() [enhancement, feature-copy]"
[#93]: https://github.com/jprichardson/node-fs-extra/issues/93 "Confusing error if drive not mounted [enhancement]"
[#92]: https://github.com/jprichardson/node-fs-extra/issues/92 "Problems with Bluebird"
[#91]: https://github.com/jprichardson/node-fs-extra/issues/91 "fs.copySync('/test', '/haha') is different with 'cp -r /test /haha' [enhancement]"
[#90]: https://github.com/jprichardson/node-fs-extra/issues/90 "Folder creation and file copy is Happening in 64 bit machine but not in 32 bit machine"
[#89]: https://github.com/jprichardson/node-fs-extra/issues/89 "Error: EEXIST using fs-extra's fs.copy to copy a directory on Windows"
[#88]: https://github.com/jprichardson/node-fs-extra/issues/88 "Stacking those libraries"
[#87]: https://github.com/jprichardson/node-fs-extra/issues/87 "createWriteStream + outputFile = ?"
[#86]: https://github.com/jprichardson/node-fs-extra/issues/86 "no moveSync?"
[#85]: https://github.com/jprichardson/node-fs-extra/pull/85 "Copy symlinks in copySync"
[#84]: https://github.com/jprichardson/node-fs-extra/issues/84 "Push latest version to npm ?"
[#83]: https://github.com/jprichardson/node-fs-extra/issues/83 "Prevent copying a directory into itself [feature-copy]"
[#82]: https://github.com/jprichardson/node-fs-extra/pull/82 "README updates for move"
[#81]: https://github.com/jprichardson/node-fs-extra/issues/81 "fd leak after fs.move"
[#80]: https://github.com/jprichardson/node-fs-extra/pull/80 "Preserve file mode in copySync"
[#79]: https://github.com/jprichardson/node-fs-extra/issues/79 "fs.copy only .html file empty"
[#78]: https://github.com/jprichardson/node-fs-extra/pull/78 "copySync was not applying filters to directories"
[#77]: https://github.com/jprichardson/node-fs-extra/issues/77 "Create README reference to bluebird"
[#76]: https://github.com/jprichardson/node-fs-extra/issues/76 "Create README reference to typescript"
[#75]: https://github.com/jprichardson/node-fs-extra/issues/75 "add glob as a dep? [question]"
[#74]: https://github.com/jprichardson/node-fs-extra/pull/74 "including new emptydir module"
[#73]: https://github.com/jprichardson/node-fs-extra/pull/73 "add dependency status in readme"
[#72]: https://github.com/jprichardson/node-fs-extra/pull/72 "Use svg instead of png to get better image quality"
[#71]: https://github.com/jprichardson/node-fs-extra/issues/71 "fse.copy not working on Windows 7 x64 OS, but, copySync does work"
[#70]: https://github.com/jprichardson/node-fs-extra/issues/70 "Not filter each file, stops on first false [bug]"
[#69]: https://github.com/jprichardson/node-fs-extra/issues/69 "How to check if folder exist and read the folder name"
[#68]: https://github.com/jprichardson/node-fs-extra/issues/68 "consider flag to readJsonSync (throw false) [enhancement]"
[#67]: https://github.com/jprichardson/node-fs-extra/issues/67 "docs for readJson incorrectly states that is accepts options"
[#66]: https://github.com/jprichardson/node-fs-extra/issues/66 "ENAMETOOLONG"
[#65]: https://github.com/jprichardson/node-fs-extra/issues/65 "exclude filter in fs.copy"
[#64]: https://github.com/jprichardson/node-fs-extra/issues/64 "Announce: mfs - monitor your fs-extra calls"
[#63]: https://github.com/jprichardson/node-fs-extra/issues/63 "Walk"
[#62]: https://github.com/jprichardson/node-fs-extra/issues/62 "npm install fs-extra doesn't work"
[#61]: https://github.com/jprichardson/node-fs-extra/issues/61 "No longer supports node 0.8 due to use of `^` in package.json dependencies"
[#60]: https://github.com/jprichardson/node-fs-extra/issues/60 "chmod & chown for mkdirs"
[#59]: https://github.com/jprichardson/node-fs-extra/issues/59 "Consider including mkdirp and making fs-extra '--use_strict' safe [question]"
[#58]: https://github.com/jprichardson/node-fs-extra/issues/58 "Stack trace not included in fs.copy error"
[#57]: https://github.com/jprichardson/node-fs-extra/issues/57 "Possible to include wildcards in delete?"
[#56]: https://github.com/jprichardson/node-fs-extra/issues/56 "Crash when have no access to write to destination file in copy "
[#55]: https://github.com/jprichardson/node-fs-extra/issues/55 "Is it possible to have any console output similar to Grunt copy module?"
[#54]: https://github.com/jprichardson/node-fs-extra/issues/54 "`copy` does not preserve file ownership and permissons"
[#53]: https://github.com/jprichardson/node-fs-extra/issues/53 "outputFile() - ability to write data in appending mode"
[#52]: https://github.com/jprichardson/node-fs-extra/pull/52 "This fixes (what I think) is a bug in copySync"
[#51]: https://github.com/jprichardson/node-fs-extra/pull/51 "Add a Bitdeli Badge to README"
[#50]: https://github.com/jprichardson/node-fs-extra/issues/50 "Replace mechanism in createFile"
[#49]: https://github.com/jprichardson/node-fs-extra/pull/49 "update rimraf to v2.2.6"
[#48]: https://github.com/jprichardson/node-fs-extra/issues/48 "fs.copy issue [bug]"
[#47]: https://github.com/jprichardson/node-fs-extra/issues/47 "Bug in copy - callback called on readStream 'close' - Fixed in ncp 0.5.0"
[#46]: https://github.com/jprichardson/node-fs-extra/pull/46 "update copyright year"
[#45]: https://github.com/jprichardson/node-fs-extra/pull/45 "Added note about fse.outputFile() being the one that overwrites"
[#44]: https://github.com/jprichardson/node-fs-extra/pull/44 "Proposal: Stream support"
[#43]: https://github.com/jprichardson/node-fs-extra/issues/43 "Better error reporting "
[#42]: https://github.com/jprichardson/node-fs-extra/issues/42 "Performance issue?"
[#41]: https://github.com/jprichardson/node-fs-extra/pull/41 "There does seem to be a synchronous version now"
[#40]: https://github.com/jprichardson/node-fs-extra/issues/40 "fs.copy throw unexplained error ENOENT, utime "
[#39]: https://github.com/jprichardson/node-fs-extra/pull/39 "Added regression test for copy() return callback on error"
[#38]: https://github.com/jprichardson/node-fs-extra/pull/38 "Return err in copy() fstat cb, because stat could be undefined or null"
[#37]: https://github.com/jprichardson/node-fs-extra/issues/37 "Maybe include a line reader? [enhancement, question]"
[#36]: https://github.com/jprichardson/node-fs-extra/pull/36 "`filter` parameter `fs.copy` and `fs.copySync`"
[#35]: https://github.com/jprichardson/node-fs-extra/pull/35 "`filter` parameter `fs.copy` and `fs.copySync` "
[#34]: https://github.com/jprichardson/node-fs-extra/issues/34 "update docs to include options for JSON methods [enhancement]"
[#33]: https://github.com/jprichardson/node-fs-extra/pull/33 "fs_extra.copySync"
[#32]: https://github.com/jprichardson/node-fs-extra/issues/32 "update to latest jsonfile [enhancement]"
[#31]: https://github.com/jprichardson/node-fs-extra/issues/31 "Add ensure methods [enhancement]"
[#30]: https://github.com/jprichardson/node-fs-extra/issues/30 "update package.json optional dep `graceful-fs`"
[#29]: https://github.com/jprichardson/node-fs-extra/issues/29 "Copy failing if dest directory doesn't exist. Is this intended?"
[#28]: https://github.com/jprichardson/node-fs-extra/issues/28 "homepage field must be a string url. Deleted."
[#27]: https://github.com/jprichardson/node-fs-extra/issues/27 "Update Readme"
[#26]: https://github.com/jprichardson/node-fs-extra/issues/26 "Add readdir recursive method. [enhancement]"
[#25]: https://github.com/jprichardson/node-fs-extra/pull/25 "adding an `.npmignore` file"
[#24]: https://github.com/jprichardson/node-fs-extra/issues/24 "[bug] cannot run in strict mode [bug]"
[#23]: https://github.com/jprichardson/node-fs-extra/issues/23 "`writeJSON()` should create parent directories"
[#22]: https://github.com/jprichardson/node-fs-extra/pull/22 "Add a limit option to mkdirs()"
[#21]: https://github.com/jprichardson/node-fs-extra/issues/21 "touch() in 0.10.0"
[#20]: https://github.com/jprichardson/node-fs-extra/issues/20 "fs.remove yields callback before directory is really deleted"
[#19]: https://github.com/jprichardson/node-fs-extra/issues/19 "fs.copy err is empty array"
[#18]: https://github.com/jprichardson/node-fs-extra/pull/18 "Exposed copyFile Function"
[#17]: https://github.com/jprichardson/node-fs-extra/issues/17 "Use `require('graceful-fs')` if found instead of `require('fs')`"
[#16]: https://github.com/jprichardson/node-fs-extra/pull/16 "Update README.md"
[#15]: https://github.com/jprichardson/node-fs-extra/issues/15 "Implement cp -r but sync aka copySync. [enhancement]"
[#14]: https://github.com/jprichardson/node-fs-extra/issues/14 "fs.mkdirSync is broken in 0.3.1"
[#13]: https://github.com/jprichardson/node-fs-extra/issues/13 "Thoughts on including a directory tree / file watcher? [enhancement, question]"
[#12]: https://github.com/jprichardson/node-fs-extra/issues/12 "copyFile & copyFileSync are global"
[#11]: https://github.com/jprichardson/node-fs-extra/issues/11 "Thoughts on including a file walker? [enhancement, question]"
[#10]: https://github.com/jprichardson/node-fs-extra/issues/10 "move / moveFile API [enhancement]"
[#9]: https://github.com/jprichardson/node-fs-extra/issues/9 "don't import normal fs stuff into fs-extra"
[#8]: https://github.com/jprichardson/node-fs-extra/pull/8 "Update rimraf to latest version"
[#6]: https://github.com/jprichardson/node-fs-extra/issues/6 "Remove CoffeeScript development dependency"
[#5]: https://github.com/jprichardson/node-fs-extra/issues/5 "comments on naming"
[#4]: https://github.com/jprichardson/node-fs-extra/issues/4 "version bump to 0.2"
[#3]: https://github.com/jprichardson/node-fs-extra/pull/3 "Hi! I fixed some code for you!"
[#2]: https://github.com/jprichardson/node-fs-extra/issues/2 "Merge with fs.extra and mkdirp"
[#1]: https://github.com/jprichardson/node-fs-extra/issues/1 "file-extra npm !exist"
+15
View File
@@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2011-2017 JP Richardson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+261
View File
@@ -0,0 +1,261 @@
Node.js: fs-extra
=================
`fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`.
[![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![License](https://img.shields.io/npm/l/express.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE)
[![build status](https://img.shields.io/travis/jprichardson/node-fs-extra/master.svg)](http://travis-ci.org/jprichardson/node-fs-extra)
[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-fs-extra/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-fs-extra/branch/master)
[![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![Coverage Status](https://img.shields.io/coveralls/github/jprichardson/node-fs-extra/master.svg)](https://coveralls.io/github/jprichardson/node-fs-extra)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
Why?
----
I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects.
Installation
------------
npm install fs-extra
Usage
-----
`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed.
You don't ever need to include the original `fs` module again:
```js
const fs = require('fs') // this is no longer necessary
```
you can now do this:
```js
const fs = require('fs-extra')
```
or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want
to name your `fs` variable `fse` like so:
```js
const fse = require('fs-extra')
```
you can also keep both, but it's redundant:
```js
const fs = require('fs')
const fse = require('fs-extra')
```
Sync vs Async vs Async/Await
-------------
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
```js
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
```
Methods
-------
### Async
- [copy](docs/copy.md)
- [emptyDir](docs/emptyDir.md)
- [ensureFile](docs/ensureFile.md)
- [ensureDir](docs/ensureDir.md)
- [ensureLink](docs/ensureLink.md)
- [ensureSymlink](docs/ensureSymlink.md)
- [mkdirp](docs/ensureDir.md)
- [mkdirs](docs/ensureDir.md)
- [move](docs/move.md)
- [outputFile](docs/outputFile.md)
- [outputJson](docs/outputJson.md)
- [pathExists](docs/pathExists.md)
- [readJson](docs/readJson.md)
- [remove](docs/remove.md)
- [writeJson](docs/writeJson.md)
### Sync
- [copySync](docs/copy-sync.md)
- [emptyDirSync](docs/emptyDir-sync.md)
- [ensureFileSync](docs/ensureFile-sync.md)
- [ensureDirSync](docs/ensureDir-sync.md)
- [ensureLinkSync](docs/ensureLink-sync.md)
- [ensureSymlinkSync](docs/ensureSymlink-sync.md)
- [mkdirpSync](docs/ensureDir-sync.md)
- [mkdirsSync](docs/ensureDir-sync.md)
- [moveSync](docs/move-sync.md)
- [outputFileSync](docs/outputFile-sync.md)
- [outputJsonSync](docs/outputJson-sync.md)
- [pathExistsSync](docs/pathExists-sync.md)
- [readJsonSync](docs/readJson-sync.md)
- [removeSync](docs/remove-sync.md)
- [writeJsonSync](docs/writeJson-sync.md)
**NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()` & `fs.write()`](docs/fs-read-write.md)
### What happened to `walk()` and `walkSync()`?
They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync).
Third Party
-----------
### TypeScript
If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
### File / Directory Watching
If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar).
### Obtain Filesystem (Devices, Partitions) Information
[fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
### Misc.
- [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug).
- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls.
Hacking on fs-extra
-------------------
Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project
uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you,
you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`.
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
What's needed?
- First, take a look at existing issues. Those are probably going to be where the priority lies.
- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
- Improve test coverage. See coveralls output for more info.
Note: If you make any big changes, **you should definitely file an issue for discussion first.**
### Running the Test Suite
fs-extra contains hundreds of tests.
- `npm run lint`: runs the linter ([standard](http://standardjs.com/))
- `npm run unit`: runs the unit tests
- `npm test`: runs both the linter and the tests
### Windows
If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my `fs-extra` directory and run the tests.
Naming
------
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
* https://github.com/jprichardson/node-fs-extra/issues/2
* https://github.com/flatiron/utile/issues/11
* https://github.com/ryanmcgrath/wrench-js/issues/29
* https://github.com/substack/node-mkdirp/issues/17
First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes.
For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`.
Credit
------
`fs-extra` wouldn't be possible without using the modules from the following authors:
- [Isaac Shlueter](https://github.com/isaacs)
- [Charlie McConnel](https://github.com/avianflu)
- [James Halliday](https://github.com/substack)
- [Andrew Kelley](https://github.com/andrewrk)
License
-------
Licensed under MIT
Copyright (c) 2011-2017 [JP Richardson](https://github.com/jprichardson)
[1]: http://nodejs.org/docs/latest/api/fs.html
[jsonfile]: https://github.com/jprichardson/node-jsonfile
@@ -0,0 +1,164 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirpSync = require('../mkdirs').mkdirsSync
const utimesSync = require('../util/utimes.js').utimesMillisSync
const stat = require('../util/stat')
function copySync (src, dest, opts) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
see https://github.com/jprichardson/node-fs-extra/issues/269`)
}
const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy')
stat.checkParentPathsSync(src, srcStat, dest, 'copy')
return handleFilterAndCopy(destStat, src, dest, opts)
}
function handleFilterAndCopy (destStat, src, dest, opts) {
if (opts.filter && !opts.filter(src, dest)) return
const destParent = path.dirname(dest)
if (!fs.existsSync(destParent)) mkdirpSync(destParent)
return startCopy(destStat, src, dest, opts)
}
function startCopy (destStat, src, dest, opts) {
if (opts.filter && !opts.filter(src, dest)) return
return getStats(destStat, src, dest, opts)
}
function getStats (destStat, src, dest, opts) {
const statSync = opts.dereference ? fs.statSync : fs.lstatSync
const srcStat = statSync(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
}
function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
return mayCopyFile(srcStat, src, dest, opts)
}
function mayCopyFile (srcStat, src, dest, opts) {
if (opts.overwrite) {
fs.unlinkSync(dest)
return copyFile(srcStat, src, dest, opts)
} else if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
function copyFile (srcStat, src, dest, opts) {
if (typeof fs.copyFileSync === 'function') {
fs.copyFileSync(src, dest)
fs.chmodSync(dest, srcStat.mode)
if (opts.preserveTimestamps) {
return utimesSync(dest, srcStat.atime, srcStat.mtime)
}
return
}
return copyFileFallback(srcStat, src, dest, opts)
}
function copyFileFallback (srcStat, src, dest, opts) {
const BUF_LENGTH = 64 * 1024
const _buff = require('../util/buffer')(BUF_LENGTH)
const fdr = fs.openSync(src, 'r')
const fdw = fs.openSync(dest, 'w', srcStat.mode)
let pos = 0
while (pos < srcStat.size) {
const bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
fs.writeSync(fdw, _buff, 0, bytesRead)
pos += bytesRead
}
if (opts.preserveTimestamps) fs.futimesSync(fdw, srcStat.atime, srcStat.mtime)
fs.closeSync(fdr)
fs.closeSync(fdw)
}
function onDir (srcStat, destStat, src, dest, opts) {
if (!destStat) return mkDirAndCopy(srcStat, src, dest, opts)
if (destStat && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
return copyDir(src, dest, opts)
}
function mkDirAndCopy (srcStat, src, dest, opts) {
fs.mkdirSync(dest)
copyDir(src, dest, opts)
return fs.chmodSync(dest, srcStat.mode)
}
function copyDir (src, dest, opts) {
fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts))
}
function copyDirItem (item, src, dest, opts) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy')
return startCopy(destStat, srcItem, destItem, opts)
}
function onLink (destStat, src, dest, opts) {
let resolvedSrc = fs.readlinkSync(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlinkSync(resolvedSrc, dest)
} else {
let resolvedDest
try {
resolvedDest = fs.readlinkSync(dest)
} catch (err) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
throw err
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// prevent copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
return copyLink(resolvedSrc, dest)
}
}
function copyLink (resolvedSrc, dest) {
fs.unlinkSync(dest)
return fs.symlinkSync(resolvedSrc, dest)
}
module.exports = copySync
@@ -0,0 +1,5 @@
'use strict'
module.exports = {
copySync: require('./copy-sync')
}
+212
View File
@@ -0,0 +1,212 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirp = require('../mkdirs').mkdirs
const pathExists = require('../path-exists').pathExists
const utimes = require('../util/utimes').utimesMillis
const stat = require('../util/stat')
function copy (src, dest, opts, cb) {
if (typeof opts === 'function' && !cb) {
cb = opts
opts = {}
} else if (typeof opts === 'function') {
opts = { filter: opts }
}
cb = cb || function () {}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
see https://github.com/jprichardson/node-fs-extra/issues/269`)
}
stat.checkPaths(src, dest, 'copy', (err, stats) => {
if (err) return cb(err)
const { srcStat, destStat } = stats
stat.checkParentPaths(src, srcStat, dest, 'copy', err => {
if (err) return cb(err)
if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)
return checkParentDir(destStat, src, dest, opts, cb)
})
})
}
function checkParentDir (destStat, src, dest, opts, cb) {
const destParent = path.dirname(dest)
pathExists(destParent, (err, dirExists) => {
if (err) return cb(err)
if (dirExists) return startCopy(destStat, src, dest, opts, cb)
mkdirp(destParent, err => {
if (err) return cb(err)
return startCopy(destStat, src, dest, opts, cb)
})
})
}
function handleFilter (onInclude, destStat, src, dest, opts, cb) {
Promise.resolve(opts.filter(src, dest)).then(include => {
if (include) return onInclude(destStat, src, dest, opts, cb)
return cb()
}, error => cb(error))
}
function startCopy (destStat, src, dest, opts, cb) {
if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb)
return getStats(destStat, src, dest, opts, cb)
}
function getStats (destStat, src, dest, opts, cb) {
const stat = opts.dereference ? fs.stat : fs.lstat
stat(src, (err, srcStat) => {
if (err) return cb(err)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb)
})
}
function onFile (srcStat, destStat, src, dest, opts, cb) {
if (!destStat) return copyFile(srcStat, src, dest, opts, cb)
return mayCopyFile(srcStat, src, dest, opts, cb)
}
function mayCopyFile (srcStat, src, dest, opts, cb) {
if (opts.overwrite) {
fs.unlink(dest, err => {
if (err) return cb(err)
return copyFile(srcStat, src, dest, opts, cb)
})
} else if (opts.errorOnExist) {
return cb(new Error(`'${dest}' already exists`))
} else return cb()
}
function copyFile (srcStat, src, dest, opts, cb) {
if (typeof fs.copyFile === 'function') {
return fs.copyFile(src, dest, err => {
if (err) return cb(err)
return setDestModeAndTimestamps(srcStat, dest, opts, cb)
})
}
return copyFileFallback(srcStat, src, dest, opts, cb)
}
function copyFileFallback (srcStat, src, dest, opts, cb) {
const rs = fs.createReadStream(src)
rs.on('error', err => cb(err)).once('open', () => {
const ws = fs.createWriteStream(dest, { mode: srcStat.mode })
ws.on('error', err => cb(err))
.on('open', () => rs.pipe(ws))
.once('close', () => setDestModeAndTimestamps(srcStat, dest, opts, cb))
})
}
function setDestModeAndTimestamps (srcStat, dest, opts, cb) {
fs.chmod(dest, srcStat.mode, err => {
if (err) return cb(err)
if (opts.preserveTimestamps) {
return utimes(dest, srcStat.atime, srcStat.mtime, cb)
}
return cb()
})
}
function onDir (srcStat, destStat, src, dest, opts, cb) {
if (!destStat) return mkDirAndCopy(srcStat, src, dest, opts, cb)
if (destStat && !destStat.isDirectory()) {
return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
}
return copyDir(src, dest, opts, cb)
}
function mkDirAndCopy (srcStat, src, dest, opts, cb) {
fs.mkdir(dest, err => {
if (err) return cb(err)
copyDir(src, dest, opts, err => {
if (err) return cb(err)
return fs.chmod(dest, srcStat.mode, cb)
})
})
}
function copyDir (src, dest, opts, cb) {
fs.readdir(src, (err, items) => {
if (err) return cb(err)
return copyDirItems(items, src, dest, opts, cb)
})
}
function copyDirItems (items, src, dest, opts, cb) {
const item = items.pop()
if (!item) return cb()
return copyDirItem(items, item, src, dest, opts, cb)
}
function copyDirItem (items, item, src, dest, opts, cb) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => {
if (err) return cb(err)
const { destStat } = stats
startCopy(destStat, srcItem, destItem, opts, err => {
if (err) return cb(err)
return copyDirItems(items, src, dest, opts, cb)
})
})
}
function onLink (destStat, src, dest, opts, cb) {
fs.readlink(src, (err, resolvedSrc) => {
if (err) return cb(err)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlink(resolvedSrc, dest, cb)
} else {
fs.readlink(dest, (err, resolvedDest) => {
if (err) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb)
return cb(err)
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))
}
// do not copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
}
return copyLink(resolvedSrc, dest, cb)
})
}
})
}
function copyLink (resolvedSrc, dest, cb) {
fs.unlink(dest, err => {
if (err) return cb(err)
return fs.symlink(resolvedSrc, dest, cb)
})
}
module.exports = copy
+6
View File
@@ -0,0 +1,6 @@
'use strict'
const u = require('universalify').fromCallback
module.exports = {
copy: u(require('./copy'))
}
+48
View File
@@ -0,0 +1,48 @@
'use strict'
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const path = require('path')
const mkdir = require('../mkdirs')
const remove = require('../remove')
const emptyDir = u(function emptyDir (dir, callback) {
callback = callback || function () {}
fs.readdir(dir, (err, items) => {
if (err) return mkdir.mkdirs(dir, callback)
items = items.map(item => path.join(dir, item))
deleteItem()
function deleteItem () {
const item = items.pop()
if (!item) return callback()
remove.remove(item, err => {
if (err) return callback(err)
deleteItem()
})
}
})
})
function emptyDirSync (dir) {
let items
try {
items = fs.readdirSync(dir)
} catch (err) {
return mkdir.mkdirsSync(dir)
}
items.forEach(item => {
item = path.join(dir, item)
remove.removeSync(item)
})
}
module.exports = {
emptyDirSync,
emptydirSync: emptyDirSync,
emptyDir,
emptydir: emptyDir
}
+49
View File
@@ -0,0 +1,49 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
function createFile (file, callback) {
function makeFile () {
fs.writeFile(file, '', err => {
if (err) return callback(err)
callback()
})
}
fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
if (!err && stats.isFile()) return callback()
const dir = path.dirname(file)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return makeFile()
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
makeFile()
})
})
})
}
function createFileSync (file) {
let stats
try {
stats = fs.statSync(file)
} catch (e) {}
if (stats && stats.isFile()) return
const dir = path.dirname(file)
if (!fs.existsSync(dir)) {
mkdir.mkdirsSync(dir)
}
fs.writeFileSync(file, '')
}
module.exports = {
createFile: u(createFile),
createFileSync
}
+23
View File
@@ -0,0 +1,23 @@
'use strict'
const file = require('./file')
const link = require('./link')
const symlink = require('./symlink')
module.exports = {
// file
createFile: file.createFile,
createFileSync: file.createFileSync,
ensureFile: file.createFile,
ensureFileSync: file.createFileSync,
// link
createLink: link.createLink,
createLinkSync: link.createLinkSync,
ensureLink: link.createLink,
ensureLinkSync: link.createLinkSync,
// symlink
createSymlink: symlink.createSymlink,
createSymlinkSync: symlink.createSymlinkSync,
ensureSymlink: symlink.createSymlink,
ensureSymlinkSync: symlink.createSymlinkSync
}
+61
View File
@@ -0,0 +1,61 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
function createLink (srcpath, dstpath, callback) {
function makeLink (srcpath, dstpath) {
fs.link(srcpath, dstpath, err => {
if (err) return callback(err)
callback(null)
})
}
pathExists(dstpath, (err, destinationExists) => {
if (err) return callback(err)
if (destinationExists) return callback(null)
fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureLink')
return callback(err)
}
const dir = path.dirname(dstpath)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return makeLink(srcpath, dstpath)
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
makeLink(srcpath, dstpath)
})
})
})
})
}
function createLinkSync (srcpath, dstpath) {
const destinationExists = fs.existsSync(dstpath)
if (destinationExists) return undefined
try {
fs.lstatSync(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
const dir = path.dirname(dstpath)
const dirExists = fs.existsSync(dir)
if (dirExists) return fs.linkSync(srcpath, dstpath)
mkdir.mkdirsSync(dir)
return fs.linkSync(srcpath, dstpath)
}
module.exports = {
createLink: u(createLink),
createLinkSync
}
@@ -0,0 +1,99 @@
'use strict'
const path = require('path')
const fs = require('graceful-fs')
const pathExists = require('../path-exists').pathExists
/**
* Function that returns two types of paths, one relative to symlink, and one
* relative to the current working directory. Checks if path is absolute or
* relative. If the path is relative, this function checks if the path is
* relative to symlink or relative to current working directory. This is an
* initiative to find a smarter `srcpath` to supply when building symlinks.
* This allows you to determine which path to use out of one of three possible
* types of source paths. The first is an absolute path. This is detected by
* `path.isAbsolute()`. When an absolute path is provided, it is checked to
* see if it exists. If it does it's used, if not an error is returned
* (callback)/ thrown (sync). The other two options for `srcpath` are a
* relative url. By default Node's `fs.symlink` works by creating a symlink
* using `dstpath` and expects the `srcpath` to be relative to the newly
* created symlink. If you provide a `srcpath` that does not exist on the file
* system it results in a broken symlink. To minimize this, the function
* checks to see if the 'relative to symlink' source file exists, and if it
* does it will use it. If it does not, it checks if there's a file that
* exists that is relative to the current working directory, if does its used.
* This preserves the expectations of the original fs.symlink spec and adds
* the ability to pass in `relative to current working direcotry` paths.
*/
function symlinkPaths (srcpath, dstpath, callback) {
if (path.isAbsolute(srcpath)) {
return fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
'toCwd': srcpath,
'toDst': srcpath
})
})
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
return pathExists(relativeToDst, (err, exists) => {
if (err) return callback(err)
if (exists) {
return callback(null, {
'toCwd': relativeToDst,
'toDst': srcpath
})
} else {
return fs.lstat(srcpath, (err) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
'toCwd': srcpath,
'toDst': path.relative(dstdir, srcpath)
})
})
}
})
}
}
function symlinkPathsSync (srcpath, dstpath) {
let exists
if (path.isAbsolute(srcpath)) {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('absolute srcpath does not exist')
return {
'toCwd': srcpath,
'toDst': srcpath
}
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
exists = fs.existsSync(relativeToDst)
if (exists) {
return {
'toCwd': relativeToDst,
'toDst': srcpath
}
} else {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('relative srcpath does not exist')
return {
'toCwd': srcpath,
'toDst': path.relative(dstdir, srcpath)
}
}
}
}
module.exports = {
symlinkPaths,
symlinkPathsSync
}
@@ -0,0 +1,31 @@
'use strict'
const fs = require('graceful-fs')
function symlinkType (srcpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
if (type) return callback(null, type)
fs.lstat(srcpath, (err, stats) => {
if (err) return callback(null, 'file')
type = (stats && stats.isDirectory()) ? 'dir' : 'file'
callback(null, type)
})
}
function symlinkTypeSync (srcpath, type) {
let stats
if (type) return type
try {
stats = fs.lstatSync(srcpath)
} catch (e) {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
module.exports = {
symlinkType,
symlinkTypeSync
}
+63
View File
@@ -0,0 +1,63 @@
'use strict'
const u = require('universalify').fromCallback
const path = require('path')
const fs = require('graceful-fs')
const _mkdirs = require('../mkdirs')
const mkdirs = _mkdirs.mkdirs
const mkdirsSync = _mkdirs.mkdirsSync
const _symlinkPaths = require('./symlink-paths')
const symlinkPaths = _symlinkPaths.symlinkPaths
const symlinkPathsSync = _symlinkPaths.symlinkPathsSync
const _symlinkType = require('./symlink-type')
const symlinkType = _symlinkType.symlinkType
const symlinkTypeSync = _symlinkType.symlinkTypeSync
const pathExists = require('../path-exists').pathExists
function createSymlink (srcpath, dstpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
pathExists(dstpath, (err, destinationExists) => {
if (err) return callback(err)
if (destinationExists) return callback(null)
symlinkPaths(srcpath, dstpath, (err, relative) => {
if (err) return callback(err)
srcpath = relative.toDst
symlinkType(relative.toCwd, type, (err, type) => {
if (err) return callback(err)
const dir = path.dirname(dstpath)
pathExists(dir, (err, dirExists) => {
if (err) return callback(err)
if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
mkdirs(dir, err => {
if (err) return callback(err)
fs.symlink(srcpath, dstpath, type, callback)
})
})
})
})
})
}
function createSymlinkSync (srcpath, dstpath, type) {
const destinationExists = fs.existsSync(dstpath)
if (destinationExists) return undefined
const relative = symlinkPathsSync(srcpath, dstpath)
srcpath = relative.toDst
type = symlinkTypeSync(relative.toCwd, type)
const dir = path.dirname(dstpath)
const exists = fs.existsSync(dir)
if (exists) return fs.symlinkSync(srcpath, dstpath, type)
mkdirsSync(dir)
return fs.symlinkSync(srcpath, dstpath, type)
}
module.exports = {
createSymlink: u(createSymlink),
createSymlinkSync
}
+109
View File
@@ -0,0 +1,109 @@
'use strict'
// This is adapted from https://github.com/normalize/mz
// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const api = [
'access',
'appendFile',
'chmod',
'chown',
'close',
'copyFile',
'fchmod',
'fchown',
'fdatasync',
'fstat',
'fsync',
'ftruncate',
'futimes',
'lchown',
'lchmod',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'readFile',
'readdir',
'readlink',
'realpath',
'rename',
'rmdir',
'stat',
'symlink',
'truncate',
'unlink',
'utimes',
'writeFile'
].filter(key => {
// Some commands are not available on some systems. Ex:
// fs.copyFile was added in Node.js v8.5.0
// fs.mkdtemp was added in Node.js v5.10.0
// fs.lchown is not available on at least some Linux
return typeof fs[key] === 'function'
})
// Export all keys:
Object.keys(fs).forEach(key => {
if (key === 'promises') {
// fs.promises is a getter property that triggers ExperimentalWarning
// Don't re-export it here, the getter is defined in "lib/index.js"
return
}
exports[key] = fs[key]
})
// Universalify async methods:
api.forEach(method => {
exports[method] = u(fs[method])
})
// We differ from mz/fs in that we still ship the old, broken, fs.exists()
// since we are a drop-in replacement for the native module
exports.exists = function (filename, callback) {
if (typeof callback === 'function') {
return fs.exists(filename, callback)
}
return new Promise(resolve => {
return fs.exists(filename, resolve)
})
}
// fs.read() & fs.write need special treatment due to multiple callback args
exports.read = function (fd, buffer, offset, length, position, callback) {
if (typeof callback === 'function') {
return fs.read(fd, buffer, offset, length, position, callback)
}
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) return reject(err)
resolve({ bytesRead, buffer })
})
})
}
// Function signature can be
// fs.write(fd, buffer[, offset[, length[, position]]], callback)
// OR
// fs.write(fd, string[, position[, encoding]], callback)
// We need to handle both cases, so we use ...args
exports.write = function (fd, buffer, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.write(fd, buffer, ...args)
}
return new Promise((resolve, reject) => {
fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
if (err) return reject(err)
resolve({ bytesWritten, buffer })
})
})
}
// fs.realpath.native only available in Node v9.2+
if (typeof fs.realpath.native === 'function') {
exports.realpath.native = u(fs.realpath.native)
}
+28
View File
@@ -0,0 +1,28 @@
'use strict'
module.exports = Object.assign(
{},
// Export promiseified graceful-fs:
require('./fs'),
// Export extra methods:
require('./copy-sync'),
require('./copy'),
require('./empty'),
require('./ensure'),
require('./json'),
require('./mkdirs'),
require('./move-sync'),
require('./move'),
require('./output'),
require('./path-exists'),
require('./remove')
)
// Export fs.promises as a getter property so that we don't trigger
// ExperimentalWarning before fs.promises is actually accessed.
const fs = require('fs')
if (Object.getOwnPropertyDescriptor(fs, 'promises')) {
Object.defineProperty(module.exports, 'promises', {
get () { return fs.promises }
})
}
+16
View File
@@ -0,0 +1,16 @@
'use strict'
const u = require('universalify').fromCallback
const jsonFile = require('./jsonfile')
jsonFile.outputJson = u(require('./output-json'))
jsonFile.outputJsonSync = require('./output-json-sync')
// aliases
jsonFile.outputJSON = jsonFile.outputJson
jsonFile.outputJSONSync = jsonFile.outputJsonSync
jsonFile.writeJSON = jsonFile.writeJson
jsonFile.writeJSONSync = jsonFile.writeJsonSync
jsonFile.readJSON = jsonFile.readJson
jsonFile.readJSONSync = jsonFile.readJsonSync
module.exports = jsonFile
+12
View File
@@ -0,0 +1,12 @@
'use strict'
const u = require('universalify').fromCallback
const jsonFile = require('jsonfile')
module.exports = {
// jsonfile exports
readJson: u(jsonFile.readFile),
readJsonSync: jsonFile.readFileSync,
writeJson: u(jsonFile.writeFile),
writeJsonSync: jsonFile.writeFileSync
}
@@ -0,0 +1,18 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdir = require('../mkdirs')
const jsonFile = require('./jsonfile')
function outputJsonSync (file, data, options) {
const dir = path.dirname(file)
if (!fs.existsSync(dir)) {
mkdir.mkdirsSync(dir)
}
jsonFile.writeJsonSync(file, data, options)
}
module.exports = outputJsonSync
@@ -0,0 +1,27 @@
'use strict'
const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
const jsonFile = require('./jsonfile')
function outputJson (file, data, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
const dir = path.dirname(file)
pathExists(dir, (err, itDoes) => {
if (err) return callback(err)
if (itDoes) return jsonFile.writeJson(file, data, options, callback)
mkdir.mkdirs(dir, err => {
if (err) return callback(err)
jsonFile.writeJson(file, data, options, callback)
})
})
}
module.exports = outputJson
+14
View File
@@ -0,0 +1,14 @@
'use strict'
const u = require('universalify').fromCallback
const mkdirs = u(require('./mkdirs'))
const mkdirsSync = require('./mkdirs-sync')
module.exports = {
mkdirs,
mkdirsSync,
// alias
mkdirp: mkdirs,
mkdirpSync: mkdirsSync,
ensureDir: mkdirs,
ensureDirSync: mkdirsSync
}
@@ -0,0 +1,54 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const invalidWin32Path = require('./win32').invalidWin32Path
const o777 = parseInt('0777', 8)
function mkdirsSync (p, opts, made) {
if (!opts || typeof opts !== 'object') {
opts = { mode: opts }
}
let mode = opts.mode
const xfs = opts.fs || fs
if (process.platform === 'win32' && invalidWin32Path(p)) {
const errInval = new Error(p + ' contains invalid WIN32 path characters.')
errInval.code = 'EINVAL'
throw errInval
}
if (mode === undefined) {
mode = o777 & (~process.umask())
}
if (!made) made = null
p = path.resolve(p)
try {
xfs.mkdirSync(p, mode)
made = made || p
} catch (err0) {
if (err0.code === 'ENOENT') {
if (path.dirname(p) === p) throw err0
made = mkdirsSync(path.dirname(p), opts, made)
mkdirsSync(p, opts, made)
} else {
// In the case of any other error, just see if there's a dir there
// already. If so, then hooray! If not, then something is borked.
let stat
try {
stat = xfs.statSync(p)
} catch (err1) {
throw err0
}
if (!stat.isDirectory()) throw err0
}
}
return made
}
module.exports = mkdirsSync
+63
View File
@@ -0,0 +1,63 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const invalidWin32Path = require('./win32').invalidWin32Path
const o777 = parseInt('0777', 8)
function mkdirs (p, opts, callback, made) {
if (typeof opts === 'function') {
callback = opts
opts = {}
} else if (!opts || typeof opts !== 'object') {
opts = { mode: opts }
}
if (process.platform === 'win32' && invalidWin32Path(p)) {
const errInval = new Error(p + ' contains invalid WIN32 path characters.')
errInval.code = 'EINVAL'
return callback(errInval)
}
let mode = opts.mode
const xfs = opts.fs || fs
if (mode === undefined) {
mode = o777 & (~process.umask())
}
if (!made) made = null
callback = callback || function () {}
p = path.resolve(p)
xfs.mkdir(p, mode, er => {
if (!er) {
made = made || p
return callback(null, made)
}
switch (er.code) {
case 'ENOENT':
if (path.dirname(p) === p) return callback(er)
mkdirs(path.dirname(p), opts, (er, made) => {
if (er) callback(er, made)
else mkdirs(p, opts, callback, made)
})
break
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
xfs.stat(p, (er2, stat) => {
// if the stat fails, then that's super weird.
// let the original error be the failure reason.
if (er2 || !stat.isDirectory()) callback(er, made)
else callback(null, made)
})
break
}
})
}
module.exports = mkdirs
+25
View File
@@ -0,0 +1,25 @@
'use strict'
const path = require('path')
// get drive on windows
function getRootPath (p) {
p = path.normalize(path.resolve(p)).split(path.sep)
if (p.length > 0) return p[0]
return null
}
// http://stackoverflow.com/a/62888/10333 contains more accurate
// TODO: expand to include the rest
const INVALID_PATH_CHARS = /[<>:"|?*]/
function invalidWin32Path (p) {
const rp = getRootPath(p)
p = p.replace(rp, '')
return INVALID_PATH_CHARS.test(p)
}
module.exports = {
getRootPath,
invalidWin32Path
}
@@ -0,0 +1,5 @@
'use strict'
module.exports = {
moveSync: require('./move-sync')
}

Some files were not shown because too many files have changed in this diff Show More