cordova-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From agri...@apache.org
Subject cordova-lib git commit: CB-8358 Add `--link` for `platform add` and `platform update`
Date Mon, 26 Jan 2015 15:18:26 GMT
Repository: cordova-lib
Updated Branches:
  refs/heads/master 8de97feba -> c8df520c2


CB-8358 Add `--link` for `platform add` and `platform update`

This refactors platform update and add to use the same helper method,
making the two code paths much more coherent and supporting the same
<platform-spec> arguments.

Commit also fixes "platform add /path/platform for older, non-package.json platforms.


Project: http://git-wip-us.apache.org/repos/asf/cordova-lib/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-lib/commit/c8df520c
Tree: http://git-wip-us.apache.org/repos/asf/cordova-lib/tree/c8df520c
Diff: http://git-wip-us.apache.org/repos/asf/cordova-lib/diff/c8df520c

Branch: refs/heads/master
Commit: c8df520c25ceb7a8990734332b2f71b5754c4d98
Parents: 8de97fe
Author: Andrew Grieve <agrieve@chromium.org>
Authored: Mon Jan 26 10:12:19 2015 -0500
Committer: Andrew Grieve <agrieve@chromium.org>
Committed: Mon Jan 26 10:16:41 2015 -0500

----------------------------------------------------------------------
 cordova-lib/spec-cordova/platform.spec.js | 574 +------------------------
 cordova-lib/src/cordova/platform.js       | 288 ++++++-------
 2 files changed, 142 insertions(+), 720 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/c8df520c/cordova-lib/spec-cordova/platform.spec.js
----------------------------------------------------------------------
diff --git a/cordova-lib/spec-cordova/platform.spec.js b/cordova-lib/spec-cordova/platform.spec.js
index c754f1d..16f70b3 100644
--- a/cordova-lib/spec-cordova/platform.spec.js
+++ b/cordova-lib/spec-cordova/platform.spec.js
@@ -36,8 +36,6 @@ var projectRoot = 'C:\\Projects\\cordova-projects\\move-tracker';
 var libDir = "C:\\Projects\\cordova-projects\\cordova-android\\";
 
 var cfg;
-var opts;
-var hooksRunnerMock;
 var hostSupportsOriginal = platform.__get__('hostSupports');
 var ConfigParserOriginal = platform.__get__('ConfigParser');
 var configOriginal = platform.__get__('config');
@@ -141,90 +139,16 @@ describe('platform end-to-end', function () {
 });
 
 describe('add function', function () {
-    
+    var opts;
+    var hooksRunnerMock;
+
     beforeEach(function(){
-	
         opts = {};
-	
         hooksRunnerMock = {
             fire: function () {
                 return Q();
             }
         };
-
-        platform.__set__('hostSupports', function (platform) {
-            return true;
-        });
-
-        platform.__set__('ConfigParser', function (xml) {
-            cfg = 
-		{
-		    getEngines: function() {
-		        return [
-                    {
-                        name: 'cordova-android',
-                        value: '3.2.0'
-                    },
-                    {
-                        name: 'cordova-wp8',
-                        value: '2.1.0'
-                    }
-		        ];
-		    }		
-		};
-            return cfg;
-        });
-	
-        platform.__set__('config', {
-            read: function (projectRoot) {
-                return {};
-            }
-        });
-
-        platform.__set__('fs', {
-            existsSync: function (path) {
-                return true;
-            }
-        });
-
-        // These are the recognized/legal platforms
-        platform.__set__('platforms', {
-            'android': {
-                'parser': './metadata/android_parser',
-                'url': 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git',
-                'version': '3.6.4'
-            },
-            'ios': {
-                'hostos': ['darwin'],
-                'parser': './metadata/ios_parser',
-                'url': 'https://git-wip-us.apache.org/repos/asf?p=cordova-ios.git',
-                'version': '3.7.0'
-            },
-            'wp8': {
-                'hostos': ['win32'],
-                'parser': './metadata/wp8_parser',
-                'url': 'https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git',
-                'version': '3.7.0',
-                'altplatform': 'wp'
-            },
-            'amazon-fireos': {
-                'name': 'cordova-amazon-fireos',
-                'version': '3.7.0-dev',
-                'description': 'cordova-amazon-fireos release',
-                'main': 'bin/create'
-            }
-        });
-
-    });
-
-    afterEach(function(){
-	
-        platform.__set__('hostSupports', hostSupportsOriginal);
-        platform.__set__('ConfigParser', ConfigParserOriginal);
-        platform.__set__('config', configOriginal);
-        platform.__set__('fs', fsOriginal);
-        platform.__set__('platforms', platformsOriginal);
-        platform.__set__('promiseutil', promiseUtilOriginal);
     });
 
     it('throws if the target list is empty', function (done) {
@@ -250,497 +174,5 @@ describe('add function', function () {
             done();
         });
     });
-
-    it('creates the "platforms" directory if it does not exist', function (done) {
-
-        var targets = ['C:\\Projects\\cordova-projects\\cordova-android'];
-        var wasPlatformDirectoryCreated = false;
-
-        // Make it so that 'platforms' directory doesn't exist
-        platform.__set__('fs', {
-            existsSync: function () {
-                return false;
-            }
-        });
-
-        // Do nothing with the targets (only in this test)
-        platform.__set__('promiseutil', {
-            Q_chainmap: function () {
-                return Q();
-            }
-        });
-
-        platform.__set__('shell', {
-            mkdir: function () {
-                wasPlatformDirectoryCreated = true;
-            }
-        });
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(wasPlatformDirectoryCreated).toBeTruthy();
-            done();
-        });
-    });
-
-    it('fires events "before_platform_add" and "after_platform_add" in the right order and
at the right time', function (done) {
-
-        var targets = ['C:\\Projects\\cordova-projects\\cordova-android'];
-
-        // events 
-        var before_platform_add_fired = false;
-        var after_platform_add_fired = false;
-        var platforms_added = false;
-
-        var hooksRunnerMock = {
-            fire: function (event, opts) {
-                switch (event) {
-                    case 'before_platform_add':
-                        before_platform_add_fired = true;
-                        expect(after_platform_add_fired).toBeFalsy();
-                        expect(platforms_added).toBeFalsy();
-                        break;
-                    case 'after_platform_add':
-                        after_platform_add_fired = true;
-                        expect(before_platform_add_fired).toBeTruthy();
-                        expect(platforms_added).toBeTruthy();
-                        break;
-                    default:
-                        // induce test failure : test this !
-                        // fail('invalid event fired');
-                        expect(1).toBe(2);
-                }
-                return Q();
-            }
-        };
-        platform.__set__('promiseutil', {
-            Q_chainmap: function (targets, func) {
-                platforms_added = true;
-                expect(before_platform_add_fired).toBeTruthy();
-                expect(after_platform_add_fired).toBeFalsy();
-                return Q();
-            }
-        });
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(before_platform_add_fired).toBeTruthy();
-            expect(after_platform_add_fired).toBeTruthy();
-            expect(platforms_added).toBeTruthy();
-            done();
-        });
-    });
-
-    it('runs the create script in the target directory when passed a directory as target',
function (done) {
-
-        var targets = ['C:\\Projects\\cordova-projects\\cordova-android'];
-
-        var getPlatformDetailsFromDirMock = jasmine.createSpy();
-        getPlatformDetailsFromDirMock.andReturn(Q({
-            platform: 'android',
-            libDir: targets[0]
-        }));
-        platform.__set__('getPlatformDetailsFromDir', getPlatformDetailsFromDirMock);
-
-        var downloadPlatformMock = jasmine.createSpy();
-        platform.__set__('downloadPlatform', downloadPlatformMock);
-
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock);
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(getPlatformDetailsFromDirMock).toHaveBeenCalledWith(targets[0]);
-            expect(downloadPlatformMock).not.toHaveBeenCalled();
-            expect(call_into_create_mock).toHaveBeenCalledWith('android', projectRoot, cfg,
targets[0], null, opts);
-            done();
-        });
-    });
-
-    it('fails if there is an error while getting the platform details', function (done) {
-
-        var targets = ['C:\\Projects\\cordova-projects\\cordova-android'];
-
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock);
-
-        platform.__set__('getPlatformDetailsFromDir', function(){ // put this in globals
section ? and reset
-            var msg = 'The provided path does not seem to contain a Cordova platform: ' +
targets[0];
-            return Q.reject(new Error(msg));
-        });
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).fail(function (error) {
-            var packagePath = path.join(targets[0], 'package');
-            expect(error.message).toBe('The provided path does not seem to contain a ' +
'Cordova platform: ' + targets[0]);
-            expect(call_into_create_mock).not.toHaveBeenCalled();
-            done();
-        });
-    });
-
-    it('downloads and uses the version of platform retrieved from config.xml when the target
is specified by name with no version', function (done) {
-
-        var targets = ['android'];
-        var versionInConfigXML = '6.2.1';
-
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock);
-
-        var getVersionFromConfigFileMock = jasmine.createSpy().andReturn(versionInConfigXML);

-        platform.__set__('getVersionFromConfigFile', getVersionFromConfigFileMock);
-
-        var downloadPlatformMock = jasmine.createSpy().andReturn(Q({
-            platform: 'android',
-            libDir: libDir
-        }));
-        platform.__set__('downloadPlatform', downloadPlatformMock);
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(getVersionFromConfigFileMock).toHaveBeenCalledWith('android', cfg);
-            expect(downloadPlatformMock).toHaveBeenCalledWith(projectRoot, 'android@' + versionInConfigXML,
opts);
-            expect(call_into_create_mock).toHaveBeenCalledWith('android', projectRoot, cfg,
libDir, null, opts);
-            done();
-        });
-    });
-    
-    it('fails if there is an error while downloading the platform', function(done) {
-
-        var targets = ['android'];
-        var errorMessage = 'Unable to fetch platform andythoroid : Cordova library \'andythoroid\'
not recognized.';
-        platform.__set__('downloadPlatform', function(){
-            throw new Error(errorMessage);
-        });
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).fail(function(error){
-            expect(error.message).toBe(errorMessage);
-            done();
-        });
-    });
-
-    it('allows targets of the form "platform@version" where "version" is a url', function
(done) {
-
-        var targets = ['wp8@https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git;a=snapshot;h=3.7.0;sf=tgz'];
-
-        var call_into_create_mock = jasmine.createSpy(); 
-        platform.__set__('call_into_create', call_into_create_mock);
-
-        var wasDownloadPlatformCalled = false;
-        platform.__set__('downloadPlatform', function(){
-            wasDownloadPlatformCalled = true;
-            return Q({
-                platform: 'wp8',
-                libDir: libDir
-            });
-        });
-	
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(wasDownloadPlatformCalled).toBeTruthy();
-            expect(call_into_create_mock).toHaveBeenCalledWith('wp8', projectRoot, cfg, libDir,
null, opts);
-            done();
-        });
-    });
-
-    it('downloads and uses the pinned CLI version if platform has no version and config.xml
has no corresponding engine', function(done) {
-	
-        var targets = ['android'];
-	
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock);
-
-        platform.__set__('getVersionFromConfigFile', function(){
-            return null;
-        });
-
-        var downloadPlatformMock = jasmine.createSpy().andReturn(Q({
-            platform: 'android',
-            libDir: libDir
-        }));
-        platform.__set__('downloadPlatform', downloadPlatformMock);
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(call_into_create_mock).toHaveBeenCalledWith('android', projectRoot, cfg,
libDir, null, opts);
-            expect(downloadPlatformMock).toHaveBeenCalledWith(projectRoot, 'android', opts);
-            done();
-        });
-    });
-
-    it('uses the directory in config.xml when the target has no version', function(done)
{
-
-        // uses the directory. make changes to other tests
-        var targets = ['android'];
-
-        platform.__set__('getVersionFromConfigFile', function(){
-            return "C:/path/to/android/platform";
-        });
-
-        var downloadPlatformMock = jasmine.createSpy();
-        platform.__set__('downloadPlatform', downloadPlatformMock);
-
-        var getPlatformDetailsFromDirMock = jasmine.createSpy().andReturn(Q({
-            platform: 'android',
-            libDir: 'C:/path/to/android/platform'
-        }));
-        platform.__set__('getPlatformDetailsFromDir', getPlatformDetailsFromDirMock);
-
-        var isDirectoryMock = jasmine.createSpy().andReturn(true);
-        platform.__set__('isDirectory', isDirectoryMock);
-
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock);
-	
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function(){
-            expect(downloadPlatformMock).not.toHaveBeenCalled();
-            expect(getPlatformDetailsFromDirMock).toHaveBeenCalledWith('C:/path/to/android/platform');
-            expect(call_into_create_mock).toHaveBeenCalledWith('android', projectRoot, cfg,
'C:/path/to/android/platform', null, opts);
-            done();
-        });
-	
-    });
-
-    it('uses the version from config.xml when no version is specified', function(done) {
-		
-        var targets = ['ios']; // no version part, as opposed to 'android@1.4.0'
-        var version = '3.6.2';
-	
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock); 
-	
-        platform.__set__('getVersionFromConfigFile', function () {
-            return version;
-        });
-		
-        var downloadPlatformMock = jasmine.createSpy().andReturn(Q({
-            platform: 'ios',
-            libDir: libDir
-        }));
-        platform.__set__('downloadPlatform', downloadPlatformMock);
-
-        var isDirectoryMock = jasmine.createSpy().andReturn(false);
-        platform.__set__('isDirectory', isDirectoryMock);
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(downloadPlatformMock).toHaveBeenCalledWith(projectRoot, (targets[0] +
'@' + version), opts);
-            expect(call_into_create_mock).toHaveBeenCalledWith('ios', projectRoot, cfg, libDir,
null, opts);
-            done();
-        });
-    });
-
-    it('uses the version of platform pinned in the CLI when the target is specified by name
with no version and config.xml contains no corresponding engine', function(done) {
-		
-        var targets = ['ios']; // no version part, as opposed to 'android@1.4.0'
-        var version = null;
-	
-        var call_into_create_mock = jasmine.createSpy();
-        platform.__set__('call_into_create', call_into_create_mock); 
-	
-        platform.__set__('getVersionFromConfigFile', function () {
-            return version; // null
-        });
-		
-        var downloadPlatformMock = jasmine.createSpy().andReturn(Q({
-            platform: 'ios',
-            libDir: libDir
-        }));
-        platform.__set__('downloadPlatform', downloadPlatformMock);
-
-        platform.add(hooksRunnerMock, projectRoot, targets, opts).then(function () {
-            expect(downloadPlatformMock).toHaveBeenCalledWith(projectRoot, targets[0], opts);
-            expect(call_into_create_mock).toHaveBeenCalledWith('ios', projectRoot, cfg, libDir,
null, opts);
-            done();
-        });
-    });
-});
-
-describe('downloadPlatform function', function(){
-    
-    var downloadPlatform = platform.__get__('downloadPlatform'); // function under test
- 
-    it('throws if lazy_loading fails', function (done) {
-
-        var target = 'android';
-
-        // Error out during 'lazy load'
-        var errorMessage = 'Cordova library "' + target + '" not recognized.';
-        platform.__set__('lazy_load', {
-            based_on_config: function (projectRoot, t, opts) {
-                return Q.reject(new Error(errorMessage));
-            }
-        });
-
-        downloadPlatform(projectRoot, target, opts).fail(function (error) {
-            expect(error.message).toBe('Unable to fetch platform ' + target + ': ' + 'Error:
' + errorMessage);
-            done();
-        });
-    });
-    
-    it('allows targets of the form "platform@version" where "version" is a url', function
(done) {
-
-        var target = 'wp8@https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git;a=snapshot;h=3.7.0;sf=tgz';
-
-        var based_on_config_called = false;
-        platform.__set__('lazy_load', {
-            based_on_config: function (projectRoot, t, opts) {
-                based_on_config_called = true;
-                return Q(libDir);
-            }
-        });
-
-        downloadPlatform(projectRoot, target, opts).then(function (platformDetails) {
-            expect(based_on_config_called).toBeTruthy();
-            expect(platformDetails.platform).toBe('wp8');
-	    expect(platformDetails.libDir).toBe(libDir);
-            done();
-        });
-    });
-
-    it('returns name and libDir of downloaded platform', function (done) {
-	
-        var target = 'wp8@3.1.0';
-
-        var based_on_config_called = false;
-        platform.__set__('lazy_load', {
-            based_on_config: function (projectRoot, t, opts) {
-                based_on_config_called = true;
-                return Q(libDir);
-            }
-        });
-
-        downloadPlatform(projectRoot, target, opts).then(function (platformDetails) {
-            expect(based_on_config_called).toBeTruthy();
-            expect(platformDetails.platform).toBe('wp8');
-	    expect(platformDetails.libDir).toBe(libDir);
-            done();
-        });
-    });
 });
 
-describe('getPlatformDetailsFromDir function', function(){
-
-    var dir = 'C:\\Projects\\cordova-projects\\cordova-android';
-    var getPackageJsonContentOriginal = platform.__get__('getPackageJsonContent');
-    var resolvePathOriginal = platform.__get__('resolvePath');
-    var getPlatformDetailsFromDir = platform.__get__('getPlatformDetailsFromDir'); // function
under test
-
-    beforeEach(function() {
-	platform.__set__('getPackageJsonContent', function (p) {
-            return p + '\\package';
-        });
-	platform.__set__('resolvePath', function(p){
-	    return p;
-	});
-    });
-
-    afterEach(function() {
-	platform.__set__('getPackageJsonContent', getPackageJsonContentOriginal);
-	platform.__set__('resolvePath', resolvePathOriginal);
-    });
-    
-    it('returns the appropriate platform details', function(done){
-
-        // Mock out package.json content
-        platform.__set__('getPackageJsonContent', function (p) {
-            return {
-                'name': 'cordova-android',
-                'version': '3.7.0-dev',
-                'description': 'cordova-android release',
-                'main': 'bin/create'
-            };
-        });
-
-        getPlatformDetailsFromDir(dir).then(function (platformDetails) {
-	    expect(platformDetails.platform).toBe('android');
-	    expect(platformDetails.libDir).toBe(dir);
-            done();
-        });
-    });
-
-    it('throws if the directory supplied does not contain a package.json file', function
(done) {
-
-        platform.__set__('getPackageJsonContent', function (p) {
-            var pPath = path.join(p, 'package');
-            var msg = "Cannot find module '" + pPath + "'";
-            var err = new Error(msg);
-            err.code = 'MODULE_NOT_FOUND';
-            throw err;
-        });
-
-        getPlatformDetailsFromDir(dir).fail(function (error) {
-            var packagePath = path.join(dir, 'package');
-            expect(error.message).toBe('The provided path does not seem to contain a Cordova
platform: ' + dir +
-				       '\n' + 'Cannot find module ' + "'" + packagePath + "'");
-            done();
-        });
-    });
-
-    it('replaces "amazon" by "amazon-fireos" if package.json returns "amazon"', function
(done) {
-
-        var dir = 'C:\\Projects\\cordova-projects\\cordova-amazon-fireos';
-
-        platform.__set__('getPackageJsonContent', function (p) {
-            return {
-                'name': 'cordova-amazon', // use 'cordova-amazon' instead of 'cordova-amazon-fireos'
-                'version': '3.7.0-dev',
-                'description': 'cordova-amazon-fireos release',
-                'main': 'bin/create'
-            };
-        });
-
-        getPlatformDetailsFromDir(dir).then(function (platformDetails) {
-	    expect(platformDetails.libDir).toBe(dir);
-	    expect(platformDetails.platform).toBe('amazon-fireos');
-            done();
-        });
-    });
-
-    it('throws if package.json file has no name property', function (done) {
-	
-        platform.__set__('getPackageJsonContent', function (p) {
-            return {
-		//name: 'cordova-android' --> No name
-	    };
-        });
-
-        getPlatformDetailsFromDir(dir).fail(function (error) {
-            var packagePath = path.join(dir, 'package');
-            expect(error.message).toBe('The provided path does not seem to contain a ' +
'Cordova platform: ' + dir);
-            done();
-        });
-    });
-
-    it('throws if package.json file returns null', function (done) {
-	
-        platform.__set__('getPackageJsonContent', function (p) {
-            return null;
-        });
-
-        getPlatformDetailsFromDir(dir).fail(function (error) {
-            var packagePath = path.join(dir, 'package');
-            expect(error.message).toBe('The provided path does not seem to contain a ' +
'Cordova platform: ' + dir);
-            done();
-        });
-    });
-
-    it('throws if the name in package.json file is not a recognized platform', function (done)
{
-
-        // These are the only 'recognized' platforms
-        platform.__set__('platforms', {
-            "ios": {
-                "hostos": ["darwin"],
-                "parser": "./metadata/ios_parser",
-                "url": "https://git-wip-us.apache.org/repos/asf?p=cordova-ios.git",
-                "version": "3.7.0"
-            }
-        });
-
-        platform.__set__('getPackageJsonContent', function () {
-            return {
-                'name': 'cordova-android',
-                'version': '3.7.0-dev',
-                'description': 'cordova-android release',
-                'main': 'bin/create'
-            };
-        });
-
-        getPlatformDetailsFromDir(dir).fail(function (error) {
-            var packagePath = path.join(dir, 'package');
-            expect(error.message).toBe('The provided path does not seem to contain a ' +
'Cordova platform: ' + dir);
-            done();
-        });
-    });
-});

http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/c8df520c/cordova-lib/src/cordova/platform.js
----------------------------------------------------------------------
diff --git a/cordova-lib/src/cordova/platform.js b/cordova-lib/src/cordova/platform.js
index 8999fcf..afe21dd 100644
--- a/cordova-lib/src/cordova/platform.js
+++ b/cordova-lib/src/cordova/platform.js
@@ -42,10 +42,18 @@ for (var p in platforms) {
     module.exports[p] = platforms[p];
 }
 
+function update(hooksRunner, projectRoot, targets, opts) {
+    return addHelper('update', hooksRunner, projectRoot, targets, opts);
+}
+
 function add(hooksRunner, projectRoot, targets, opts) {
+    return addHelper('add', hooksRunner, projectRoot, targets, opts);
+}
+
+function addHelper(cmd, hooksRunner, projectRoot, targets, opts) {
     var msg;
     if ( !targets || !targets.length ) {
-        msg = 'No platform specified. Please specify a platform to add. ' +
+        msg = 'No platform specified. Please specify a platform to ' + cmd + '. ' +
               'See `' + cordova_util.binname + ' platform list`.';
         return Q.reject(new CordovaError(msg));
     }
@@ -61,20 +69,17 @@ function add(hooksRunner, projectRoot, targets, opts) {
     var xml = cordova_util.projectConfig(projectRoot);
     var cfg = new ConfigParser(xml);
     var config_json = config.read(projectRoot);
-    var platformsDir = path.join(projectRoot, 'platforms');
     opts = opts || {};
     opts.searchpath = opts.searchpath || config_json.plugin_search_path;
 
     // The "platforms" dir is safe to delete, it's almost equivalent to
     // cordova platform rm <list of all platforms>
-    if ( !fs.existsSync(platformsDir)) {
-        shell.mkdir('-p', platformsDir);
-    }
+    shell.mkdir('-p', path.join(projectRoot, 'platforms'));
 
-    return hooksRunner.fire('before_platform_add', opts)
+    return hooksRunner.fire('before_platform_' + cmd, opts)
     .then(function() {
         return promiseutil.Q_chainmap(targets, function(target) {
-            // For each platform, download it and call its "create" script.
+            // For each platform, download it and call its helper script.
             var parts = target.split('@');
             var platform = parts[0];
             var version = parts[1];
@@ -87,17 +92,64 @@ function add(hooksRunner, projectRoot, targets, opts) {
                         events.emit('verbose', 'No version supplied. Retrieving version from
config.xml...');
                     }
                     version = version || getVersionFromConfigFile(platform, cfg);
-                    var tgt = version ? (platform + '@' + version) : platform;
-                    return isDirectory(version) ? getPlatformDetailsFromDir(version) : downloadPlatform(projectRoot,
tgt, opts);
+                    return isDirectory(version) ? getPlatformDetailsFromDir(version, platform)
: downloadPlatform(projectRoot, platform, version, opts);
                 }
             }).then(function(platDetails) {
-                var template = config_json && config_json.lib && config_json.lib[platform]
&& config_json.lib[platform].template || null;
-                return call_into_create(platDetails.platform, projectRoot, cfg, platDetails.libDir,
template, opts);
+                platform = platDetails.platform;
+                version = platDetails.version;
+                var platformPath = path.join(projectRoot, 'platforms', platform);
+                var platformAlreadyAdded = fs.existsSync(platformPath);
+
+                return Q().then(function() {
+                    if (cmd == 'add') {
+                        if (platformAlreadyAdded) {
+                            throw new CordovaError('Platform ' + platform + ' already added.');
+                        }
+                        var template_dir = config_json && config_json.lib &&
config_json.lib[platform] && config_json.lib[platform].template || null;
+                        events.emit('log', 'Adding ' + platform + ' project...');
+
+                        return getCreateArgs(platDetails, projectRoot, cfg, template_dir,
opts);
+                    } else if (cmd == 'update') {
+                        if (!platformAlreadyAdded) {
+                            throw new CordovaError('Platform "' + platform + '" is not yet
added. See `' +
+                                cordova_util.binname + ' platform list`.');
+                        }
+                        events.emit('log', 'Updating ' + platform + ' project...');
+
+                        // CB-6976 Windows Universal Apps. Special case to upgrade from windows8
to windows platform
+                        if (platform == 'windows8' && !fs.existsSync(path.join(projectRoot,
'platforms', 'windows'))) {
+                            var platformPathWindows = path.join(projectRoot, 'platforms',
'windows');
+                            fs.renameSync(platformPath, platformPathWindows);
+                            platform = 'windows';
+                            platformPath = platformPathWindows;
+                        }
+                        // Call the platform's update script.
+                        var args = [platformPath];
+                        if (opts.link) {
+                            args.push('--link');
+                        }
+                        return args;
+                    }
+                }).then(function(args) {
+                    var bin = path.join(platDetails.libDir, 'bin', cmd == 'add' ? 'create'
: 'update');
+                    var copts = { stdio: 'inherit' };
+                    if ('spawnoutput' in opts) {
+                        copts = { stdio: opts.spawnoutput };
+                    }
+                    return superspawn.spawn(bin, args, copts);
+                }).then(function() {
+                    copy_cordova_js(projectRoot, platform);
+                }).then(function() {
+                    if (cmd == 'add') {
+                        return installPluginsForNewPlatform(platform, projectRoot, cfg, opts);
+                    }
+                }).then(function() {
+                    return hooksRunner.fire('after_platform_' + cmd, opts);
+                }).then(function() {
+                    return require('./cordova').raw.prepare(platform);
+                });
             });
         });
-    })
-    .then(function() {
-        return hooksRunner.fire('after_platform_add', opts);
     });
 }
 
@@ -110,14 +162,12 @@ function isDirectory(dir) {
 }
 
 // Returns a Promise
-function downloadPlatform(projectRoot, target, opts) {
+function downloadPlatform(projectRoot, platform, version, opts) {
+    var target = version ? (platform + '@' + version) : platform;
     // Using lazy_load for a platform specified by name
     return lazy_load.based_on_config(projectRoot, target, opts)
     .then(function (libDir) {
-        return {
-            platform: target.split('@')[0],
-            libDir: libDir
-        };
+        return getPlatformDetailsFromDir(libDir, platform);
     }).fail(function (err) {
         throw new CordovaError('Unable to fetch platform ' + target + ': ' + err);
     });
@@ -131,37 +181,45 @@ function resolvePath(pPath){
     return path.resolve(pPath);
 }
 
+function platformFromName(name) {
+    var platMatch = /^cordova-([a-z0-9]+)$/.exec(name);
+    var ret = platMatch && platMatch[1];
+    if (ret == 'amazon') {
+        ret = 'amazon-fireos';
+    }
+    return ret;
+}
+
 // Returns a Promise
 // Gets platform details from a directory
-function getPlatformDetailsFromDir(dir){
-    var pkg;
-    var pPath = resolvePath(dir);
+function getPlatformDetailsFromDir(dir, platformIfKnown){
+    var libDir = resolvePath(dir);
+    var platform;
+    var version;
 
-    // Prep the message in advance, we might need it in several places.
-    var msg = 'The provided path does not seem to contain a ' +
-        'Cordova platform: ' + dir;
     try {
-        pkg = getPackageJsonContent(pPath);
+        var pkg = getPackageJsonContent(libDir);
+        platform = platformFromName(pkg.name);
+        version = pkg.version;
     } catch(e) {
-	return Q.reject(new CordovaError(msg + '\n' + e.message));
-    }
-    if ( !pkg || !pkg.name ) {
-	return Q.reject(new CordovaError(msg));
-    }
-    // Package names for Cordova platforms look like "cordova-ios".
-    var nameParts = pkg.name.split('-');
-    var name = nameParts[1];
-    if (name == 'amazon') {
-        name = 'amazon-fireos';
+        // Older platforms didn't have package.json.
+        platform = platformIfKnown || platformFromName(path.basename(dir));
+        var verFile = fs.existsSync(path.join(libDir, 'VERSION')) ? path.join(libDir, 'VERSION')
:
+                      fs.existsSync(path.join(libDir, 'CordovaLib', 'VERSION')) ? path.join(libDir,
'CordovaLib', 'VERSION') : null;
+        if (verFile) {
+            version = fs.readFileSync(verFile, 'UTF-8').trim();
+        }
     }
-    if (!platforms[name]) {
-	return Q.reject(new CordovaError(msg));
+
+    if (!version || !platform || !platforms[platform]) {
+        return Q.reject(new CordovaError('The provided path does not seem to contain a '
+
+            'Cordova platform: ' + libDir));
     }
 
-    // Use a fulfilled promise with the platform name and path as value to skip downloading.
     return Q({
-	platform: name,
-	libDir: pPath
+	libDir: libDir,
+	platform: platform,
+        version: version
     });
 }
 
@@ -194,50 +252,6 @@ function remove(hooksRunner, projectRoot, targets, opts) {
     });
 }
 
-function update(hooksRunner, projectRoot, targets, opts) {
-    // Shell out to the update script provided by the named platform.
-    var msg;
-    if ( !targets || !targets.length ) {
-        msg = 'No platform specified. Please specify a platform to update. See `' +
-              cordova_util.binname + ' platform list`.';
-        return Q.reject(new CordovaError(msg));
-    } else if (targets.length > 1) {
-        msg = 'Platform update can only be executed on one platform at a time.';
-        return Q.reject(new CordovaError(msg));
-    }
-    var plat = targets[0];
-    var platformPath = path.join(projectRoot, 'platforms', plat);
-    var installed_platforms = cordova_util.listPlatforms(projectRoot);
-    if (installed_platforms.indexOf(plat) < 0) {
-        msg = 'Platform "' + plat + '" is not installed. See `' +
-              cordova_util.binname + ' platform list`.';
-        return Q.reject(new CordovaError(msg));
-    }
-    // CB-6976 Windows Universal Apps. Special case to upgrade from windows8 to windows platform
-    if (plat == 'windows8' && !fs.existsSync(path.join(projectRoot, 'platforms',
'windows'))) {
-        var platformPathWindows = path.join(projectRoot, 'platforms', 'windows');
-        fs.renameSync(platformPath, platformPathWindows);
-        plat = 'windows';
-        platformPath = platformPathWindows;
-    }
-
-    // First, lazy_load the latest version.
-    return hooksRunner.fire('before_platform_update', opts)
-    .then(function() {
-        return lazy_load.based_on_config(projectRoot, plat, opts);
-    })
-    .then(function(libDir) {
-        // Call the platform's update script.
-        var script = path.join(libDir, 'bin', 'update');
-        return superspawn.spawn(script, [platformPath], { stdio: 'inherit' });
-    })
-    .then(function() {
-        // Copy the new cordova.js from www -> platform_www.
-        copy_cordova_js(projectRoot, plat);
-        // Leave it to the update script to log out "updated to v FOO".
-    });
-}
-
 function check(hooksRunner, projectRoot) {
     var platformsText = [],
         platforms_on_fs = cordova_util.listPlatforms(projectRoot),
@@ -473,84 +487,60 @@ function hostSupports(platform) {
 }
 
 // Returns a promise.
-function call_into_create(target, projectRoot, cfg, libDir, template_dir, opts) {
-    var output = path.join(projectRoot, 'platforms', target);
-    var msg;
+function getCreateArgs(platDetails, projectRoot, cfg, template_dir, opts) {
+    var output = path.join(projectRoot, 'platforms', platDetails.platform);
 
-    // Check if output directory already exists.
-    if (fs.existsSync(output)) {
-        msg = 'Platform ' + target + ' already added';
-        return Q.reject(new CordovaError(msg));
-    }
-
-    events.emit('log', 'Creating ' + target + ' project...');
-    var bin = path.join(libDir, 'bin', 'create');
     var args = [];
-    var platformVersion;
-    if (target == 'android') {
-        platformVersion = fs.readFileSync(path.join(libDir, 'VERSION'), 'UTF-8').trim();
-        if (semver.gt(platformVersion, '3.3.0')) {
-            args.push('--cli');
-        }
-    } else if (target == 'ios') {
-        platformVersion = fs.readFileSync(path.join(libDir, 'CordovaLib', 'VERSION'), 'UTF-8').trim();
-        if (semver.gt(platformVersion, '3.3.0')) {
-            args.push('--cli');
-        }
+    if (/android|ios/.exec(platDetails.platform) && semver.gt(platDetails.version,
'3.3.0')) {
+        args.push('--cli');
     }
 
     var pkg = cfg.packageName().replace(/[^\w.]/g,'_');
     // CB-6992 it is necessary to normalize characters
     // because node and shell scripts handles unicode symbols differently
     // We need to normalize the name to NFD form since iOS uses NFD unicode form
-    var name = target == 'ios' ? unorm.nfd(cfg.name()) : cfg.name();
+    var name = platDetails.platform == 'ios' ? unorm.nfd(cfg.name()) : cfg.name();
     args.push(output, pkg, name);
     if (template_dir) {
         args.push(template_dir);
     }
-
-    var copts = { stdio: 'inherit' };
-    if ('spawnoutput' in opts) {
-        copts = { stdio: opts.spawnoutput };
+    if (opts.link) {
+        args.push('--link');
     }
-    return superspawn.spawn(bin, args, copts)
-    .then(function() {
-        copy_cordova_js(projectRoot, target);
-    })
-    .then(function() {
-        return require('./cordova').raw.prepare(target);
-    })
-    .then(function() {
-        // Install all currently installed plugins into this new platform.
-        var plugins_dir = path.join(projectRoot, 'plugins');
-        var plugins = cordova_util.findPlugins(plugins_dir);
-        if (!plugins) return Q();
-
-        var plugman = require('../plugman/plugman');
-        // Install them serially.
-        return plugins.reduce(function(soFar, plugin) {
-            return soFar.then(function() {
-                events.emit('verbose', 'Installing plugin "' + plugin + '" following successful
platform add of ' + target);
-                plugin = path.basename(plugin);
-                var options = (function(){
-                    // Get plugin preferences from config features if have any
-                    // Pass them as cli_variables to plugman
-                    var feature = cfg.getFeature(plugin);
-                    var variables = feature && feature.variables;
-                    if (!!variables) {
-                        events.emit('verbose', 'Found variables for "' + plugin + '". Processing
as cli_variables.');
-                        return {
-                            cli_variables: variables
-                        };
-                    }
-                    return {};
-                })();
-                options.searchpath = opts.searchpath;
+    return args;
+}
 
-                return plugman.raw.install(target, output, plugin, plugins_dir, options);
-            });
-        }, Q());
-    });
+function installPluginsForNewPlatform(platform, projectRoot, cfg, opts) {
+    var output = path.join(projectRoot, 'platforms', platform);
+    // Install all currently installed plugins into this new platform.
+    var plugins_dir = path.join(projectRoot, 'plugins');
+    var plugins = cordova_util.findPlugins(plugins_dir);
+    if (!plugins) return Q();
+
+    var plugman = require('../plugman/plugman');
+    // Install them serially.
+    return plugins.reduce(function(soFar, plugin) {
+        return soFar.then(function() {
+            events.emit('verbose', 'Installing plugin "' + plugin + '" following successful
platform add of ' + platform);
+            plugin = path.basename(plugin);
+            var options = (function(){
+                // Get plugin preferences from config features if have any
+                // Pass them as cli_variables to plugman
+                var feature = cfg.getFeature(plugin);
+                var variables = feature && feature.variables;
+                if (!!variables) {
+                    events.emit('verbose', 'Found variables for "' + plugin + '". Processing
as cli_variables.');
+                    return {
+                        cli_variables: variables
+                    };
+                }
+                return {};
+            })();
+            options.searchpath = opts.searchpath;
+
+            return plugman.raw.install(platform, output, plugin, plugins_dir, options);
+        });
+    }, Q());
 }
 
 


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cordova.apache.org
For additional commands, e-mail: commits-help@cordova.apache.org


Mime
View raw message