mirror of
https://github.com/apache/cordova-android.git
synced 2026-04-23 00:00:09 +08:00
CB-14145 remove old node_modules before patch fix
This commit is contained in:
-1
@@ -1 +0,0 @@
|
||||
spec/fixtures/*
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
root: true
|
||||
extends: semistandard
|
||||
rules:
|
||||
indent:
|
||||
- error
|
||||
- 4
|
||||
camelcase: off
|
||||
padded-blocks: off
|
||||
operator-linebreak: off
|
||||
no-throw-literal: off
|
||||
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"disallowMixedSpacesAndTabs": true,
|
||||
"disallowTrailingWhitespace": true,
|
||||
"validateLineBreaks": "LF",
|
||||
"validateIndentation": 4,
|
||||
"requireLineFeedAtFileEnd": true,
|
||||
|
||||
"disallowSpaceAfterPrefixUnaryOperators": true,
|
||||
"disallowSpaceBeforePostfixUnaryOperators": true,
|
||||
"requireSpaceAfterLineComment": true,
|
||||
"requireCapitalizedConstructors": true,
|
||||
|
||||
"disallowSpacesInNamedFunctionExpression": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
},
|
||||
|
||||
"requireSpaceAfterKeywords": [
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"do"
|
||||
]
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
fixtures
|
||||
coverage
|
||||
jasmine.json
|
||||
appveyor.yml
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
language: node_js
|
||||
sudo: false
|
||||
git:
|
||||
depth: 10
|
||||
node_js:
|
||||
- "4"
|
||||
- "6"
|
||||
- "8"
|
||||
install:
|
||||
- npm install
|
||||
- npm install -g codecov
|
||||
script:
|
||||
- npm test
|
||||
- npm run cover
|
||||
after_script:
|
||||
- codecov
|
||||
-157
@@ -1,157 +0,0 @@
|
||||
<!--
|
||||
#
|
||||
# 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.
|
||||
#
|
||||
-->
|
||||
|
||||
[](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-common/branch/master)
|
||||
[](https://travis-ci.org/apache/cordova-common)
|
||||
[](https://nodei.co/npm/cordova-common/)
|
||||
|
||||
# cordova-common
|
||||
Expoeses 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://git-wip-us.apache.org/repos/asf/cordova-lib.git`
|
||||
* In terminal, navigate to the inner cordova-common directory
|
||||
`cd cordova-lib/cordova-common`
|
||||
* Install dependencies and npm-link
|
||||
`npm install && npm link`
|
||||
* Navigate to cordova-lib directory and link cordova-common
|
||||
`cd ../cordova-lib && npm link cordova-common && npm install`
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
<!--
|
||||
#
|
||||
# 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
|
||||
|
||||
### 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
|
||||
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
# appveyor file
|
||||
# http://www.appveyor.com/docs/appveyor-yml
|
||||
|
||||
environment:
|
||||
matrix:
|
||||
- nodejs_version: "4"
|
||||
- nodejs_version: "6"
|
||||
- nodejs_version: "8"
|
||||
|
||||
install:
|
||||
- ps: Install-Product node $env:nodejs_version
|
||||
- npm install
|
||||
|
||||
build: off
|
||||
|
||||
test_script:
|
||||
- node --version
|
||||
- npm --version
|
||||
- npm test
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
{
|
||||
"_args": [
|
||||
[
|
||||
{
|
||||
"raw": "cordova-common@^2.2.0",
|
||||
"scope": null,
|
||||
"escapedName": "cordova-common",
|
||||
"name": "cordova-common",
|
||||
"rawSpec": "^2.2.0",
|
||||
"spec": ">=2.2.0 <3.0.0",
|
||||
"type": "range"
|
||||
},
|
||||
"/Users/steveng/repo/cordova/cordova-android"
|
||||
]
|
||||
],
|
||||
"_from": "cordova-common@>=2.2.0 <3.0.0",
|
||||
"_id": "cordova-common@2.2.1",
|
||||
"_inCache": true,
|
||||
"_location": "/cordova-common",
|
||||
"_nodeVersion": "8.9.3",
|
||||
"_npmOperationalInternal": {
|
||||
"host": "s3://npm-registry-packages",
|
||||
"tmp": "tmp/cordova-common-2.2.1.tgz_1513711030961_0.7797101123724133"
|
||||
},
|
||||
"_npmUser": {
|
||||
"name": "stevegill",
|
||||
"email": "stevengill97@gmail.com"
|
||||
},
|
||||
"_npmVersion": "4.6.1",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"raw": "cordova-common@^2.2.0",
|
||||
"scope": null,
|
||||
"escapedName": "cordova-common",
|
||||
"name": "cordova-common",
|
||||
"rawSpec": "^2.2.0",
|
||||
"spec": ">=2.2.0 <3.0.0",
|
||||
"type": "range"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/"
|
||||
],
|
||||
"_resolved": "file:cordova-dist/tools/cordova-common-2.2.1.tgz",
|
||||
"_shasum": "7009bc591729caa7285a588cfd6a7b54cd834f0c",
|
||||
"_shrinkwrap": null,
|
||||
"_spec": "cordova-common@^2.2.0",
|
||||
"_where": "/Users/steveng/repo/cordova/cordova-android",
|
||||
"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",
|
||||
"cordova-registry-mapper": "^1.1.8",
|
||||
"elementtree": "0.1.6",
|
||||
"glob": "^5.0.13",
|
||||
"minimatch": "^3.0.0",
|
||||
"osenv": "^0.1.3",
|
||||
"plist": "^1.2.0",
|
||||
"q": "^1.4.1",
|
||||
"semver": "^5.0.1",
|
||||
"shelljs": "^0.5.3",
|
||||
"underscore": "^1.8.3",
|
||||
"unorm": "^1.3.3"
|
||||
},
|
||||
"description": "Apache Cordova tools and platforms shared routines",
|
||||
"devDependencies": {
|
||||
"eslint": "^4.0.0",
|
||||
"eslint-config-semistandard": "^11.0.0",
|
||||
"eslint-config-standard": "^10.2.1",
|
||||
"eslint-plugin-import": "^2.3.0",
|
||||
"eslint-plugin-node": "^5.0.0",
|
||||
"eslint-plugin-promise": "^3.5.0",
|
||||
"eslint-plugin-standard": "^3.0.1",
|
||||
"istanbul": "^0.4.5",
|
||||
"jasmine": "^2.5.2",
|
||||
"promise-matchers": "^0.9.6",
|
||||
"rewire": "^2.5.1"
|
||||
},
|
||||
"directories": {},
|
||||
"dist": {
|
||||
"shasum": "7009bc591729caa7285a588cfd6a7b54cd834f0c",
|
||||
"tarball": "https://registry.npmjs.org/cordova-common/-/cordova-common-2.2.1.tgz"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
},
|
||||
"homepage": "https://github.com/apache/cordova-lib#readme",
|
||||
"license": "Apache-2.0",
|
||||
"main": "cordova-common.js",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "audreyso",
|
||||
"email": "audreyeso@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "apachebuilds",
|
||||
"email": "root@apache.org"
|
||||
},
|
||||
{
|
||||
"name": "filmaj",
|
||||
"email": "maj.fil@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "timbarham",
|
||||
"email": "npmjs@barhams.info"
|
||||
},
|
||||
{
|
||||
"name": "shazron",
|
||||
"email": "shazron@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "bowserj",
|
||||
"email": "bowserj@apache.org"
|
||||
},
|
||||
{
|
||||
"name": "purplecabbage",
|
||||
"email": "purplecabbage@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "stevegill",
|
||||
"email": "stevengill97@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "kotikov.vladimir",
|
||||
"email": "kotikov.vladimir@gmail.com"
|
||||
}
|
||||
],
|
||||
"name": "cordova-common",
|
||||
"optionalDependencies": {},
|
||||
"readme": "ERROR: No README data found!",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/apache/cordova-lib.git"
|
||||
},
|
||||
"scripts": {
|
||||
"cover": "istanbul cover --root src --print detail jasmine",
|
||||
"eslint": "eslint src && eslint spec",
|
||||
"jasmine": "jasmine JASMINE_CONFIG_PATH=spec/support/jasmine.json",
|
||||
"test": "npm run eslint && npm run jasmine"
|
||||
},
|
||||
"version": "2.2.1"
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
/**
|
||||
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;
|
||||
-424
@@ -1,424 +0,0 @@
|
||||
/**
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 ****/
|
||||
-257
@@ -1,257 +0,0 @@
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/* eslint no-control-regex: 0 */
|
||||
|
||||
var fs = require('fs');
|
||||
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') {
|
||||
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)) :
|
||||
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 = new RegExp('<string>[ \t\r\n]+?</string>', 'g');
|
||||
fs.writeFileSync(self.filepath, modules.plist.build(self.data).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;
|
||||
|
||||
if (file.indexOf('*') > -1) {
|
||||
// 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.indexOf('-Info.plist') > -1) {
|
||||
var plistName = getIOSProjectname(project_dir) + '-Info.plist';
|
||||
for (var i = 0; i < matches.length; i++) {
|
||||
if (matches[i].indexOf(plistName) > -1) {
|
||||
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)) {
|
||||
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.match(/res\/xml/)) {
|
||||
// Catch-all for all other stored XML configuration in legacy plugins
|
||||
var 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') {
|
||||
var iospath = module.exports.getIOSProjectname(project_dir);
|
||||
filepath = path.join(project_dir, iospath, '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 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;
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* 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;
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
/*
|
||||
* 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);
|
||||
};
|
||||
-615
@@ -1,615 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
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].indexOf('xmlns:') === 0 &&
|
||||
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 || '';
|
||||
}
|
||||
|
||||
ConfigParser.prototype = {
|
||||
getAttribute: function (attr) {
|
||||
return this.doc.getroot().attrib[attr];
|
||||
},
|
||||
|
||||
packageName: function (id) {
|
||||
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'));
|
||||
},
|
||||
getPreference: function (name, platform) {
|
||||
|
||||
var platformPreference = '';
|
||||
|
||||
if (platform) {
|
||||
platformPreference = this.getPlatformPreference(name, platform);
|
||||
}
|
||||
|
||||
return platformPreference || this.getGlobalPreference(name);
|
||||
|
||||
},
|
||||
/**
|
||||
* 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;
|
||||
|
||||
// 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) {
|
||||
var plugins = this.doc.findall('./plugin/[@name="' + id + '"]')
|
||||
.concat(this.doc.findall('./feature/param[@name="id"][@value="' + id + '"]/..'));
|
||||
var children = this.doc.getroot().getchildren();
|
||||
plugins.forEach(function (plugin) {
|
||||
var idx = children.indexOf(plugin);
|
||||
if (idx > -1) {
|
||||
children.splice(idx, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// 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) {
|
||||
var engines = this.doc.findall('./engine/[@name="' + name + '"]');
|
||||
for (var i = 0; i < engines.length; i++) {
|
||||
var children = this.doc.getroot().getchildren();
|
||||
var idx = children.indexOf(engines[i]);
|
||||
if (idx > -1) {
|
||||
children.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
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_tag = this.doc.find('./platform[@name="' + platform + '"]');
|
||||
var platform_edit_configs = platform_tag ? platform_tag.findall('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_tag = this.doc.find('./platform[@name="' + platform + '"]');
|
||||
var platform_config_files = platform_tag ? platform_tag.findall('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;
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
<!--
|
||||
#
|
||||
# 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-Lib
|
||||
|
||||
## ConfigParser
|
||||
|
||||
wraps a valid cordova config.xml file
|
||||
|
||||
### Usage
|
||||
|
||||
### Include the ConfigParser module in a projet
|
||||
|
||||
var ConfigParser = require('cordova-lib').configparser;
|
||||
|
||||
### Create a new ConfigParser
|
||||
|
||||
var config = new ConfigParser('path/to/config/xml/');
|
||||
|
||||
### Utility Functions
|
||||
|
||||
#### packageName(id)
|
||||
returns document root 'id' attribute value
|
||||
#### Usage
|
||||
|
||||
config.packageName: function(id)
|
||||
|
||||
/*
|
||||
* sets document root element 'id' attribute to @id
|
||||
*
|
||||
* @id - new id value
|
||||
*
|
||||
*/
|
||||
#### setPackageName(id)
|
||||
set document root 'id' attribute to
|
||||
function(id) {
|
||||
this.doc.getroot().attrib['id'] = id;
|
||||
},
|
||||
|
||||
###
|
||||
name: function() {
|
||||
return getNodeTextSafe(this.doc.find('name'));
|
||||
},
|
||||
setName: function(name) {
|
||||
var el = findOrCreate(this.doc, 'name');
|
||||
el.text = name;
|
||||
},
|
||||
|
||||
### read the description element
|
||||
|
||||
config.description()
|
||||
|
||||
var text = "New and improved description of App"
|
||||
setDescription(text)
|
||||
|
||||
### version management
|
||||
version()
|
||||
android_versionCode()
|
||||
ios_CFBundleVersion()
|
||||
setVersion()
|
||||
|
||||
### read author element
|
||||
|
||||
config.author();
|
||||
|
||||
### read preference
|
||||
|
||||
config.getPreference(name);
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
|
||||
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
|
||||
};
|
||||
-92
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
|
||||
/* eslint no-proto: 0 */
|
||||
|
||||
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;
|
||||
}
|
||||
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 (var key in CordovaError) {
|
||||
if (CordovaError.hasOwnProperty(key)) {
|
||||
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;
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
/**
|
||||
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;
|
||||
-220
@@ -1,220 +0,0 @@
|
||||
/*
|
||||
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 ansi = require('ansi');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var CordovaError = require('./CordovaError/CordovaError');
|
||||
var EOL = require('os').EOL;
|
||||
|
||||
var INSTANCE;
|
||||
|
||||
/**
|
||||
* @class CordovaLogger
|
||||
*
|
||||
* Implements logging facility that anybody could use. Should not be
|
||||
* instantiated directly, `CordovaLogger.get()` method should be used instead
|
||||
* to acquire logger instance
|
||||
*/
|
||||
function CordovaLogger () {
|
||||
this.levels = {};
|
||||
this.colors = {};
|
||||
this.stdout = process.stdout;
|
||||
this.stderr = process.stderr;
|
||||
|
||||
this.stdoutCursor = ansi(this.stdout);
|
||||
this.stderrCursor = ansi(this.stderr);
|
||||
|
||||
this.addLevel('verbose', 1000, 'grey');
|
||||
this.addLevel('normal', 2000);
|
||||
this.addLevel('warn', 2000, 'yellow');
|
||||
this.addLevel('info', 3000, 'blue');
|
||||
this.addLevel('error', 5000, 'red');
|
||||
this.addLevel('results', 10000);
|
||||
|
||||
this.setLevel('normal');
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method to create new or acquire existing instance.
|
||||
*
|
||||
* @return {CordovaLogger} Logger instance
|
||||
*/
|
||||
CordovaLogger.get = function () {
|
||||
return INSTANCE || (INSTANCE = new CordovaLogger());
|
||||
};
|
||||
|
||||
CordovaLogger.VERBOSE = 'verbose';
|
||||
CordovaLogger.NORMAL = 'normal';
|
||||
CordovaLogger.WARN = 'warn';
|
||||
CordovaLogger.INFO = 'info';
|
||||
CordovaLogger.ERROR = 'error';
|
||||
CordovaLogger.RESULTS = 'results';
|
||||
|
||||
/**
|
||||
* 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 {String} 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'
|
||||
* stdio
|
||||
*
|
||||
* @return {CordovaLogger} Current instance, to allow calls chaining.
|
||||
*/
|
||||
CordovaLogger.prototype.log = function (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 === '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 `debug(message)`, equal to logger.log('debug', message),
|
||||
* will be added to logger instance)
|
||||
*
|
||||
* @param {String} level A log level name. The levels with the following
|
||||
* names 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)
|
||||
*
|
||||
* @return {CordovaLogger} Current instance, to allow calls chaining.
|
||||
*/
|
||||
CordovaLogger.prototype.addLevel = function (level, severity, color) {
|
||||
|
||||
this.levels[level] = severity;
|
||||
|
||||
if (color) {
|
||||
this.colors[level] = color;
|
||||
}
|
||||
|
||||
// Define own method with corresponding name
|
||||
if (!this[level]) {
|
||||
this[level] = 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 {String} logLevel Level name. The level with this name should be
|
||||
* added to logger before.
|
||||
*
|
||||
* @return {CordovaLogger} Current instance, to allow calls chaining.
|
||||
*/
|
||||
CordovaLogger.prototype.setLevel = function (logLevel) {
|
||||
this.logLevel = this.levels[logLevel] ? logLevel : CordovaLogger.NORMAL;
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adjusts the current logger level according to the passed options.
|
||||
*
|
||||
* @param {Object|Array} opts An object or args array with options
|
||||
*
|
||||
* @return {CordovaLogger} Current instance, to allow calls chaining.
|
||||
*/
|
||||
CordovaLogger.prototype.adjustLevel = function (opts) {
|
||||
if (opts.verbose || (Array.isArray(opts) && opts.indexOf('--verbose') !== -1)) {
|
||||
this.setLevel('verbose');
|
||||
} else if (opts.silent || (Array.isArray(opts) && opts.indexOf('--silent') !== -1)) {
|
||||
this.setLevel('error');
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Attaches logger to EventEmitter instance provided.
|
||||
*
|
||||
* @param {EventEmitter} eventEmitter An EventEmitter instance to attach
|
||||
* logger to.
|
||||
*
|
||||
* @return {CordovaLogger} Current instance, to allow calls chaining.
|
||||
*/
|
||||
CordovaLogger.prototype.subscribe = function (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;
|
||||
};
|
||||
|
||||
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().indexOf('ERROR:') !== 0) {
|
||||
// Needed for backward compatibility with external tools
|
||||
message = 'Error: ' + message;
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
module.exports = CordovaLogger;
|
||||
-415
@@ -1,415 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
var path = require('path');
|
||||
var shell = require('shelljs');
|
||||
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) {
|
||||
// The target exists. But if the directory status doesn't match the source, delete it.
|
||||
if (targetStats.isDirectory() && !sourceStats.isDirectory()) {
|
||||
log('rmdir ' + targetPath + ' (source is a file)');
|
||||
shell.rm('-rf', targetFullPath);
|
||||
targetStats = null;
|
||||
updated = true;
|
||||
} else if (!targetStats.isDirectory() && sourceStats.isDirectory()) {
|
||||
log('delete ' + targetPath + ' (source is a directory)');
|
||||
shell.rm('-f', targetFullPath);
|
||||
targetStats = null;
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetStats) {
|
||||
if (sourceStats.isDirectory()) {
|
||||
// The target directory does not exist, so it should be created.
|
||||
log('mkdir ' + targetPath);
|
||||
shell.mkdir('-p', 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)'));
|
||||
shell.cp('-f', 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);
|
||||
shell.cp('-f', 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)');
|
||||
shell.cp('-f', sourceFullPath, targetFullPath);
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (targetStats) {
|
||||
// The target exists but the source is null, so the target should be deleted.
|
||||
if (targetStats.isDirectory()) {
|
||||
log('rmdir ' + targetPath + (copyAll ? '' : ' (no source)'));
|
||||
shell.rm('-rf', targetFullPath);
|
||||
} else {
|
||||
log('delete ' + targetPath + (copyAll ? '' : ' (no source)'));
|
||||
shell.rm('-f', 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)) {
|
||||
shell.mkdir('-p', 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 (message) { };
|
||||
|
||||
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 (message) { };
|
||||
|
||||
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 (message) { };
|
||||
|
||||
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
|
||||
};
|
||||
-277
@@ -1,277 +0,0 @@
|
||||
/*
|
||||
* 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');
|
||||
var path = require('path');
|
||||
var shelljs = require('shelljs');
|
||||
var mungeutil = require('./ConfigChanges/munge-util');
|
||||
var pluginMappernto = require('cordova-registry-mapper').newToOld;
|
||||
var pluginMapperotn = require('cordova-registry-mapper').oldToNew;
|
||||
|
||||
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 () {
|
||||
shelljs.mkdir('-p', path.dirname(this.filePath));
|
||||
fs.writeFileSync(this.filePath, JSON.stringify(this.root, null, 2), 'utf-8');
|
||||
};
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
var installedPlugins = this.root.installed_plugins;
|
||||
return installedPlugins[pluginId] ||
|
||||
installedPlugins[pluginMappernto[pluginId]] ||
|
||||
installedPlugins[pluginMapperotn[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) {
|
||||
var dependentPlugins = this.root.dependent_plugins;
|
||||
return dependentPlugins[pluginId] ||
|
||||
dependentPlugins[pluginMappernto[pluginId]] ||
|
||||
dependentPlugins[pluginMapperotn[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.indexOf(metadata.file) === -1;
|
||||
});
|
||||
|
||||
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.indexOf(installedModule.file) === -1);
|
||||
});
|
||||
|
||||
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 () {
|
||||
return [
|
||||
'cordova.define(\'cordova/plugin_list\', function(require, exports, module) {',
|
||||
'module.exports = ' + JSON.stringify(this.root.modules, null, 2) + ';',
|
||||
'module.exports.metadata = ',
|
||||
'// TOP OF METADATA',
|
||||
JSON.stringify(this.root.plugin_metadata, null, 2) + ';',
|
||||
'// BOTTOM OF METADATA',
|
||||
'});' // Close cordova.define.
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* @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) {
|
||||
var meta = this.generateMetadata();
|
||||
shelljs.mkdir('-p', path.dirname(destination));
|
||||
fs.writeFileSync(destination, meta, 'utf-8');
|
||||
|
||||
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]); /* eslint no-useless-escape: 0 */
|
||||
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;
|
||||
-439
@@ -1,439 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
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']
|
||||
};
|
||||
});
|
||||
return headerFiles;
|
||||
}
|
||||
|
||||
// <resource-file>
|
||||
// Example:
|
||||
// <resource-file src="FooPluginStrings.xml" target="res/values/FooPluginStrings.xml" device-target="win" arch="x86" versions=">=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;
|
||||
}
|
||||
|
||||
// <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);
|
||||
};
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
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;
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
/*
|
||||
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');
|
||||
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.apply(actions, [installer, actionArgs, uninstaller, actionArgs]); /* eslint no-useless-call: 0 */
|
||||
} else /* op === PluginManager.UNINSTALL */{
|
||||
action = actions.createAction.apply(actions, [uninstaller, actionArgs, installer, actionArgs]); /* eslint no-useless-call: 0 */
|
||||
}
|
||||
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);
|
||||
};
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
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 EventEmitter = require('events').EventEmitter;
|
||||
|
||||
var INSTANCE = new EventEmitter();
|
||||
INSTANCE.setMaxListeners(20);
|
||||
var EVENTS_RECEIVER;
|
||||
|
||||
module.exports = INSTANCE;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
module.exports.forwardEventsTo = function (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;
|
||||
}
|
||||
};
|
||||
|
||||
var emit = INSTANCE.emit;
|
||||
|
||||
/**
|
||||
* This method replaces original 'emit' method to allow events forwarding.
|
||||
*
|
||||
* @return {eventEmitter} Current instance to allow calls chaining, as
|
||||
* original 'emit' does
|
||||
*/
|
||||
module.exports.emit = function () {
|
||||
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
|
||||
if (EVENTS_RECEIVER) {
|
||||
EVENTS_RECEIVER.emit.apply(EVENTS_RECEIVER, args);
|
||||
}
|
||||
|
||||
return emit.apply(this, args);
|
||||
};
|
||||
-189
@@ -1,189 +0,0 @@
|
||||
/**
|
||||
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 child_process = require('child_process');
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var _ = require('underscore');
|
||||
var Q = require('q');
|
||||
var shell = require('shelljs');
|
||||
var events = require('./events');
|
||||
var iswin32 = process.platform === 'win32';
|
||||
|
||||
// On Windows, spawn() for batch files requires absolute path & having the extension.
|
||||
function resolveWindowsExe (cmd) {
|
||||
var winExtensions = ['.exe', '.bat', '.cmd', '.js', '.vbs'];
|
||||
function isValidExe (c) {
|
||||
return winExtensions.indexOf(path.extname(c)) !== -1 && fs.existsSync(c);
|
||||
}
|
||||
if (isValidExe(cmd)) {
|
||||
return cmd;
|
||||
}
|
||||
cmd = shell.which(cmd) || cmd;
|
||||
if (!isValidExe(cmd)) {
|
||||
winExtensions.some(function (ext) {
|
||||
if (fs.existsSync(cmd + ext)) {
|
||||
cmd = cmd + ext;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
return cmd;
|
||||
}
|
||||
|
||||
function maybeQuote (a) {
|
||||
if (/^[^"].*[ &].*[^"]/.test(a)) return '"' + a + '"';
|
||||
return a;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (iswin32) {
|
||||
cmd = resolveWindowsExe(cmd);
|
||||
// If we couldn't find the file, likely we'll end up failing,
|
||||
// but for things like "del", cmd will do the trick.
|
||||
if (path.extname(cmd) !== '.exe') {
|
||||
var cmdArgs = '"' + [cmd].concat(args).map(maybeQuote).join(' ') + '"';
|
||||
// We need to use /s to ensure that spaces are parsed properly with cmd spawned content
|
||||
args = [['/s', '/c', cmdArgs].join(' ')];
|
||||
cmd = 'cmd';
|
||||
spawnOpts.windowsVerbatimArguments = true;
|
||||
} else if (!fs.existsSync(cmd)) {
|
||||
// We need to use /s to ensure that spaces are parsed properly with cmd spawned content
|
||||
args = ['/s', '/c', cmd].concat(args).map(maybeQuote);
|
||||
}
|
||||
}
|
||||
|
||||
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: ' + maybeQuote(cmd) + ' ' + args.map(maybeQuote).join(' '));
|
||||
|
||||
var child = child_process.spawn(cmd, args, spawnOpts);
|
||||
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) {
|
||||
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);
|
||||
};
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
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;
|
||||
}
|
||||
});
|
||||
};
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
/* eslint no-useless-escape: 0 */
|
||||
|
||||
// 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, '\\$&');
|
||||
}
|
||||
-365
@@ -1,365 +0,0 @@
|
||||
/**
|
||||
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');
|
||||
var path = require('path');
|
||||
var _ = require('underscore');
|
||||
var et = require('elementtree');
|
||||
|
||||
/* eslint-disable no-useless-escape */
|
||||
var ROOT = /^\/([^\/]*)/;
|
||||
var ABSOLUTE = /^\/([^\/]*)\/(.*)/;
|
||||
/* eslint-enable no-useless-escape */
|
||||
|
||||
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 = null;
|
||||
if ((matchingKid = findChild(node, parent)) !== null) {
|
||||
// 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 = fs.readFileSync(filename, 'utf-8');
|
||||
if (contents) {
|
||||
// Windows is the BOM. Skip the Byte Order Mark.
|
||||
contents = contents.substring(contents.indexOf('<'));
|
||||
}
|
||||
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) {
|
||||
var matchingKids = parent.findall(node.tag);
|
||||
var i;
|
||||
var j;
|
||||
|
||||
for (i = 0, j = matchingKids.length; i < j; i++) {
|
||||
if (module.exports.equalNodes(node, matchingKids[i])) {
|
||||
return matchingKids[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function uniqueChild (node, parent) {
|
||||
var matchingKids = parent.findall(node.tag);
|
||||
var i = 0;
|
||||
|
||||
if (matchingKids.length === 0) {
|
||||
return true;
|
||||
} else {
|
||||
for (i; i < matchingKids.length; i++) {
|
||||
if (module.exports.equalNodes(node, matchingKids[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 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.indexOf(src.tag) !== -1) 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.indexOf(srcTag) !== -1) return;
|
||||
|
||||
if (SINGLETONS.indexOf(srcTag) !== -1) {
|
||||
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, index) {
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user