cordova-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mmo...@apache.org
Subject [1/5] cordova-lib git commit: [CB-8286] Update create.js to always require passing in a www
Date Fri, 06 Mar 2015 21:06:17 GMT
Repository: cordova-lib
Updated Branches:
  refs/heads/copy-from-app-hello-world [created] 9ce5bc1ba


[CB-8286] Update create.js to always require passing in a www


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

Branch: refs/heads/copy-from-app-hello-world
Commit: e70432f2d3ad37506d1824a61d066887dbaf68b7
Parents: 99f981a
Author: Michal Mocny <mmocny@gmail.com>
Authored: Tue Mar 3 17:44:29 2015 -0500
Committer: Michal Mocny <mmocny@gmail.com>
Committed: Tue Mar 3 17:44:29 2015 -0500

----------------------------------------------------------------------
 cordova-lib/src/cordova/create.js     | 280 +++++++++++++----------------
 cordova-lib/templates/hooks-README.md | 196 --------------------
 2 files changed, 126 insertions(+), 350 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/e70432f2/cordova-lib/src/cordova/create.js
----------------------------------------------------------------------
diff --git a/cordova-lib/src/cordova/create.js b/cordova-lib/src/cordova/create.js
index 4aa68f8..2153733 100644
--- a/cordova-lib/src/cordova/create.js
+++ b/cordova-lib/src/cordova/create.js
@@ -25,177 +25,156 @@ var path          = require('path'),
     lazy_load     = require('./lazy_load'),
     Q             = require('q'),
     CordovaError  = require('../CordovaError'),
-    ConfigParser = require('../configparser/ConfigParser'),
+    ConfigParser  = require('../configparser/ConfigParser'),
     cordova_util  = require('./util'),
-    validateIdentifier = require('valid-identifier');
-
-var DEFAULT_NAME = 'HelloCordova',
-    DEFAULT_ID   = 'io.cordova.hellocordova';
+    validateIdentifier = require('valid-identifier'),
+    _             = require('underscore');
 
 /**
  * Usage:
  * @dir - directory where the project will be created. Required.
- * @id - app id. Optional, default is DEFAULT_ID.
- * @name - app name. Optional, default is DEFAULT_NAME.
  * @cfg - extra config to be saved in .cordova/config.json
  **/
 // Returns a promise.
 module.exports = create;
-function create(dir, id, name, cfg) {
-    if (!dir ) {
-        return Q.reject(new CordovaError(
-            'At least the dir must be provided to create new project. See `'+cordova_util.binname+'
help`.'
-        ));
-    }
-
-    if(id && !validateIdentifier(id)) {
-        return Q.reject(new CordovaError(
-            'App id contains a reserved word, or is not a valid identifier.'
-        ));
-    }
-
-    // Massage parameters
-    if (typeof cfg == 'string') {
-        cfg = JSON.parse(cfg);
-    }
-    cfg = cfg || {};
-    id = id || cfg.id || DEFAULT_ID;
-    name = name || cfg.name || DEFAULT_NAME;
-
-    // Make absolute.
-    dir = path.resolve(dir);
-
-    events.emit('log', 'Creating a new cordova project with name "' + name + '" and id "'
+ id + '" at location "' + dir + '"');
-
-    var www_dir = path.join(dir, 'www');
-
-    // dir must be either empty or not exist at all.
-
-    // dir must be either empty except for .cordova config file or not exist at all..
-    var sanedircontents = function (d) {
-        var contents = fs.readdirSync(d);
-        if (contents.length === 0) {
-            return true;
-        } else if (contents.length == 1) {
-            if (contents[0] == '.cordova') {
+function create(dir, cfg) {
+    return Q.fcall(function() {
+        // Lets check prerequisites first
+
+        if (!dir) {
+            throw new CordovaError('At least the dir must be provided to create new project.
See `' + cordova_util.binname + ' help`.');
+        }
+        if (!cfg) {
+            cfg = config.read(dir);
+            if (!cfg) {
+                throw new CordovaError('Must provide a project configuration.');
+            }
+        }
+
+        // Make absolute.
+        dir = path.resolve(dir);
+
+        // dir must be either empty except for .cordova config file or not exist at all..
+        var sanedircontents = function (d) {
+            var contents = fs.readdirSync(d);
+            if (contents.length === 0) {
                 return true;
+            } else if (contents.length == 1) {
+                if (contents[0] == '.cordova') {
+                    return true;
+                }
             }
+            return false;
+        };
+
+        if (fs.existsSync(dir) && !sanedircontents(dir)) {
+            throw new CordovaError('Path already exists and is not empty: ' + dir);
+        }
+
+        // Massage parameters
+        if (typeof cfg == 'string') {
+            cfg = JSON.parse(cfg);
         }
-        return false;
-    };
 
-    if (fs.existsSync(dir) && !sanedircontents(dir)) {
-        return Q.reject(new CordovaError('Path already exists and is not empty: ' + dir));
-    }
+        if (cfg.id && !validateIdentifier(cfg.id)) {
+            throw new CordovaError('App id contains a reserved word, or is not a valid identifier.');
+        }
+
+        if (!cfg.lib || !cfg.lib.www) {
+            throw new CordovaError('Must supply a source www path.');
+        }
 
-    var symlink = false; // Whether to symlink the www dir instead of copying.
-    var diskConfig = config.read(dir);
-    var wwwLib = cfg.lib && cfg.lib.www || diskConfig.lib && diskConfig.lib.www;
-    if (wwwLib) {
         // This was changed from "uri" to "url", but checking uri for backwards compatibility.
-        wwwLib.url = wwwLib.url || wwwLib.uri;
+        cfg.lib.www.url = cfg.lib.www.url || cfg.lib.www.uri;
         // TODO (kamrik): extend lazy_load for retrieval without caching to allow net urls
for --src.
-        wwwLib.version = wwwLib.version || 'not_versioned';
-        wwwLib.id = wwwLib.id || 'dummy_id';
-        symlink  = !!wwwLib.link;
-        // Strip link and url from cfg to avoid them being persisted to disk via .cordova/config.json.
-        cfg = JSON.parse(JSON.stringify(cfg));
-        cfg.lib.www = 0;
-        cfg = JSON.parse(JSON.stringify(cfg).replace(',"www":0', '').replace(/"www":0,?/,
'').replace(',"lib":{}', '').replace(/"lib":{},?/, ''));
-    }
-
-    // Update cached version of config.json
-    var origAutoPersist = config.getAutoPersist();
-    config.setAutoPersist(false);
-    config(dir, cfg);
-    config.setAutoPersist(origAutoPersist);
-
-    var p;
-    var www_parent_dir;
-    var custom_config_xml;
-    var custom_merges;
-    var custom_hooks;
-
-    if (wwwLib && wwwLib.url) {
-        events.emit('log', 'Using custom www assets from ' + wwwLib.url);
+        cfg.lib.www.version = cfg.lib.www.version || 'not_versioned';
+        cfg.lib.www.id = cfg.lib.www.id || 'dummy_id';
 
         // Make sure that the source www/ is not a direct ancestor of the
         // target www/, or else we will recursively copy forever. To do this,
         // we make sure that the shortest relative path from source-to-target
         // must start by going up at least one directory or with a drive
         // letter for Windows.
-        var rel_path = path.relative(wwwLib.url, www_dir);
+        var rel_path = path.relative(cfg.lib.www.url, dir);
         var goes_up = rel_path.split(path.sep)[0] == '..';
 
         if (!(goes_up || rel_path[1] == ':')) {
             throw new CordovaError(
-                'Project dir "' +
-                dir +
+                'Project dir "' + dir +
                 '" must not be created at/inside the template used to create the project
"' +
-                wwwLib.url + '".'
+                cfg.lib.www.url + '".'
             );
         }
-        if (symlink) {
-            p = Q(wwwLib.url);
-            events.emit('verbose', 'Symlinking custom www assets into "' + www_dir + '"');
+    })
+    .then(function() {
+        // Finally, Ready to start!
+        events.emit('log', 'Creating a new cordova project.');
+    })
+    .then(function() {
+        // Strip link and url from cfg to avoid them being persisted to disk via .cordova/config.json.
+        // TODO: apparently underscore has no deep clone.  Replace with lodash or something.
+        var cfgToPersistToDisk = _.clone(cfg);
+        //delete cfgToPersistToDisk.lib.www;
+        //if (Object.keys(cfgToPersistToDisk.lib).length === 0) delete cfgToPersistToDisk.lib;
+
+        // Update cached version of config.json
+        var origAutoPersist = config.getAutoPersist();
+        config.setAutoPersist(false);
+        config(dir, cfgToPersistToDisk);
+        config.setAutoPersist(origAutoPersist);
+    })
+    .then(function() {
+        if (!!cfg.lib.www.link) {
+            events.emit('verbose', 'Symlinking assets."');
+            return cfg.lib.www.url;
         } else {
-            p = lazy_load.custom({'www': wwwLib}, 'www')
-            .then(function(d) {
-                events.emit('verbose', 'Copying custom www assets into "' + www_dir + '"');
-                return d;
-            });
-        }
-    } else {
-        // No custom www - use stock cordova-hello-world-app.
-        events.emit('verbose', 'Using stock cordova hello-world application.');
-        p = lazy_load.cordova('www')
-        .then(function(d) {
-            events.emit('verbose', 'Copying stock Cordova www assets into "' + www_dir +
'"');
-            return d;
-        });
-    }
-
-    return p.then(function(www_lib) {
-        if (!fs.existsSync(www_lib)) {
-            throw new CordovaError('Could not find directory: '+www_lib);
+            events.emit('verbose', 'Copying assets."');
+            return lazy_load.custom({ 'www': cfg.lib.www }, 'www');
+        }
+    })
+    .then(function(import_from_path) {
+        if (!fs.existsSync(import_from_path)) {
+            throw new CordovaError('Could not find directory: ' + import_from_path);
         }
+
+        var paths = {
+            root: import_from_path,
+            www: import_from_path
+        };
+
         // Keep going into child "www" folder if exists in stock app package.
-        while (fs.existsSync(path.join(www_lib, 'www'))) {
-            www_parent_dir = www_lib;
-            www_lib = path.join(www_lib, 'www');
+        while (fs.existsSync(path.join(paths.www, 'www'))) {
+            paths.root = paths.www;
+            paths.www = path.join(paths.root, 'www');
         }
 
-        // Find if we also have custom merges and config.xml as siblings of custom www.
-        if (www_parent_dir && wwwLib) {
-            custom_config_xml = path.join(www_parent_dir, 'config.xml');
-            if ( !fs.existsSync(custom_config_xml) ) {
-                custom_config_xml = null;
-            }
-            custom_merges = path.join(www_parent_dir, 'merges');
-            if ( !fs.existsSync(custom_merges) ) {
-                custom_merges = null;
-            }
-            custom_hooks = path.join(www_parent_dir, 'hooks');
-            if ( !fs.existsSync(custom_hooks) ) {
-                custom_hooks = null;
-            }
+        if (fs.existsSync(path.join(paths.root, 'config.xml'))) {
+            paths.configXml = path.join(paths.root, 'config.xml');
+        }
+        if (fs.existsSync(path.join(paths.root, 'merges'))) {
+            paths.merges = path.join(paths.root, 'merges');
+        }
+        if (fs.existsSync(path.join(paths.root, 'hooks'))) {
+            paths.hooks = path.join(paths.root, 'hooks');
         }
 
         var dirAlreadyExisted = fs.existsSync(dir);
         if (!dirAlreadyExisted) {
             fs.mkdirSync(dir);
         }
-        if (symlink) {
+
+        if (!!cfg.lib.www.link) {
+            // symlink
             try {
-                fs.symlinkSync(www_lib, www_dir, 'dir');
-                if (custom_merges) {
-                    fs.symlinkSync(custom_merges, path.join(dir, 'merges'), 'dir');
+                fs.symlinkSync(paths.www, path.join(dir, 'www'), 'dir');
+                if (paths.merges) {
+                    fs.symlinkSync(paths.merges, path.join(dir, 'merges'), 'dir');
                 }
-                if (custom_hooks) {
-                    fs.symlinkSync(custom_hooks, path.join(dir, 'hooks'), 'dir');
+                if (paths.hooks) {
+                    fs.symlinkSync(paths.hooks, path.join(dir, 'hooks'), 'dir');
                 }
-                if (custom_config_xml) {
-                    fs.symlinkSync(custom_config_xml, path.join(dir, 'config.xml'));
+                if (paths.configXml) {
+                    fs.symlinkSync(paths.configXml, path.join(dir, 'config.xml'));
                 }
             } catch (e) {
                 if (!dirAlreadyExisted) {
@@ -207,20 +186,20 @@ function create(dir, id, name, cfg) {
                 throw e;
             }
         } else {
-            shell.mkdir(www_dir);
-            shell.cp('-R', path.join(www_lib, '*'), www_dir);
-            if (custom_merges) {
-                var merges_dir = path.join(dir, 'merges');
-                shell.mkdir(merges_dir);
-                shell.cp('-R', path.join(custom_merges, '*'), merges_dir);
+            // copy
+            shell.mkdir(path.join(dir, 'www'));
+            shell.cp('-R', path.join(paths.www, '*'), path.join(dir, 'www'));
+
+            if (paths.merges) {
+                shell.mkdir(path.join(dir, 'merges'));
+                shell.cp('-R', path.join(paths.merges, '*'), path.join(dir, 'merges'));
             }
-            if (custom_hooks) {
-                var hooks_dir = path.join(dir, 'hooks');
-                shell.mkdir(hooks_dir);
-                shell.cp('-R', path.join(custom_hooks, '*'), hooks_dir);
+            if (paths.hooks) {
+                shell.mkdir(path.join(dir, 'hooks'));
+                shell.cp('-R', path.join(paths.hooks, '*'), path.join(dir, 'hooks'));
             }
-            if (custom_config_xml) {
-                shell.cp(custom_config_xml, path.join(dir, 'config.xml'));
+            if (paths.configXml) {
+                shell.cp(paths.configXml, path.join(dir, 'config.xml'));
             }
 
         }
@@ -229,23 +208,16 @@ function create(dir, id, name, cfg) {
         shell.mkdir(path.join(dir, 'platforms'));
         shell.mkdir(path.join(dir, 'plugins'));
 
-        // Add template hooks/ for apps that are missing it
-        if (!custom_hooks) {
-            shell.mkdir(path.join(dir, 'hooks'));
-            // Add hooks README.md
-            shell.cp(path.join(__dirname, '..', '..', 'templates', 'hooks-README.md'), path.join(dir,
'hooks', 'README.md'));
-        }
-
         // Add template config.xml for apps that are missing it
         var configPath = cordova_util.projectConfig(dir);
         if (!fs.existsSync(configPath)) {
-            var template_config_xml = path.join(__dirname, '..', '..', 'templates', 'config.xml');
-            shell.cp(template_config_xml, configPath);
-            // Write out id and name to config.xml
-            var conf = new ConfigParser(configPath);
-            conf.setPackageName(id);
-            conf.setName(name);
-            conf.write();
+            shell.cp(path.join(__dirname, '..', '..', 'templates', 'config.xml'), configPath);
         }
+
+        // Write out id and name to config.xml
+        var conf = new ConfigParser(configPath);
+        if (cfg.id) conf.setPackageName(cfg.id);
+        if (cfg.name) conf.setName(cfg.name);
+        conf.write();
     });
 }

http://git-wip-us.apache.org/repos/asf/cordova-lib/blob/e70432f2/cordova-lib/templates/hooks-README.md
----------------------------------------------------------------------
diff --git a/cordova-lib/templates/hooks-README.md b/cordova-lib/templates/hooks-README.md
deleted file mode 100644
index 62e58b4..0000000
--- a/cordova-lib/templates/hooks-README.md
+++ /dev/null
@@ -1,196 +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 Hooks
-
-Cordova Hooks represent special scripts which could be added by application and plugin developers
or even by your own build system  to customize cordova commands. Hook scripts could be defined
by adding them to the special predefined folder (`/hooks`) or via configuration files (`config.xml`
and `plugin.xml`) and run serially in the following order:
-* Application hooks from `/hooks`;
-* Application hooks from `config.xml`;
-* Plugin hooks from `plugins/.../plugin.xml`.
-
-__Remember__: Make your scripts executable.
-
-__Note__: `.cordova/hooks` directory is also supported for backward compatibility, but we
don't recommend using it as it is deprecated.
-
-## Supported hook types
-The following hook types are supported:
-
-    after_build/
-    after_compile/
-    after_docs/
-    after_emulate/
-    after_platform_add/
-    after_platform_rm/
-    after_platform_ls/
-    after_plugin_add/
-    after_plugin_ls/
-    after_plugin_rm/
-    after_plugin_search/
-    after_plugin_install/   <-- Plugin hooks defined in plugin.xml are executed exclusively
for a plugin being installed
-    after_prepare/
-    after_run/
-    after_serve/
-    before_build/
-    before_compile/
-    before_docs/
-    before_emulate/
-    before_platform_add/
-    before_platform_rm/
-    before_platform_ls/
-    before_plugin_add/
-    before_plugin_ls/
-    before_plugin_rm/
-    before_plugin_search/
-    before_plugin_install/   <-- Plugin hooks defined in plugin.xml are executed exclusively
for a plugin being installed
-    before_plugin_uninstall/   <-- Plugin hooks defined in plugin.xml are executed exclusively
for a plugin being uninstalled
-    before_prepare/
-    before_run/
-    before_serve/
-    pre_package/ <-- Windows 8 and Windows Phone only.
-
-## Ways to define hooks
-### Via '/hooks' directory
-To execute custom action when corresponding hook type is fired, use hook type as a name for
a subfolder inside 'hooks' directory and place you script file here, for example:
-
-    # script file will be automatically executed after each build
-    hooks/after_build/after_build_custom_action.js
-
-
-### Config.xml
-
-Hooks can be defined in project's `config.xml` using `<hook>` elements, for example:
-
-    <hook type="before_build" src="scripts/appBeforeBuild.bat" />
-    <hook type="before_build" src="scripts/appBeforeBuild.js" />
-    <hook type="before_plugin_install" src="scripts/appBeforePluginInstall.js" />
-
-    <platform name="wp8">
-        <hook type="before_build" src="scripts/wp8/appWP8BeforeBuild.bat" />
-        <hook type="before_build" src="scripts/wp8/appWP8BeforeBuild.js" />
-        <hook type="before_plugin_install" src="scripts/wp8/appWP8BeforePluginInstall.js"
/>
-        ...
-    </platform>
-
-    <platform name="windows8">
-        <hook type="before_build" src="scripts/windows8/appWin8BeforeBuild.bat" />
-        <hook type="before_build" src="scripts/windows8/appWin8BeforeBuild.js" />
-        <hook type="before_plugin_install" src="scripts/windows8/appWin8BeforePluginInstall.js"
/>
-        ...
-    </platform>
-
-### Plugin hooks (plugin.xml)
-
-As a plugin developer you can define hook scripts using `<hook>` elements in a `plugin.xml`
like that:
-
-    <hook type="before_plugin_install" src="scripts/beforeInstall.js" />
-    <hook type="after_build" src="scripts/afterBuild.js" />
-
-    <platform name="wp8">
-        <hook type="before_plugin_install" src="scripts/wp8BeforeInstall.js" />
-        <hook type="before_build" src="scripts/wp8BeforeBuild.js" />
-        ...
-    </platform>
-
-`before_plugin_install`, `after_plugin_install`, `before_plugin_uninstall` plugin hooks will
be fired exclusively for the plugin being installed/uninstalled.
-
-## Script Interface
-
-### Javascript
-
-If you are writing hooks in Javascript you should use the following module definition:
-```javascript
-module.exports = function(context) {
-    ...
-}
-```
-
-You can make your scipts async using Q:
-```javascript
-module.exports = function(context) {
-    var Q = context.requireCordovaModule('q');
-    var deferral = new Q.defer();
-
-    setTimeout(function(){
-    	console.log('hook.js>> end');
-		deferral.resolve();
-    }, 1000);
-
-    return deferral.promise;
-}
-```
-
-`context` object contains hook type, executed script full path, hook options, command-line
arguments passed to Cordova and top-level "cordova" object:
-```json
-{
-	"hook": "before_plugin_install",
-	"scriptLocation": "c:\\script\\full\\path\\appBeforePluginInstall.js",
-	"cmdLine": "The\\exact\\command\\cordova\\run\\with arguments",
-	"opts": {
-		"projectRoot":"C:\\path\\to\\the\\project",
-		"cordova": {
-			"platforms": ["wp8"],
-			"plugins": ["com.plugin.withhooks"],
-			"version": "0.21.7-dev"
-		},
-		"plugin": {
-			"id": "com.plugin.withhooks",
-			"pluginInfo": {
-				...
-			},
-			"platform": "wp8",
-			"dir": "C:\\path\\to\\the\\project\\plugins\\com.plugin.withhooks"
-		}
-	},
-	"cordova": {...}
-}
-
-```
-`context.opts.plugin` object will only be passed to plugin hooks scripts.
-
-You can also require additional Cordova modules in your script using `context.requireCordovaModule`
in the following way:
-```javascript
-var Q = context.requireCordovaModule('q');
-```
-
-__Note__:  new module loader script interface is used for the `.js` files defined via `config.xml`
or `plugin.xml` only.
-For compatibility reasons hook files specified via `/hooks` folders are run via Node child_process
spawn, see 'Non-javascript' section below.
-
-### Non-javascript
-
-Non-javascript scripts are run via Node child_process spawn from the project's root directory
and have the root directory passes as the first argument. All other options are passed to
the script using environment variables:
-
-* CORDOVA_VERSION - The version of the Cordova-CLI.
-* CORDOVA_PLATFORMS - Comma separated list of platforms that the command applies to (e.g.:
android, ios).
-* CORDOVA_PLUGINS - Comma separated list of plugin IDs that the command applies to (e.g.:
org.apache.cordova.file, org.apache.cordova.file-transfer)
-* CORDOVA_HOOK - Path to the hook that is being executed.
-* CORDOVA_CMDLINE - The exact command-line arguments passed to cordova (e.g.: cordova run
ios --emulate)
-
-If a script returns a non-zero exit code, then the parent cordova command will be aborted.
-
-## Writing hooks
-
-We highly recommend writing your hooks using Node.js so that they are
-cross-platform. Some good examples are shown here:
-
-[http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/](http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/)
-
-Also, note that even if you are working on Windows, and in case your hook scripts aren't
bat files (which is recommended, if you want your scripts to work in non-Windows operating
systems) Cordova CLI will expect a shebang line as the first line for it to know the interpreter
it needs to use to launch the script. The shebang line should match the following example:
-
-    #!/usr/bin/env [name_of_interpreter_executable]


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


Mime
View raw message