diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 878cac9..0000000 --- a/.eslintrc.json +++ /dev/null @@ -1,208 +0,0 @@ -{ - "env": { - "node": true - }, - "extends": "eslint:recommended", - "rules": { - "accessor-pairs": "error", - "array-bracket-spacing": "off", - "array-callback-return": "error", - "arrow-body-style": "error", - "arrow-parens": "error", - "arrow-spacing": "error", - "block-scoped-var": "off", - "block-spacing": "off", - "brace-style": "off", - "callback-return": "off", - "camelcase": "off", - "comma-dangle": [ - "error", - "only-multiline" - ], - "comma-spacing": "off", - "comma-style": [ - "error", - "last" - ], - "complexity": "off", - "computed-property-spacing": "off", - "consistent-return": "off", - "consistent-this": "off", - "curly": "off", - "default-case": "off", - "dot-location": [ - "error", - "property" - ], - "dot-notation": "off", - "eol-last": "off", - "eqeqeq": "off", - "func-names": "off", - "func-style": "off", - "generator-star-spacing": "error", - "global-require": "off", - "guard-for-in": "off", - "handle-callback-err": "off", - "id-blacklist": "error", - "id-length": "off", - "id-match": "error", - "indent": "off", - "init-declarations": "off", - "jsx-quotes": "error", - "key-spacing": "off", - "keyword-spacing": "off", - "linebreak-style": [ - "error", - "unix" - ], - "lines-around-comment": "off", - "max-depth": "off", - "max-len": "off", - "max-nested-callbacks": "error", - "max-params": "off", - "max-statements": "off", - "new-parens": "off", - "newline-after-var": "off", - "newline-before-return": "off", - "newline-per-chained-call": "off", - "no-alert": "off", - "no-array-constructor": "error", - "no-bitwise": "off", - "no-caller": "error", - "no-catch-shadow": "off", - "no-confusing-arrow": "error", - "no-continue": "off", - "no-div-regex": "error", - "no-else-return": "off", - "no-empty-function": "off", - "no-eq-null": "off", - "no-eval": "error", - "no-extend-native": "error", - "no-extra-bind": "error", - "no-extra-label": "error", - "no-extra-parens": "off", - "no-floating-decimal": "error", - "no-implicit-coercion": [ - "error", - { - "boolean": false, - "number": false, - "string": false - } - ], - "no-implicit-globals": "off", - "no-implied-eval": "error", - "no-inline-comments": "off", - "no-inner-declarations": [ - "error", - "functions" - ], - "no-invalid-this": "off", - "no-iterator": "error", - "no-label-var": "off", - "no-labels": "off", - "no-lone-blocks": "error", - "no-lonely-if": "off", - "no-loop-func": "off", - "no-magic-numbers": "off", - "no-mixed-requires": "off", - "no-multi-spaces": "off", - "no-multi-str": "off", - "no-multiple-empty-lines": "error", - "no-native-reassign": "error", - "no-negated-condition": "off", - "no-nested-ternary": "off", - "no-new": "off", - "no-new-func": "off", - "no-new-object": "error", - "no-new-require": "off", - "no-new-wrappers": "error", - "no-octal-escape": "error", - "no-param-reassign": "off", - "no-path-concat": "off", - "no-plusplus": "off", - "no-process-env": "off", - "no-process-exit": "off", - "no-proto": "error", - "no-restricted-globals": "error", - "no-restricted-imports": "error", - "no-restricted-modules": "error", - "no-restricted-syntax": "error", - "no-return-assign": "off", - "no-script-url": "error", - "no-self-compare": "off", - "no-sequences": "off", - "no-shadow": "off", - "no-shadow-restricted-names": "error", - "no-spaced-func": "off", - "no-sync": "off", - "no-ternary": "off", - "no-throw-literal": "off", - "no-trailing-spaces": "off", - "no-undef-init": "error", - "no-undefined": "off", - "no-underscore-dangle": "off", - "no-unmodified-loop-condition": "error", - "no-unneeded-ternary": [ - "error", - { - "defaultAssignment": true - } - ], - "no-unused-expressions": "off", - "no-use-before-define": "off", - "no-useless-call": "error", - "no-useless-concat": "off", - "no-useless-constructor": "error", - "no-var": "off", - "no-void": "off", - "no-warning-comments": "off", - "no-whitespace-before-property": "error", - "no-with": "error", - "object-curly-spacing": "off", - "object-shorthand": "off", - "one-var": "off", - "one-var-declaration-per-line": "off", - "operator-assignment": [ - "error", - "always" - ], - "operator-linebreak": "off", - "padded-blocks": "off", - "prefer-arrow-callback": "off", - "prefer-const": "error", - "prefer-reflect": "off", - "prefer-rest-params": "off", - "prefer-spread": "off", - "prefer-template": "off", - "quote-props": "off", - "quotes": "off", - "radix": "off", - "require-jsdoc": "off", - "require-yield": "error", - "semi": "off", - "semi-spacing": "off", - "sort-imports": "error", - "sort-vars": "off", - "space-before-blocks": "off", - "space-before-function-paren": "off", - "space-in-parens": "off", - "space-infix-ops": "off", - "space-unary-ops": [ - "error", - { - "nonwords": false, - "words": false - } - ], - "spaced-comment": "off", - "strict": "off", - "template-curly-spacing": "error", - "valid-jsdoc": "off", - "vars-on-top": "off", - "wrap-iife": "off", - "wrap-regex": "off", - "yield-star-spacing": "error", - "yoda": "off" - } -} \ No newline at end of file diff --git a/lib/config-xml.js b/lib/config-xml.js index 204ed38..9ae831b 100644 --- a/lib/config-xml.js +++ b/lib/config-xml.js @@ -4,9 +4,7 @@ var Q = require('q'); var xml2js = require('xml2js'); var log = require('./logging').logger; -var ConfigXml = module.exports; - -ConfigXml.loadToJson = function(appDirectory) { +function loadToJson(appDirectory) { var d = Q.defer(); if (!appDirectory) { @@ -26,17 +24,17 @@ ConfigXml.loadToJson = function(appDirectory) { }); return d.promise; -}; +} -ConfigXml.loadToStream = function(appDirectory) { +function loadToStream(appDirectory) { if (!appDirectory) { appDirectory = process.cwd(); } return fs.createReadStream(path.join(appDirectory, 'config.xml')); -}; +} -ConfigXml.setConfigXml = function setConfigXml(appDirectory, options) { +function setConfigXml(appDirectory, options) { var madeChange = false; if (!appDirectory) { @@ -56,7 +54,7 @@ ConfigXml.setConfigXml = function setConfigXml(appDirectory, options) { } } - return ConfigXml.loadToJson(appDirectory, options) + return loadToJson(appDirectory, options) .then(function(configJson) { if (!configJson.widget) { throw new Error('\nYour config.xml file is invalid. You must have a element.'); @@ -90,4 +88,10 @@ ConfigXml.setConfigXml = function setConfigXml(appDirectory, options) { fs.writeFileSync(configXmlPath, configString); } }); +} + +module.exports = { + loadToJson: loadToJson, + loadToStream: loadToStream, + setConfigXml: setConfigXml }; diff --git a/lib/cordova.js b/lib/cordova.js index 98aa3bb..e546388 100644 --- a/lib/cordova.js +++ b/lib/cordova.js @@ -7,11 +7,10 @@ var State = require('./state'); var Q = require('q'); var log = require('./logging').logger; -var Cordova = module.exports; -Cordova.Lib = require('cordova-lib'); +var Lib = require('cordova-lib'); -Cordova.runCordova = function runCordova(cmdName) { +function runCordova(cmdName) { var deferred = Q.defer(); var self = this; var cmdArgs = (process.argv.length > 3 ? process.argv.slice(3) : []); @@ -138,9 +137,9 @@ Cordova.runCordova = function runCordova(cmdName) { } return deferred.promise; -}; +} -Cordova.setupLiveReload = function() { +function setupLiveReload() { var d = Q.defer(); log.info('Setup Live Reload'); @@ -183,10 +182,10 @@ Cordova.setupLiveReload = function() { }); return d.promise; -}; +} -Cordova.addPlatform = function addPlatform(projectRoot, platform, savePlatform) { +function addPlatform(projectRoot, platform, savePlatform) { log.debug('Cordova.addPlatform: ', projectRoot, platform, savePlatform); // var opts = { @@ -216,9 +215,9 @@ Cordova.addPlatform = function addPlatform(projectRoot, platform, savePlatform) return State.savePlatform(projectRoot, platform); } }); -}; +} -Cordova.removePlatform = function removePlatform(projectRoot, platform, savePlatform) { +function removePlatform(projectRoot, platform, savePlatform) { var options = {}; var originalPwd = process.env.PWD; process.env.PWD = projectRoot; @@ -230,9 +229,9 @@ Cordova.removePlatform = function removePlatform(projectRoot, platform, savePlat return State.removePlatform(projectRoot, platform); } }); -}; +} -Cordova.runPlatform = function runPlatform(projectRoot, platform) { +function runPlatform(projectRoot, platform) { var options = { platforms: [], options: [], @@ -253,10 +252,10 @@ Cordova.runPlatform = function runPlatform(projectRoot, platform) { .catch(function(error) { throw error; }); -}; +} -Cordova.addPlugin = function addPlugin(projectRoot, pluginId, pluginVariables, savePlugin) { +function addPlugin(projectRoot, pluginId, pluginVariables, savePlugin) { log.debug('Cordova.addPlugin: projectRoot', projectRoot, 'pluginId', pluginId, 'pluginVariables', pluginVariables, 'savePlugin', savePlugin); var originalPwd = process.env.PWD; @@ -276,9 +275,9 @@ Cordova.addPlugin = function addPlugin(projectRoot, pluginId, pluginVariables, s log.error('Error occurred while adding plugin: ', error); throw error; }); -}; +} -Cordova.removePlugin = function removePlugin(projectRoot, pluginId) { +function removePlugin(projectRoot, pluginId) { var originalPwd = process.env.PWD; process.env.PWD = projectRoot; @@ -289,9 +288,9 @@ Cordova.removePlugin = function removePlugin(projectRoot, pluginId) { .catch(function(error) { throw error; }); -}; +} -Cordova.buildPlatform = function buildPlatform(projectRoot, platform) { +function buildPlatform(projectRoot, platform) { var options = { platforms: [], options: [], @@ -312,9 +311,9 @@ Cordova.buildPlatform = function buildPlatform(projectRoot, platform) { .catch(function(error) { throw error; }); -}; +} -Cordova.preparePlatform = function preparePlatform(projectRoot, platform) { +function preparePlatform(projectRoot, platform) { var options = { platforms: [], options: [], @@ -335,4 +334,17 @@ Cordova.preparePlatform = function preparePlatform(projectRoot, platform) { .catch(function(error) { throw error; }); +} + +module.exports = { + Lib: Lib, + runCordova: runCordova, + setupLiveReload: setupLiveReload, + addPlatform: addPlatform, + removePlatform: removePlatform, + runPlatform: runPlatform, + addPlugin: addPlugin, + removePlugin: removePlugin, + buildPlatform: buildPlatform, + preparePlatform: preparePlatform }; diff --git a/lib/hooks.js b/lib/hooks.js index dbac836..5f6a580 100644 --- a/lib/hooks.js +++ b/lib/hooks.js @@ -3,11 +3,9 @@ var path = require('path'); var shelljs = require('shelljs'); var log = require('./logging').logger; -var Hooks = module.exports; - shelljs.config.silent = true; -Hooks.addCliHookDirectory = function addCliHookDirectory(appDirectory, cliHookPath, hookDirectoryName) { +function addCliHookDirectory(appDirectory, cliHookPath, hookDirectoryName) { fs.readdir(cliHookPath, function(err, files) { // loop through each of the scripts in the ionic-cli hook directory @@ -17,12 +15,12 @@ Hooks.addCliHookDirectory = function addCliHookDirectory(appDirectory, cliHookPa if (hookFilename.indexOf('.js') === -1) return; // check if this hook script has already been added to this ionic project - Hooks.addHookScript(appDirectory, cliHookPath, hookDirectoryName, hookFilename); + addHookScript(appDirectory, cliHookPath, hookDirectoryName, hookFilename); } }); -}; +} -Hooks.addHookScript = function addHookScript(appDirectory, cliHookPath, hookDirectoryName, hookFilename) { +function addHookScript(appDirectory, cliHookPath, hookDirectoryName, hookFilename) { // add the root hooks directory if the project doesn't have it try { @@ -60,9 +58,9 @@ Hooks.addHookScript = function addHookScript(appDirectory, cliHookPath, hookDire } catch (e) { log.error('Error adding hook script ' + hookDirectoryName + '/' + hookFilename + ', %s', e, {}); } -}; +} -Hooks.add = function add(appDirectory) { +function add(appDirectory) { log.info('Adding in default Ionic Cordova hooks'); // Add hooks which this Ionic project doesn't already have @@ -83,14 +81,14 @@ Hooks.add = function add(appDirectory) { for (var x = 0; x < files.length; x += 1) { if (files[x].indexOf('.') > -1) continue; - Hooks.addCliHookDirectory(appDirectory, path.join(cliHooksPath, files[x]), files[x]); + addCliHookDirectory(appDirectory, path.join(cliHooksPath, files[x]), files[x]); } }); log.info('Added default Ionic Cordova hooks'); -}; +} -Hooks.remove = function remove(appDirectory) { +function remove(appDirectory) { log.info('Removing the Ionic Cordova plugin hooks'); var oldPluginHooks = [ 'after_platform_add/010_install_plugins.js', @@ -106,10 +104,9 @@ Hooks.remove = function remove(appDirectory) { }); log.info('Removed the Ionic Cordova hooks'); -}; - +} -Hooks.setHooksPermission = function setHooksPermission(appDirectory) { +function setHooksPermission(appDirectory) { // Go through `hooks` directory - after_prepare // for each directory, go into the directories of that path @@ -143,4 +140,12 @@ Hooks.setHooksPermission = function setHooksPermission(appDirectory) { } log.debug('Updated the hooks directory to have execute permissions'); +} + +module.exports = { + addCliHookDirectory: addCliHookDirectory, + addHookScript: addHookScript, + add: add, + remove: remove, + setHooksPermission: setHooksPermission }; diff --git a/lib/info.js b/lib/info.js index 82add8c..dc18f29 100644 --- a/lib/info.js +++ b/lib/info.js @@ -4,14 +4,12 @@ var os = require('os'); var semver = require('semver'); var log = require('./logging').logger; -var Info = module.exports; - var requirements = { node: '>=0.12.x', cordova: '>=4.2.0' }; -Info.getMacInfo = function getMacInfo() { +function getMacInfo() { // Need to get: // Look up for what version (Yosemite, Mavericks, Mountain Lion) @@ -39,9 +37,9 @@ Info.getMacInfo = function getMacInfo() { } return 'Mac OS X ' + macVersion; -}; +} -Info.getCordovaInfo = function getCordovaInfo(info) { +function getCordovaInfo(info) { var command = 'cordova -v'; var result = shelljs.exec(command, { silent: true }); if (result.code !== 0) { @@ -50,53 +48,53 @@ Info.getCordovaInfo = function getCordovaInfo(info) { } info.cordova = result.output.replace('\n', ''); -}; +} -Info.getXcodeInfo = function getXcodeInfo() { +function getXcodeInfo() { var result = shelljs.exec('/usr/bin/xcodebuild -version', { silent: true }); if (result.code !== 0) { return 'Not installed'; } var version = result.output.replace(/\n/g, ' '); return version; -}; +} -Info.getIosSimInfo = function getIosSimInfo() { +function getIosSimInfo() { var result = shelljs.exec('ios-sim --version', { silent: true }); if (result.code !== 0) { return 'Not installed'; } var version = result.output.replace(/\n/g, ' '); return version; -}; +} -Info.getIosDeployInfo = function getIosDeployInfo() { +function getIosDeployInfo() { var result = shelljs.exec('ios-deploy --version', { silent: true }); if (result.code !== 0) { return 'Not installed'; } var version = result.output.replace(/\n/g, ' '); return version; -}; +} -Info.getIonicCliVersion = function getIonicCliVersion(info, ionicCliPath) { +function getIonicCliVersion(info, ionicCliPath) { try { var ionicCliPackageJsonPath = path.join(ionicCliPath, 'package.json'); var ionicCliPackageJson = require(ionicCliPackageJsonPath); info.ionic_cli = ionicCliPackageJson.version; // eslint-disable-line camelcase } catch (ex) {} // eslint-disable-line no-empty -}; +} -Info.getIonicLibVersion = function getIonicLibVersion(info) { +function getIonicLibVersion(info) { try { var packageJson = require(path.resolve(__dirname, '../package.json')); var ionicLibVersion = packageJson.version; info.ionic_lib = ionicLibVersion; // eslint-disable-line camelcase } catch (ex) {} // eslint-disable-line no-empty -}; +} -Info.getIonicVersion = function getIonicVersion(info, appDirectory) { +function getIonicVersion(info, appDirectory) { var packageJson; try { packageJson = require(path.join(appDirectory, 'node_modules', 'ionic-angular', 'package.json')); @@ -120,7 +118,7 @@ Info.getIonicVersion = function getIonicVersion(info, appDirectory) { var ionicBowerJson = require(path.join(appDirectory, 'www', 'lib', 'ionic', 'bower.json')); info.ionic = ionicBowerJson.version; } catch (ex) {} // eslint-disable-line no-empty -}; +} // Windows XP 5.1.2600 // Windows Server 2003 5.2.3790 @@ -137,7 +135,7 @@ Info.getIonicVersion = function getIonicVersion(info, appDirectory) { // Windows Server 2012 R2 6.3.9600 // Windows 10 Technical Preview 6.4.9841 -Info.getWindowsEnvironmentInfo = function getWindowsEnvironmentInfo() { +function getWindowsEnvironmentInfo() { // Windows version reference // http://en.wikipedia.org/wiki/Ver_%28command%29 @@ -168,36 +166,36 @@ Info.getWindowsEnvironmentInfo = function getWindowsEnvironmentInfo() { } return windowsVersion; -}; +} -Info.getLinuxEnvironmentInfo = function getLinuxEnvironmentInfo() { +function getLinuxEnvironmentInfo() { var result = shelljs.exec('lsb_release -id', { silent: true }); return result.output.replace(/\n/g, ' '); -}; +} // http://stackoverflow.com/questions/6551006/get-my-os-from-the-node-js-shell -Info.getOsEnvironment = function getOsEnvironment(info) { +function getOsEnvironment(info) { switch (os.type()) { case 'Darwin': - info.os = Info.getMacInfo(); - info.xcode = Info.getXcodeInfo(); - info.ios_sim = Info.getIosSimInfo(); // eslint-disable-line camelcase - info.ios_deploy = Info.getIosDeployInfo(); // eslint-disable-line camelcase + info.os = getMacInfo(); + info.xcode = getXcodeInfo(); + info.ios_sim = getIosSimInfo(); // eslint-disable-line camelcase + info.ios_deploy = getIosDeployInfo(); // eslint-disable-line camelcase break; case 'Windows_NT': - info.os = Info.getWindowsEnvironmentInfo(); + info.os = getWindowsEnvironmentInfo(); break; case 'Linux': - info.os = Info.getLinuxEnvironmentInfo(); + info.os = getLinuxEnvironmentInfo(); break; } -}; +} -Info.getNodeVersion = function getNodeVersion(info) { +function getNodeVersion(info) { info.node = process.version; -}; +} -Info.gatherGulpInfo = function gatherGulpInfo(info) { +function gatherGulpInfo(info) { var result = shelljs.exec('gulp -v', { silent: true }); try { @@ -209,9 +207,9 @@ Info.gatherGulpInfo = function gatherGulpInfo(info) { } } } catch (ex) {} // eslint-disable-line no-empty -}; +} -Info.gatherInfo = function gatherInfo() { +function gatherInfo() { var info = {}; // For macs we want: @@ -234,20 +232,20 @@ Info.gatherInfo = function gatherInfo() { // ionic_cli: '1.3.0' // }; - Info.getIonicLibVersion(info); + getIonicLibVersion(info); - Info.getNodeVersion(info); + getNodeVersion(info); - Info.getOsEnvironment(info); + getOsEnvironment(info); - Info.getCordovaInfo(info); + getCordovaInfo(info); - Info.gatherGulpInfo(info); + gatherGulpInfo(info); return info; -}; +} -Info.printInfo = function printInfo(info) { +function printInfo(info) { log.info('\nYour system information:\n'); log.info('Cordova CLI:', info.cordova); @@ -284,10 +282,10 @@ Info.printInfo = function printInfo(info) { } log.info('\n'); -}; +} -Info.checkRuntime = function checkRuntime() { - var info = this.gatherInfo(); +function checkRuntime() { + var info = gatherInfo(); var iosDeployInstalled = false; var iosSimInstalled = false; var cordovaInstalled = false; @@ -351,13 +349,32 @@ Info.checkRuntime = function checkRuntime() { } return validRuntime; +} + +function run() { + + var info = gatherInfo(); + printInfo(info); + + checkRuntime(); +} + +module.exports = { + getMacInfo: getMacInfo, + getCordovaInfo: getCordovaInfo, + getXcodeInfo: getXcodeInfo, + getIosSimInfo: getIosSimInfo, + getIosDeployInfo: getIosDeployInfo, + getIonicCliVersion: getIonicCliVersion, + getIonicLibVersion: getIonicLibVersion, + getIonicVersion: getIonicVersion, + getWindowsEnvironmentInfo: getWindowsEnvironmentInfo, + getLinuxEnvironmentInfo: getLinuxEnvironmentInfo, + getOsEnvironment: getOsEnvironment, + getNodeVersion: getNodeVersion, + gatherGulpInfo: gatherGulpInfo, + gatherInfo: gatherInfo, + printInfo: printInfo, + checkRuntime: checkRuntime, + run: run }; - -Info.run = function run() { - - var info = Info.gatherInfo(); - Info.printInfo(info); - - Info.checkRuntime(); -}; - diff --git a/lib/io-config.js b/lib/io-config.js index 45dcb47..125b988 100644 --- a/lib/io-config.js +++ b/lib/io-config.js @@ -7,8 +7,6 @@ var settings = require('./settings'); var cheerio = require('cheerio'); var log = require('./logging').logger; -var IoConfig = module.exports; - var CORE_FILE = './www/lib/ionic-platform-web-client/dist/ionic.io.bundle.js'; var CORE_FILE_MIN = './www/lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js'; var CONFIG_BACKUP = './.io-config.json'; @@ -59,7 +57,7 @@ var SETTINGS_REPLACE_END = "\\\"IONIC_SETTINGS_STRING_END\\\""; // eslint-disabl var SETTINGS_REPLACEMENT = 'return { get: function(setting) { if (settings[setting]) {' + 'return settings[setting]; } return null; } };'; -IoConfig.isCoreAvailable = function isCoreAvailable() { +function isCoreAvailable() { var deferred = Q.defer(); fs.exists(CORE_FILE, function(exists) { if (exists) { @@ -69,9 +67,9 @@ IoConfig.isCoreAvailable = function isCoreAvailable() { } }); return deferred.promise; -}; +} -IoConfig.doesHaveKey = function doesHaveKey(key) { +function doesHaveKey(key) { var deferred = Q.defer(); fs.readFile(CONFIG_BACKUP, function(err, data) { if (err) { @@ -89,9 +87,9 @@ IoConfig.doesHaveKey = function doesHaveKey(key) { } }); return deferred.promise; -}; +} -IoConfig.listConfig = function listConfig() { +function listConfig() { fs.readFile(CONFIG_BACKUP, function(err, data) { if (err) { if (!err.code === 'ENOENT') { @@ -117,9 +115,9 @@ IoConfig.listConfig = function listConfig() { }); } }); -}; +} -IoConfig.warnMissingData = function warnMissingData() { +function warnMissingData() { var deferred = Q.defer(); var jsonObj = {}; fs.readFile(CONFIG_BACKUP, function(err, data) { @@ -135,9 +133,9 @@ IoConfig.warnMissingData = function warnMissingData() { } }); return deferred.promise; -}; +} -IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { +function writeIoConfig(key, val, set) { var deferred = Q.defer(); if (ALLOWED_CONFIG[key] || key === false) { var type = 'undefined'; @@ -195,7 +193,7 @@ IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { } else { log.info('Building platform config...'); } - IoConfig.isCoreAvailable().then(function(available) { + isCoreAvailable().then(function(available) { if (available) { fs.readFile(CORE_FILE_MIN, function(er, content) { var jsMinFile = String(content); @@ -244,14 +242,13 @@ IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { deferred.reject('Unauthorized configuration value'); } return deferred.promise; -}; +} -IoConfig.getAppId = function getAppId() { +function getAppId() { return IonicProject.load('.').get().app_id; -}; +} -IoConfig.injectIoComponent = function injectIoComponent(set, component) { - var self = this; +function injectIoComponent(set, component) { var deferred = Q.defer(); if (IO_COMPONENTS[component]) { var name = IO_COMPONENTS[component].name; @@ -260,11 +257,11 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { if (IO_COMPONENTS[component].config.length) { IO_COMPONENTS[component].config.forEach(function(item) { - self.doesHaveKey(item.key).then(function(available) { + doesHaveKey(item.key).then(function(available) { if (!available) { - self.writeIoConfig(item.key, item.value, true); + writeIoConfig(item.key, item.value, true); } else if (!set) { - self.writeIoConfig(item.key, item.value, false); + writeIoConfig(item.key, item.value, false); } }); }); @@ -377,20 +374,20 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { }); } return deferred.promise; -}; +} -IoConfig.initIoPlatform = function initIoPlatform(appDirectory, jar) { +function initIoPlatform(appDirectory, jar) { log.info('Initializing app with ionic.io....'); var project = IonicProject.load(appDirectory); try { - return IoConfig.dashInit(project, jar).then(function(key) { + return dashInit(project, jar).then(function(key) { // Save App ID and API key to the io-config - IoConfig.writeIoConfig('app_id', key.app_id, true).then(function() { + writeIoConfig('app_id', key.app_id, true).then(function() { if (key.api_key) { - IoConfig.writeIoConfig('api_key', key.api_key, true).then(function() { - IoConfig.warnMissingData(); + writeIoConfig('api_key', key.api_key, true).then(function() { + warnMissingData(); }, function(error) { log.error('Error saving API key:', error); }); @@ -410,9 +407,9 @@ IoConfig.initIoPlatform = function initIoPlatform(appDirectory, jar) { } catch (ex) { log.error('Error initializing app: %s', ex, {}); } -}; +} -IoConfig.dashInit = function dashInit(project, jar) { +function dashInit(project, jar) { var q = Q.defer(); log.debug('Getting app information from ', settings.IONIC_DASH); @@ -439,4 +436,16 @@ IoConfig.dashInit = function dashInit(project, jar) { } }); return q.promise; +} + +module.exports = { + isCoreAvailable: isCoreAvailable, + doesHaveKey: doesHaveKey, + listConfig: listConfig, + warnMissingData: warnMissingData, + writeIoConfig: writeIoConfig, + getAppId: getAppId, + injectIoComponent: injectIoComponent, + initIoPlatform: initIoPlatform, + dashInit: dashInit }; diff --git a/lib/logging.js b/lib/logging.js index 6472e81..8b84dc6 100644 --- a/lib/logging.js +++ b/lib/logging.js @@ -1,9 +1,6 @@ -var Logging = module.exports; var winston = require('winston'); -Logging.winston = winston; - -Logging.logger = new winston.Logger({ +var logger = new winston.Logger({ exitOnError: false, transports: [ new (winston.transports.Console)({ @@ -14,16 +11,16 @@ Logging.logger = new winston.Logger({ }); // To be used by helpers createDefaultLogger and createLoggerWithFile -Logging.createLogger = function createLogger(transports, level) { +function createLogger(transports, level) { level = level || 'info'; - return Logging.logger = new winston.Logger({ + return logger = new winston.Logger({ exitOnError: false, level: level, transports: transports }); -}; +} -Logging.createDefaultLogger = function createDefaultLogger(level) { +function createDefaultLogger(level) { level = level || 'info'; var transports = [ new (winston.transports.Console)({ @@ -31,20 +28,20 @@ Logging.createDefaultLogger = function createDefaultLogger(level) { showLevel: false }) ]; - return Logging.createLogger(transports, level); -}; + return createLogger(transports, level); +} -Logging.createLoggerWithFile = function createLoggerWithFile(logFilePath, level) { +function createLoggerWithFile(logFilePath, level) { var transports = [ new (winston.transports.File)({ filename: logFilePath, name: 'file' }) ]; - return Logging.createLogger(transports, level); -}; + return createLogger(transports, level); +} -Logging.queryLogs = function queryLogs(searchText, timestamp) { +function queryLogs(searchText, timestamp) { var searchDate = new Date(timestamp) || new Date(); var options = { from: new Date() - 24 * 60 * 60 * 1000, @@ -65,4 +62,13 @@ Logging.queryLogs = function queryLogs(searchText, timestamp) { console.log(results); }); +} + +module.exports = { + winston: winston, + logger: logger, + createLogger: createLogger, + createDefaultLogger: createDefaultLogger, + createLoggerWithFile: createLoggerWithFile, + queryLogs: queryLogs }; diff --git a/lib/login.js b/lib/login.js index 74fac0f..616b80c 100644 --- a/lib/login.js +++ b/lib/login.js @@ -7,22 +7,20 @@ var settings = require('./settings'); var Utils = require('./utils'); var log = require('./logging').logger; -var Login = module.exports; - -Login.jar = null; +var jar = null; // Here we want to look up an existing cookie jar for login if it exists. // If not, resolve false -Login.retrieveLogin = function retrieveLogin() { +function retrieveLogin() { var q = Q.defer(); try { var cookieData = new IonicStore('cookies'); - if (Login.jar) { + if (jar) { // already in memory - q.resolve(Login.jar); + q.resolve(jar); return q.promise; } @@ -38,15 +36,15 @@ Login.retrieveLogin = function retrieveLogin() { // if(!email && !password) { // // did not include cmd line flags, check for existing cookies - var jar = cookieData.get(settings.IONIC_DASH); + var tempJar = cookieData.get(settings.IONIC_DASH); - if (jar && jar.length) { - for (var i in jar) { - if (jar.hasOwnProperty(i)) { - var cookie = jar[i]; + if (tempJar && tempJar.length) { + for (var i in tempJar) { + if (tempJar.hasOwnProperty(i)) { + var cookie = tempJar[i]; if (cookie.key === 'sessionid' && new Date(cookie.expires) > new Date()) { - Login.jar = jar; - q.resolve(Login.jar); + jar = tempJar; + q.resolve(jar); return q.promise; } } @@ -59,9 +57,9 @@ Login.retrieveLogin = function retrieveLogin() { } return q.promise; -}; +} -Login.run = function(ionic, callback) { +function run(ionic, callback) { var self = this; if (!this.email && !this.password) { @@ -103,10 +101,9 @@ Login.run = function(ionic, callback) { // cmd line flag were added, use those instead of a prompt self.requestLogIn(ionic, callback, false); } +} -}; - -Login.requestLogIn = function requestLogin(email, password, saveCookies) { +function requestLogIn(email, password, saveCookies) { var q = Q.defer(); var transformedCookies = null; @@ -133,7 +130,7 @@ Login.requestLogIn = function requestLogin(email, password, saveCookies) { } if (saveCookies) { - transformedCookies = Login.saveCookies(jar); + transformedCookies = saveCookies(jar); } else { try { var jsonString = JSON.stringify(jar.getCookies(settings.IONIC_DASH, null, 2)); @@ -147,9 +144,9 @@ Login.requestLogIn = function requestLogin(email, password, saveCookies) { }); return q.promise; -}; +} -Login.saveCookies = function saveCookies(jar) { +function saveCookies(jar) { var cookies = jar.getCookies(settings.IONIC_DASH); var cookieData; var transformedCookies; @@ -172,15 +169,15 @@ Login.saveCookies = function saveCookies(jar) { } // save in memory - Login.jar = transformedCookies; + jar = transformedCookies; } catch (ex) { log.error('Invalid cookies from jar.getCookies'); } return transformedCookies; -}; +} -Login.getUserInfo = function getUserInfo(jar) { +function getUserInfo(jar) { var q = Q.defer(); var url = [settings.IONIC_DASH_API, 'user?format=json'].join(''); @@ -214,9 +211,9 @@ Login.getUserInfo = function getUserInfo(jar) { } }); return q.promise; -}; +} -Login.getUserApps = function getUserApps(jar) { +function getUserApps(jar) { var q = Q.defer(); var url = [settings.IONIC_DASH_API, 'apps?format=json'].join(''); @@ -247,9 +244,9 @@ Login.getUserApps = function getUserApps(jar) { } }); return q.promise; -}; +} -Login.getDownloadLink = function getDownloadLink(jar, appId) { +function getDownloadLink(jar, appId) { var q = Q.defer(); var url = [settings.IONIC_DASH_API, 'app/', appId, '/updates/download'].join(''); @@ -280,4 +277,14 @@ Login.getDownloadLink = function getDownloadLink(jar, appId) { } }); return q.promise; +} + +module.exports = { + retrieveLogin: retrieveLogin, + run: run, + requestLogIn: requestLogIn, + saveCookies: saveCookies, + getUserInfo: getUserInfo, + getUserApps: getUserApps, + getDownloadLink: getDownloadLink }; diff --git a/lib/package.js b/lib/package.js index 5bd72b8..ce66e51 100644 --- a/lib/package.js +++ b/lib/package.js @@ -13,8 +13,6 @@ var Utils = require('./utils'); var settings = require('./settings'); var log = require('./logging').logger; -var Package = module.exports; - events.on('package-start', function() { var logLevel = log.level; log.level = 'error'; @@ -33,28 +31,28 @@ events.on('package-start', function() { }); -Package.buildAndroidDebug = function(appDirectory, jar, appId, options) { +function buildAndroidDebug(appDirectory, jar, appId, options) { return build(appDirectory, jar, appId, undefined, { platform: 'android', build_mode: 'debug' // eslint-disable-line camelcase }, options); -}; +} -Package.buildAndroidRelease = function(appDirectory, jar, appId, profile, options) { +function buildAndroidRelease(appDirectory, jar, appId, profile, options) { return build(appDirectory, jar, appId, profile, { platform: 'android', build_mode: 'release' // eslint-disable-line camelcase }, options); -}; +} -Package.buildIOS = function(appDirectory, jar, appId, profile, buildMode, options) { +function buildIOS(appDirectory, jar, appId, profile, buildMode, options) { return build(appDirectory, jar, appId, profile, { platform: 'ios', build_mode: buildMode // eslint-disable-line camelcase }, options); -}; +} -Package.listBuilds = function(appId, jar) { +function listBuilds(appId, jar) { var q = Q.defer(); request.get({ @@ -84,9 +82,9 @@ Package.listBuilds = function(appId, jar) { }); return q.promise; -}; +} -Package.getBuild = function(appId, jar, buildId, extraQueryParams) { +function getBuild(appId, jar, buildId, extraQueryParams) { var q = Q.defer(); extraQueryParams = extraQueryParams || {}; @@ -117,10 +115,10 @@ Package.getBuild = function(appId, jar, buildId, extraQueryParams) { }); return q.promise; -}; +} -Package.downloadBuild = function(appId, jar, buildId, downloadDir) { - return Package.getBuild(appId, jar, buildId, { fields: ['url'] }) +function downloadBuild(appId, jar, buildId, downloadDir) { + return getBuild(appId, jar, buildId, { fields: ['url'] }) .then(function(body) { var q = Q.defer(); var build = body.data; @@ -131,7 +129,7 @@ Package.downloadBuild = function(appId, jar, buildId, downloadDir) { return Q.reject(new Error('Cannot download! Build "' + buildId + '" did not finish.')); } - filename = build.name + '.' + Package.determineFileExtensionByPlatform(build.platform); + filename = build.name + '.' + determineFileExtensionByPlatform(build.platform); filepath = path.join(downloadDir, filename); requestProgess(request({ url: build.url })) @@ -151,9 +149,9 @@ Package.downloadBuild = function(appId, jar, buildId, downloadDir) { return q.promise; }); -}; +} -Package.determineFileExtensionByPlatform = function(platform) { +function determineFileExtensionByPlatform(platform) { switch (platform) { case 'android': return 'apk'; @@ -162,7 +160,7 @@ Package.determineFileExtensionByPlatform = function(platform) { } throw new Error('Unknown platform: ' + platform); -}; +} function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { events.emit('package-start'); @@ -415,3 +413,13 @@ function sendToPackageService(appId, jar, formData) { return q.promise; } + +module.exports = { + buildAndroidDebug: buildAndroidDebug, + buildAndroidRelease: buildAndroidRelease, + buildIOS: buildIOS, + listBuilds: listBuilds, + getBuild: getBuild, + downloadBuild: downloadBuild, + determineFileExtensionByPlatform: determineFileExtensionByPlatform +}; diff --git a/lib/ports.js b/lib/ports.js index bc56f58..2398931 100644 --- a/lib/ports.js +++ b/lib/ports.js @@ -11,15 +11,15 @@ var net = require('net'); // ### @basePort {Number} // The lowest port to begin any port search from // -exports.basePort = 8000; +var basePort = 8000; // // ### @basePath {string} // Default path to begin any socket search from // -exports.basePath = '/tmp/portfinder'; +var basePath = '/tmp/portfinder'; -exports.getPort = function(options, callback) { +function getPort(options, callback) { if (!callback) { callback = options; options = {}; @@ -57,118 +57,7 @@ exports.getPort = function(options, callback) { options.server.once('error', onError); options.server.once('listening', onListen); options.server.listen(options.port, options.host); -}; - -// exports.getPorts = function (count, options, callback) { -// if (!callback) { -// callback = options; -// options = {}; -// } -// -// var lastPort = null; -// async.timesSeries(count, function(index, asyncCallback) { -// if (lastPort) { -// options.port = exports.nextPort(lastPort); -// } -// -// exports.getPort(options, function (err, port) { -// if (err) { -// asyncCallback(err); -// } else { -// lastPort = port; -// asyncCallback(null, port); -// } -// }); -// }, callback); -// }; - -// -// ### function getSocket (options, callback) -// #### @options {Object} Settings to use when finding the necessary port -// #### @callback {function} Continuation to respond to when complete. -// Responds with a unbound socket using the specified directory and base -// name on the current machine. -// -// exports.getSocket = function (options, callback) { -// if (!callback) { -// callback = options; -// options = {}; -// } -// -// options.mod = options.mod || 0755; -// options.path = options.path || exports.basePath + '.sock'; -// -// // -// // Tests the specified socket -// // -// function testSocket () { -// fs.stat(options.path, function (err) { -// // -// // If file we're checking doesn't exist (thus, stating it emits ENOENT), -// // we should be OK with listening on this socket. -// // -// if (err) { -// if (err.code == 'ENOENT') { -// callback(null, options.path); -// } -// else { -// callback(err); -// } -// } -// else { -// // -// // This file exists, so it isn't possible to listen on it. Lets try -// // next socket. -// // -// options.path = exports.nextSocket(options.path); -// exports.getSocket(options, callback); -// } -// }); -// } -// -// // -// // Create the target `dir` then test connection -// // against the socket. -// // -// function createAndTestSocket (dir) { -// mkdirp(dir, options.mod, function (err) { -// if (err) { -// return callback(err); -// } -// -// options.exists = true; -// testSocket(); -// }); -// } -// -// // -// // Check if the parent directory of the target -// // socket path exists. If it does, test connection -// // against the socket. Otherwise, create the directory -// // then test connection. -// // -// function checkAndTestSocket () { -// var dir = path.dirname(options.path); -// -// fs.stat(dir, function (err, stats) { -// if (err || !stats.isDirectory()) { -// return createAndTestSocket(dir); -// } -// -// options.exists = true; -// testSocket(); -// }); -// } -// -// // -// // If it has been explicitly stated that the -// // target `options.path` already exists, then -// // simply test the socket. -// // -// return options.exists -// ? testSocket() -// : checkAndTestSocket(); -// }; +} // // ### function nextPort (port) @@ -176,27 +65,13 @@ exports.getPort = function(options, callback) { // Gets the next port in sequence from the // specified `port`. // -exports.nextPort = function(port) { +function nextPort(port) { return port + 1; -}; +} -// -// ### function nextSocket (socketPath) -// #### @socketPath {string} Path to increment from -// Gets the next socket path in sequence from the -// specified `socketPath`. -// -// exports.nextSocket = function (socketPath) { -// var dir = path.dirname(socketPath), -// name = path.basename(socketPath, '.sock'), -// match = name.match(/^([a-zA-z]+)(\d*)$/i), -// index = parseInt(match[2]), -// base = match[1]; -// -// if (isNaN(index)) { -// index = 0; -// } -// -// index += 1; -// return path.join(dir, base + index + '.sock'); -// }; +module.exports = { + basePort: basePort, + basePath: basePath, + getPort: getPort, + nextPort: nextPort +}; diff --git a/lib/project.js b/lib/project.js index 1192576..36fe5d5 100644 --- a/lib/project.js +++ b/lib/project.js @@ -2,7 +2,7 @@ var fs = require('fs'); var path = require('path'); var log = require('./logging').logger; -var Project = module.exports; +var Project = {}; Project.PROJECT_FILE = 'ionic.config.json'; Project.OLD_PROJECT_FILE = 'ionic.project'; @@ -13,24 +13,24 @@ Project.PROJECT_DEFAULT = { }; Project.data = null; -Project.wrap = function wrap(appDirectory, data) { +function wrap(appDirectory, data) { return { get: function get(key) { - return Project.get(data, key); + return get(data, key); }, remove: function remove(key) { - return Project.remove(data, key); + return remove(data, key); }, set: function set(key, value) { - return Project.set(data, key, value); + return set(data, key, value); }, save: function save() { - return Project.save(appDirectory, data); + return save(appDirectory, data); } }; -}; +} -Project.load = function load(appDirectory) { +function load(appDirectory) { if (!appDirectory) { // Try to grab cwd @@ -79,23 +79,23 @@ Project.load = function load(appDirectory) { } var parts = path.join(appDirectory, '.').split(path.sep); var dirname = parts[parts.length - 1]; - Project.create(appDirectory, dirname); - Project.save(appDirectory, data); + create(appDirectory, dirname); + save(appDirectory, data); } - return Project.wrap(appDirectory, data); -}; + return wrap(appDirectory, data); +} -Project.create = function create(appDirectory, name) { +function create(appDirectory, name) { var data = Project.PROJECT_DEFAULT; if (name) { - Project.set(data, 'name', name); + set(data, 'name', name); } - return Project.wrap(appDirectory, data); -}; + return wrap(appDirectory, data); +} -Project.save = function save(appDirectory, data) { +function save(appDirectory, data) { if (!data) { throw new Error('No data passed to Project.save'); } @@ -108,9 +108,9 @@ Project.save = function save(appDirectory, data) { } catch (e) { log.error('Unable to save settings file:', e); } -}; +} -Project.get = function get(data, key) { +function get(data, key) { if (!data) { return null; } @@ -119,18 +119,28 @@ Project.get = function get(data, key) { } else { return data; } -}; +} -Project.set = function set(data, key, value) { +function set(data, key, value) { if (!data) { data = Project.PROJECT_DEFAULT; } data[key] = value; -}; +} -Project.remove = function remove(data, key) { +function remove(data, key) { if (!data) { data = Project.PROJECT_DEFAULT; } data[key] = ''; +} + +module.exports = { + wrap: wrap, + load: load, + create: create, + save: save, + get: get, + set: set, + remove: remove }; diff --git a/lib/resources.js b/lib/resources.js index 28dde3b..b770c63 100644 --- a/lib/resources.js +++ b/lib/resources.js @@ -40,7 +40,6 @@ var Settings = { }; var Platforms = { - android: { icon: { images: [ diff --git a/lib/security.js b/lib/security.js index 279d826..b74d98f 100644 --- a/lib/security.js +++ b/lib/security.js @@ -4,9 +4,7 @@ var Utils = require('./utils'); var settings = require('./settings'); var log = require('./logging').logger; -var Security = module.exports; - -Security.addProfile = function(appId, jar, name) { +function addProfile(appId, jar, name) { var q = Q.defer(); request.post({ @@ -45,9 +43,9 @@ Security.addProfile = function(appId, jar, name) { }); return q.promise; -}; +} -Security.listProfiles = function(appId, jar) { +function listProfiles(appId, jar) { var q = Q.defer(); request.get({ @@ -78,9 +76,9 @@ Security.listProfiles = function(appId, jar) { }); return q.promise; -}; +} -Security.getProfile = function(appId, jar, tag) { +function getProfile(appId, jar, tag) { var q = Q.defer(); request.get({ @@ -115,9 +113,9 @@ Security.getProfile = function(appId, jar, tag) { }); return q.promise; -}; +} -Security.addAndroidCredentials = function(appId, jar, profileTag, keystoreFileStream, +function addAndroidCredentials(appId, jar, profileTag, keystoreFileStream, keystorePassword, keyAlias, keyPassword) { return sendCredentials(appId, jar, profileTag, { type: 'android', @@ -126,9 +124,9 @@ Security.addAndroidCredentials = function(appId, jar, profileTag, keystoreFileSt key_alias: keyAlias, // eslint-disable-line camelcase key_password: keyPassword // eslint-disable-line camelcase }); -}; +} -Security.addIOSCredentials = function(appId, jar, profileTag, certificateFileStream, +function addIOSCredentials(appId, jar, profileTag, certificateFileStream, certificatePassword, provisioningProfileFileStream) { return sendCredentials(appId, jar, profileTag, { type: 'ios', @@ -136,7 +134,7 @@ Security.addIOSCredentials = function(appId, jar, profileTag, certificateFileStr cert_password: certificatePassword, // eslint-disable-line camelcase provisioning_profile_file: provisioningProfileFileStream // eslint-disable-line camelcase }); -}; +} function sendCredentials(appId, jar, profileTag, formData) { var q = Q.defer(); @@ -175,3 +173,11 @@ function sendCredentials(appId, jar, profileTag, formData) { return q.promise; } + +module.exports = { + addProfile: addProfile, + listProfiles: listProfiles, + getProfile: getProfile, + addAndroidCredentials: addAndroidCredentials, + addIOSCredentials: addIOSCredentials +}; diff --git a/lib/serve.js b/lib/serve.js index 1a81ca2..e9870a2 100644 --- a/lib/serve.js +++ b/lib/serve.js @@ -30,7 +30,7 @@ var DEFAULT_LIVE_RELOAD_PORT = 35729; var IONIC_LAB_URL = '/ionic-lab'; var IONIC_ANGULAR_URL = '/angular.min.js'; -Serve.listenForServerCommands = function listenForServerCommands(options) { +function listenForServerCommands(options) { var readline = require('readline'); process.on('SIGINT', function() { @@ -77,23 +77,23 @@ Serve.listenForServerCommands = function listenForServerCommands(options) { } else { events.removeAllListeners('consoleLog'); } - Serve._goToUrl('/?restart=' + Math.floor((Math.random() * 899999) + 100000), options); + _goToUrl('/?restart=' + Math.floor((Math.random() * 899999) + 100000), options); } else if (input === 'serverlogs' || input === 's') { options.printServerLogs = !options.printServerLogs; log.info('Server log output: ' + (options.printServerLogs ? 'enabled' : 'disabled')); } else if (input.match(/^go\([+\-]?[0-9]{1,9}\)$/)) { - Serve._goToHistory(input, options); + _goToHistory(input, options); } else if (input === 'help' || input === 'h') { - Serve.printCommandTips(); + printCommandTips(); } else if (input === 'clear' || input === 'clr') { process.stdout.write('\u001b[2J\u001b[0;0H'); } else { log.error('\nInvalid ionic server command'); - Serve.printCommandTips(); + printCommandTips(); } // log.debug('input: ', input); @@ -105,10 +105,10 @@ Serve.listenForServerCommands = function listenForServerCommands(options) { } process.exit(0); }); -}; +} // isIonicServer = true when serving www directory, false when live reload -Serve.checkPorts = function(isIonicServer, testPort, testHost, options) { +function checkPorts(isIonicServer, testPort, testHost, options) { log.debug('Serve.checkports isIonicServer', isIonicServer, 'testPort:', testPort, 'testHost', testHost, 'options:', options); var q = Q.defer(); @@ -138,10 +138,10 @@ Serve.checkPorts = function(isIonicServer, testPort, testHost, options) { }); return q.promise; -}; +} // argv should be parsed out and put into a nice hash before getting here. -Serve.loadSettings = function loadSettings(argv, project) { +function loadSettings(argv, project) { var errorMessage; if (!argv) { @@ -208,10 +208,10 @@ Serve.loadSettings = function loadSettings(argv, project) { } return options; -}; +} -Serve.printCommandTips = function() { +function printCommandTips() { log.info('Ionic server commands, enter:'); log.info(' restart'.cyan + ' or ' + 'r'.cyan + ' to restart the client app from the root'); log.info(' goto'.cyan + ' or ' + 'g'.cyan + ' and a url to have the app navigate to the given url'); @@ -219,9 +219,9 @@ Serve.printCommandTips = function() { log.info(' serverlogs'.cyan + ' or ' + 's'.cyan + ' to enable/disable server log output'); log.info(' quit'.cyan + ' or ' + 'q'.cyan + ' to shutdown the server and exit'); log.info(''); -}; +} -Serve.openBrowser = function openBrowser(options) { +function openBrowser(options) { if (options.launchLab || options.launchBrowser) { var open = require('open'); var openUrl = options.launchLab ? @@ -242,9 +242,9 @@ Serve.openBrowser = function openBrowser(options) { log.error('Error opening the browser - ', ex); } } -}; +} -Serve.checkForDocumentRoot = function checkForDocumentRoot(options) { +function checkForDocumentRoot(options) { if (!fs.existsSync(path.join(options.appDirectory, options.documentRoot))) { if (options.createDocumentRoot) { fs.mkdirSync(options.documentRoot); @@ -256,9 +256,9 @@ Serve.checkForDocumentRoot = function checkForDocumentRoot(options) { } return true; -}; +} -Serve.runLivereload = function runLivereload(options, app) { +function runLivereload(options, app) { var q = Q.defer(); log.debug('Running Live Reload with options', options); @@ -307,9 +307,9 @@ Serve.runLivereload = function runLivereload(options, app) { } return q.promise; -}; +} -Serve.setupProxy = function setupProxy(options, app) { +function setupProxy(options, app) { if (options.useProxy) { for (var x = 0; x < options.proxies.length; x += 1) { @@ -326,9 +326,9 @@ Serve.setupProxy = function setupProxy(options, app) { log.info('Proxy added:', proxy.path + ' => ' + url.format(proxy.proxyUrl)); } } -}; +} -Serve.startServer = function startServer(options, app) { +function startServer(options, app) { options.devServer = Serve.host(options.address, options.port); log.debug('Starting server at host address - ' + options.devServer); var rootDirectory = path.join(options.appDirectory, options.documentRoot); @@ -472,9 +472,9 @@ Serve.startServer = function startServer(options, app) { } log.info('√ Running dev server: ', options.devServer.cyan); -}; +} -Serve.start = function start(options) { +function start(options) { if (!options) { throw 'You cannot serve without options.'; @@ -528,14 +528,14 @@ Serve.start = function start(options) { log.error(msg); throw msg; } -}; +} -Serve.showFinishedServeMessage = function showFinishedServeMessage(options) { +function showFinishedServeMessage(options) { Serve.printCommandTips(options); Serve.listenForServerCommands(options); -}; +} -Serve.serverLog = function(req, msg, options) { +function serverLog(req, msg, options) { if (options.printServerLogs) { var log = 'serve '; @@ -556,10 +556,10 @@ Serve.serverLog = function(req, msg, options) { events.emit('serverlog', log); } -}; +} -Serve.consoleLog = function(req) { +function consoleLog(req) { var body = ''; req.on('data', function(data) { @@ -623,7 +623,7 @@ Serve.consoleLog = function(req) { events.emit('consoleLog', msg); } catch (e) {} // eslint-disable-line no-empty }); -}; +} function getPlatformUrl(req) { @@ -756,7 +756,7 @@ function injectPlatformScript(html, platformOverride) { return html; } -Serve._changed = function(filePath, options) { +function _changed(filePath, options) { // Cleanup the path a bit // var pwd = process.cwd(); @@ -774,23 +774,23 @@ Serve._changed = function(filePath, options) { } Serve._postToLiveReload([filePath], options); -}; +} -Serve._goToUrl = function(url, options) { +function _goToUrl(url, options) { log.info('Loading: ' + url); Serve._postToLiveReload(['__ionic_goto_url__' + url], options); -}; +} -Serve._goToHistory = function(goHistory, options) { +function _goToHistory(goHistory, options) { goHistory = goHistory.replace('go(', '').replace(')', ''); log.info('History Go: ' + goHistory); Serve._postToLiveReload(['__ionic_history_go__' + goHistory], options); -}; +} -Serve._postToLiveReload = function(files, options) { +function _postToLiveReload(files, options) { var postUrl = [options.liveReloadServer, '/changed'].join(''); request.post(postUrl, { path: '/changed', @@ -803,10 +803,10 @@ Serve._postToLiveReload = function(files, options) { log.error('Unable to update live reload: %s', err, {}); } }); -}; +} -Serve.getAddress = function(options) { +function getAddress(options) { var q = Q.defer(); try { var addresses = []; @@ -953,9 +953,9 @@ Serve.getAddress = function(options) { } return q.promise; -}; +} -Serve.host = function host(address, port) { +function host(address, port) { var platformName = require('os').platform(); if ((platformName.indexOf('win') !== -1 && platformName !== 'darwin') && @@ -966,10 +966,10 @@ Serve.host = function host(address, port) { } var hostAddress = ['http://', address, ':', port].join(''); return hostAddress; -}; +} -Serve.stopServer = function stopServer() { +function stopServer() { if (runningServer) { runningServer.close(); lrServer.close(); @@ -977,4 +977,27 @@ Serve.stopServer = function stopServer() { } else { log.info('Server not running'); } +} + +module.exports = { + listenForServerCommands: listenForServerCommands, + checkPorts: checkPorts, + loadSettings: loadSettings, + printCommandTips: printCommandTips, + openBrowser: openBrowser, + checkForDocumentRoot: checkForDocumentRoot, + runLivereload: runLivereload, + setupProxy: setupProxy, + startServer: startServer, + start: start, + showFinishedServeMessage: showFinishedServeMessage, + serverLog: serverLog, + consoleLog: consoleLog, + _changed: _changed, + _goToUrl: _goToUrl, + _goToHistory: _goToHistory, + _postToLiveReload: _postToLiveReload, + getAddress: getAddress, + host: host, + stopServer: stopServer }; diff --git a/lib/settings.js b/lib/settings.js index 81d178f..7543721 100644 --- a/lib/settings.js +++ b/lib/settings.js @@ -1,7 +1,9 @@ -var Settings = module.exports; +var IONIC_DASH = 'https://apps.ionic.io'; +var IONIC_DASH_API = IONIC_DASH + '/api/v1/'; +var PRIVATE_PATH = '.ionic'; -Settings.IONIC_DASH = 'https://apps.ionic.io'; - -// Settings.IONIC_DASH = 'http://localhost:8000'; -Settings.IONIC_DASH_API = Settings.IONIC_DASH + '/api/v1/'; -Settings.PRIVATE_PATH = '.ionic'; +module.exports = { + IONIC_DASH: IONIC_DASH, + IONIC_DASH_API: IONIC_DASH_API, + PRIVATE_PATH: PRIVATE_PATH +}; diff --git a/lib/share.js b/lib/share.js index d5fb1ff..664cc02 100644 --- a/lib/share.js +++ b/lib/share.js @@ -6,9 +6,7 @@ var IonicProject = require('./project'); var Settings = require('./settings'); var log = require('./logging').logger; -var Share = module.exports; - -Share.shareApp = function shareApp(appDirectory, jar, email) { +function shareApp(appDirectory, jar, email) { var q = Q.defer(); @@ -46,4 +44,8 @@ Share.shareApp = function shareApp(appDirectory, jar, email) { }); return q.promise; +} + +module.exports = { + shareApp: shareApp }; diff --git a/lib/start.js b/lib/start.js index e94fda4..6ede362 100644 --- a/lib/start.js +++ b/lib/start.js @@ -23,7 +23,6 @@ var IonicResources = require('./resources'); var State = require('./state'); var seedType = 'ionic-starter'; -var Start = module.exports; var IONIC_DASH = 'https://apps.ionic.io'; var IONIC_CREATOR_API_URL = 'https://creator.ionic.io/api/v1'; @@ -47,7 +46,7 @@ var V2_STARTERS = { tutorial: { repoName: 'ionic2-starter-tutorial' } }; -Start.runSpawnCommand = function runSpawnCommand(cmd, args) { +function runSpawnCommand(cmd, args) { var q = Q.defer(); var command = cmd + args.join(' '); var spawn = require('cross-spawn-async'); @@ -73,7 +72,7 @@ Start.runSpawnCommand = function runSpawnCommand(cmd, args) { }); return q.promise; -}; +} // Options for startApp: // { @@ -84,7 +83,7 @@ Start.runSpawnCommand = function runSpawnCommand(cmd, args) { // template: 'tabs', // targetPath: '/User/Path/Development/' // } -Start.startApp = function startApp(options) { +function startApp(options) { if (typeof options != 'object' || typeof options == 'undefined') { throw new Error('You cannot start an app without options'); } @@ -101,24 +100,24 @@ Start.startApp = function startApp(options) { log.info(createMessage); - return Start.fetchWrapper(options) + return fetchWrapper(options) .then(function() { - return Start.fetchSeed(options); + return fetchSeed(options); }) .then(function() { if (!options.skipNpm) { log.info('Installing npm packages...'); - return Start.runSpawnCommand('npm', ['install']); + return runSpawnCommand('npm', ['install']); } }) .then(function() { - return Start.loadAppSetup(options); + return loadAppSetup(options); }) .then(function(appSetup) { if (options.isCordovaProject && !options.isGui) { - return Start.initCordova(options, appSetup); + return initCordova(options, appSetup); } else if (options.isCordovaProject && options.isGui) { - return Start.initCordovaFromGui(options, appSetup); + return initCordovaFromGui(options, appSetup); } }) .catch(function(ex) { @@ -129,7 +128,7 @@ Start.startApp = function startApp(options) { if (options.isCordovaProject) { // Check if iOS - if so, add platform iOS - return Start.addDefaultPlatforms(options); + return addDefaultPlatforms(options); } }) .catch(function(ex) { @@ -142,12 +141,12 @@ Start.startApp = function startApp(options) { }) .then(function() { if (options.isCordovaProject) { - return Start.updateConfigXml(options.targetPath, options.packageName, + return updateConfigXml(options.targetPath, options.packageName, options.appName, options.ios, options.android); } }) .then(function() { - return Start.finalize(options); + return finalize(options); }) .catch(function(err) { log.error('Error Initializing app: %s', err, {}); @@ -156,9 +155,9 @@ Start.startApp = function startApp(options) { .fin(function() { return 'Completed successfully'; }); -}; +} -Start.addDefaultPlatforms = function addDefaultPlatforms(options) { +function addDefaultPlatforms(options) { var currOs = os.type().toLowerCase(); if (currOs === 'darwin') { @@ -175,9 +174,9 @@ Start.addDefaultPlatforms = function addDefaultPlatforms(options) { } else { return Q(); } -}; +} -Start.fetchWrapper = function fetchWrapper(options) { +function fetchWrapper(options) { var q = Q.defer(); var wrapperRepoName = options.v2 ? 'ionic2-app-base' : 'ionic-app-base'; var branchName = (options.v2 && options.typescript) ? 'typescript' : 'master'; @@ -209,36 +208,36 @@ Start.fetchWrapper = function fetchWrapper(options) { }); return q.promise; -}; +} // Tested -Start.fetchSeed = function(options) { +function fetchSeed(options) { // Codepen: http://codepen.io/ionic/pen/GpCst if (/\/\/codepen.io\//i.test(options.template)) { seedType = 'codepen'; - return Start.fetchCodepen(options); + return fetchCodepen(options); } if (/plnkr.co\//i.test(options.template)) { seedType = 'plnkr'; - return Start.fetchPlnkr(options); + return fetchPlnkr(options); } if (/creator:/i.test(options.template)) { seedType = 'creator'; - return Start.fetchCreatorApp(options); + return fetchCreatorApp(options); } // Github URL: http://github.com/myrepo/ if (/\/\/github.com\//i.test(options.template)) { seedType = 'github'; - return Start.fetchGithubStarter(options, options.template); + return fetchGithubStarter(options, options.template); } // Fix for downloading zip files: https://github.com/driftyco/ionic-cli/issues/526 if (options.zipFileDownload) { - return Start.fetchZipStarter(options); + return fetchZipStarter(options); } // Local Directory: /User/starterapp @@ -247,16 +246,15 @@ Start.fetchSeed = function(options) { // TODO: seedType - how to pass back? seedType = 'local'; - return Start.fetchLocalStarter(options); + return fetchLocalStarter(options); } // Ionic Github Repo seedType = 'ionic-starter'; - return Start.fetchIonicStarter(options); -}; + return fetchIonicStarter(options); +} -// Not Tested -Start.loadAppSetup = function loadAppSetup(options) { +function loadAppSetup(options) { var appSetup = DEFAULT_APP; var appJsonPath = path.join(options.targetPath, 'www', 'app.json'); @@ -270,10 +268,9 @@ Start.loadAppSetup = function loadAppSetup(options) { } return appSetup; -}; +} -// Not Tested -Start.fetchCreatorApp = function(options) { +function fetchCreatorApp(options) { var cookies = new IonicStore('cookies').get('https://apps.ionic.io'); var sessionId; @@ -329,9 +326,9 @@ Start.fetchCreatorApp = function(options) { }); return Q.all([q]); } -}; +} -Start.fetchCodepen = function(options) { +function fetchCodepen(options) { var codepenUrl = options.template.split('?')[0].split('#')[0]; var wwwPath = path.join(options.targetPath, 'www'); @@ -366,7 +363,7 @@ Start.fetchCodepen = function(options) { html = html.replace(/<\/head>/i, '\n' + resources); - html = Start.convertTemplates(html); + html = convertTemplates(html); fs.writeFileSync(path.join(wwwPath, 'index.html'), html, 'utf8'); } @@ -401,10 +398,10 @@ Start.fetchCodepen = function(options) { }); return Q.all([qHTML.promise, qCSS.promise, qJS.promise]); -}; +} -Start.convertTemplates = function(html, targetPath) { +function convertTemplates(html, targetPath) { var templates = []; try { @@ -458,10 +455,10 @@ Start.convertTemplates = function(html, targetPath) { } catch (e) {} // eslint-disable-line no-empty return html; -}; +} -Start.fetchLocalStarter = function(options) { +function fetchLocalStarter(options) { var q = Q.defer(); try { @@ -488,10 +485,10 @@ Start.fetchLocalStarter = function(options) { shelljs.cd(options.targetPath); return q.promise; -}; +} -Start.fetchIonicStarter = function(options) { +function fetchIonicStarter(options) { var repoName; if (options.v2) { var starter = V2_STARTERS[options.template]; @@ -508,11 +505,11 @@ Start.fetchIonicStarter = function(options) { // Get the URL for the starter project repo: var repoUrl = 'https://github.com/driftyco/' + repoName; - return Start.fetchGithubStarter(options, repoUrl); -}; + return fetchGithubStarter(options, repoUrl); +} -Start.fetchGithubStarter = function(options, repoUrl) { +function fetchGithubStarter(options, repoUrl) { var q = Q.defer(); // https://github.com/driftyco/ionic-starter-tabs/ @@ -563,9 +560,9 @@ Start.fetchGithubStarter = function(options, repoUrl) { }); return q.promise; -}; +} -Start.fetchZipStarter = function fetchZipStarter(options) { +function fetchZipStarter(options) { var q = Q.defer(); var repoFolderName = 'zipFileDownload'; @@ -598,9 +595,9 @@ Start.fetchZipStarter = function fetchZipStarter(options) { }); return q.promise; -}; +} -Start.fetchPlnkr = function fetchPlnkr(options) { +function fetchPlnkr(options) { var q = Q.defer(); var plnkrUrl = options.template.split('?')[0].split('#')[0]; @@ -657,10 +654,10 @@ Start.fetchPlnkr = function fetchPlnkr(options) { }); return q.promise; -}; +} // New initCordova method intended for GUI - to use cordova-lib commands instead of CLI. -Start.initCordovaFromGui = function initCordovaFromGui(options, appSetup) { +function initCordovaFromGui(options, appSetup) { var q = Q.defer(); log.debug('Initializing Cordova for Gui'); @@ -709,9 +706,9 @@ Start.initCordovaFromGui = function initCordovaFromGui(options, appSetup) { } return q.promise; -}; +} -Start.initCordovaNoCli = function initCordova(options, appSetup) { +function initCordovaNoCli(options, appSetup) { try { // console.log('running initCordovaNoCli'); @@ -738,9 +735,9 @@ Start.initCordovaNoCli = function initCordova(options, appSetup) { } catch (ex) { Utils.fail(ex); } -}; +} -Start.initCordova = function(options, appSetup) { +function initCordova(options, appSetup) { var q; try { if (!options.isCordovaProject) { @@ -757,7 +754,7 @@ Start.initCordova = function(options, appSetup) { if (!Utils.cordovaInstalled()) { // console.log('utils cordova not installed'); - return Start.initCordovaNoCli(options, appSetup); + return initCordovaNoCli(options, appSetup); } q = Q.defer(); @@ -815,7 +812,6 @@ Start.initCordova = function(options, appSetup) { } }); - // Start.updateConfigXml(options.targetPath, options.packageName, options.appName, options.ios, options.android); } catch (ex) { log.debug('Exception caught in initCordova: %s', ex, {}); log.debug('Exception details: %s', ex.stack, {}); @@ -823,9 +819,9 @@ Start.initCordova = function(options, appSetup) { } return q.promise; -}; +} -Start.updateConfigXml = function(targetPath, packageName, appName) { +function updateConfigXml(targetPath, packageName, appName) { var q = Q.defer(); try { @@ -872,10 +868,10 @@ Start.updateConfigXml = function(targetPath, packageName, appName) { } return q.promise; -}; +} -Start.updateLibFiles = function(libPath) { +function updateLibFiles(libPath) { // create a symlink if the path exists locally var libSymlinkPath = path.resolve(libPath); @@ -1012,9 +1008,9 @@ Start.updateLibFiles = function(libPath) { fs.writeFileSync(indexPath, html, 'utf8'); } catch (e) {} // eslint-disable-line no-empty -}; +} -Start.promptLogin = function() { +function promptLogin() { var q = Q.defer(); var ionicConfig = new IonicStore('ionic.config'); @@ -1067,9 +1063,9 @@ Start.promptLogin = function() { }); return q.promise; -}; +} -Start.finalize = function(options) { +function finalize(options) { try { var packageFilePath = path.join(options.targetPath, 'package.json'); var packageData = require(packageFilePath); @@ -1130,16 +1126,9 @@ Start.finalize = function(options) { if (options.isCordovaProject) { State.saveState(process.cwd(), { plugins: true }); } +} - // Start.printQuickHelp(); - - // Start.ionic.printNewsUpdates(true).then(function() { - // self.promptLogin(); - // }); - -}; - -Start.printQuickHelp = function(options) { +function printQuickHelp(options) { log.info('\n♬ ♫ ♬ ♫ Your Ionic app is ready to go! ♬ ♫ ♬ ♫'.bold); log.info('\nMake sure to cd into your new app directory:'.bold); log.info(' cd ' + options.appName); @@ -1151,9 +1140,9 @@ Start.printQuickHelp = function(options) { log.info(' ionic run android'); log.info('\nTo test your app on a device easily, try Ionic View:'.bold); log.info(' http://view.ionic.io'); -}; +} -Start.promptForOverwrite = function promptForOverwrite(targetPath) { +function promptForOverwrite(targetPath) { var q = Q.defer(); log.warn('Directory already exists:', targetPath.cyan); log.info('Would you like to overwrite the directory with this new project?'); @@ -1192,5 +1181,30 @@ Start.promptForOverwrite = function promptForOverwrite(targetPath) { }); return q.promise; +} + +module.exports = { + runSpawnCommand: runSpawnCommand, + startApp: startApp, + addDefaultPlatforms: addDefaultPlatforms, + fetchWrapper: fetchWrapper, + fetchSeed: fetchSeed, + loadAppSetup: loadAppSetup, + fetchCreatorApp: fetchCreatorApp, + fetchCodepen: fetchCodepen, + convertTemplates: convertTemplates, + fetchLocalStarter: fetchLocalStarter, + fetchIonicStarter: fetchIonicStarter, + fetchGithubStarter: fetchGithubStarter, + fetchZipStarter: fetchZipStarter, + fetchPlnkr: fetchPlnkr, + initCordovaFromGui: initCordovaFromGui, + initCordovaNoCli: initCordovaNoCli, + initCordova: initCordova, + updateConfigXml: updateConfigXml, + updateLibFiles: updateLibFiles, + promptLogin: promptLogin, + finalize: finalize, + printQuickHelp: printQuickHelp, + promptForOverwrite: promptForOverwrite }; - diff --git a/lib/state.js b/lib/state.js index 2d7d72e..44f6ca9 100644 --- a/lib/state.js +++ b/lib/state.js @@ -6,22 +6,20 @@ var Utils = require('./utils'); var _ = require('underscore'); var log = require('./logging').logger; -var State = module.exports; - shelljs.config.silent = true; -State.readInPackageJson = function readInPackageJson(jsonPath) { +function readInPackageJson(jsonPath) { return require(jsonPath); -}; +} -State.getPackageJson = function getPackageJson(appDirectory) { +function getPackageJson(appDirectory) { var packageJsonPath = path.join(appDirectory, 'package.json'); var packageJson = null; try { // packageJson = require(packageJsonPath); - packageJson = State.readInPackageJson(packageJsonPath); + packageJson = readInPackageJson(packageJsonPath); if (!packageJson.cordovaPlugins) { packageJson.cordovaPlugins = []; } @@ -35,14 +33,14 @@ State.getPackageJson = function getPackageJson(appDirectory) { } return packageJson; -}; +} -State.getPackageJsonReadStream = function(appDirectory) { +function getPackageJsonReadStream(appDirectory) { var packageJsonPath = path.join(appDirectory, 'package.json'); return fs.createReadStream(packageJsonPath); -}; +} -State.addOrUpdatePluginToPackageJson = function addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo) { +function addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo) { var existingPlugin; if (typeof pluginInfo === 'undefined') { @@ -62,25 +60,25 @@ State.addOrUpdatePluginToPackageJson = function addOrUpdatePluginToPackageJson(p if (!existingPlugin) { packageJson.cordovaPlugins.push(pluginInfo); } -}; +} -State.saveState = function saveState(appDirectory) { +function saveState(appDirectory) { log.info('Saving your Ionic app state of platforms and plugins'); - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); try { - State.saveExistingPlatforms(appDirectory, packageJson); + saveExistingPlatforms(appDirectory, packageJson); log.info('Saved platform'); - State.saveExistingPlugins(appDirectory, packageJson); + saveExistingPlugins(appDirectory, packageJson); log.info('Saved plugins'); - State.savePackageJson(appDirectory, packageJson); + savePackageJson(appDirectory, packageJson); log.info('Saved package.json'); } catch (ex) { log.error('There was an error saving your current Ionic setup'); log.error(ex); } -}; +} -State.platformExists = function platformExists(appDirectory, platform) { +function platformExists(appDirectory, platform) { var platformExists = false; var platformPath; var platformStats; @@ -95,9 +93,9 @@ State.platformExists = function platformExists(appDirectory, platform) { } } catch (ex) {} // eslint-disable-line no-empty return platformExists; -}; +} -State.saveExistingPlatforms = function saveExistingPlatforms(appDirectory, packageJson) { +function saveExistingPlatforms(appDirectory, packageJson) { var pp = path.join(appDirectory, 'platforms'), platforms = [], platformPath, @@ -124,7 +122,7 @@ State.saveExistingPlatforms = function saveExistingPlatforms(appDirectory, packa try { var versionPath = path.join(appDirectory, platform, 'cordova', 'version'); - var version = State.getPlatformVersion(versionPath); + var version = getPlatformVersion(versionPath); var locator = platform; // Check to see if its crosswalk @@ -155,9 +153,9 @@ State.saveExistingPlatforms = function saveExistingPlatforms(appDirectory, packa log.info('There was an error trying to save your existing state', ex); } }); -}; +} -State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJson) { +function saveExistingPlugins(appDirectory, packageJson) { // Lets try just relying on the fetch.json file // this file lists all plugins with where they come from, etc @@ -212,7 +210,7 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs } pluginXmlPath = path.join(appDirectory, 'plugins', pluginId, 'plugin.xml'); - pluginXml = State.getXmlData(pluginXmlPath); + pluginXml = getXmlData(pluginXmlPath); preferences = pluginXml.plugin.preference; @@ -233,7 +231,7 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs // log.info('we have avariables to look at:', variableList) // var features = configXmlData.widget.feature; // events.emit('log', 'features', features) - var pluginPreferences = State.getPluginPreferences(fetchJson, pluginId); + var pluginPreferences = getPluginPreferences(fetchJson, pluginId); // why we are searching for plugin params from the config xml? @@ -283,9 +281,9 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs log.error('There was no fetch.json file available to restore plugin information from.'); log.error('Restoring plugins from scanning the plugins folder is still being worked on.'); } -}; // Closes saveExistingPlugins +} // Closes saveExistingPlugins -State.getXmlData = function getXmlData(xmlPath) { +function getXmlData(xmlPath) { var xml2js = require('xml2js'); var xmlString = fs.readFileSync(xmlPath, { encoding: 'utf8' }); var xmlData; @@ -302,9 +300,9 @@ State.getXmlData = function getXmlData(xmlPath) { }); return xmlData; -}; +} -State.getPlatformVersion = function getPlatformVersion(path) { +function getPlatformVersion(path) { var result = shelljs.exec(['node', path].join(' '), { silent: true }); if (result.code !== 0) { return ''; @@ -313,11 +311,9 @@ State.getPlatformVersion = function getPlatformVersion(path) { // log.info('Version for path:', path, version) return version.replace(/\n/g, ''); -}; +} -State.addOrUpdatePlatformToPackageJson = function addOrUpdatePlatformToPackageJson(packageJson, - platformId, - platformInfo) { +function addOrUpdatePlatformToPackageJson(packageJson, platformId, platformInfo) { // var platformExists = _.findWhere(packageJson.cordovaPlatforms, {platform: platformId}); var existingPlatform; @@ -359,9 +355,9 @@ State.addOrUpdatePlatformToPackageJson = function addOrUpdatePlatformToPackageJs // platformExists.platform = platform // platformExists.locator = locator // } -}; +} -State.savePlatform = function savePlatform(appDirectory, locator) { +function savePlatform(appDirectory, locator) { log.debug('State.savePlatform', appDirectory, locator); // Locator may be: @@ -373,13 +369,13 @@ State.savePlatform = function savePlatform(appDirectory, locator) { // var locator = platformArgs._[2]; var platform = 'ios'; var version; - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); // Test to see if its just ios or android if (locator === 'ios' || locator === 'android') { platform = locator; - State.addOrUpdatePlatformToPackageJson(packageJson, platform); - return State.savePackageJson(appDirectory, packageJson); + addOrUpdatePlatformToPackageJson(packageJson, platform); + return savePackageJson(appDirectory, packageJson); } @@ -401,11 +397,11 @@ State.savePlatform = function savePlatform(appDirectory, locator) { locator: locator }; - State.addOrUpdatePlatformToPackageJson(packageJson, platform, platformInfo); - State.savePackageJson(appDirectory, packageJson); -}; + addOrUpdatePlatformToPackageJson(packageJson, platform, platformInfo); + savePackageJson(appDirectory, packageJson); +} -State.savePackageJson = function savePackageJson(appDirectory, packageJsonData) { +function savePackageJson(appDirectory, packageJsonData) { log.debug('State.savePackageJson', appDirectory, packageJsonData); try { var packageJsonPath = path.join(appDirectory, 'package.json'); @@ -413,9 +409,9 @@ State.savePackageJson = function savePackageJson(appDirectory, packageJsonData) } catch (e) { log.error(('Error saving ' + packageJsonPath + ': %s').bold, e, {}); } -}; +} -State.restoreState = function restoreState(appDirectory, options) { +function restoreState(appDirectory, options) { log.debug('State.restoreState', appDirectory, options); if (!options || !appDirectory) { @@ -431,13 +427,13 @@ State.restoreState = function restoreState(appDirectory, options) { // var packageJsonPath = path.join(appDirectory, 'package.json'); // var packageJson = require(packageJsonPath); - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); var restorePromise; if (options.platforms) { log.info('Restoring Platforms\n'); - restorePromise = State.restorePlatforms(appDirectory, packageJson) + restorePromise = restorePlatforms(appDirectory, packageJson) .then(function() { log.info('\nRestore platforms is complete\n'); }); @@ -450,7 +446,7 @@ State.restoreState = function restoreState(appDirectory, options) { .then(function() { if (options.plugins) { log.info('\rRestoring Plugins\n'); - return State.restorePlugins(appDirectory, packageJson) + return restorePlugins(appDirectory, packageJson) .then(function() { log.info('Restore plugins is complete\n'); }); @@ -465,25 +461,25 @@ State.restoreState = function restoreState(appDirectory, options) { log.error('Ionic state restore failed\n'); log.error(ex); }); -}; +} -State.restorePlugins = function restorePlugins(appDirectory, packageJson) { +function restorePlugins(appDirectory, packageJson) { log.debug('State.restorePlugins', appDirectory, packageJson); var q = Q.defer(); - State.processPlugin(appDirectory, 0, packageJson, q); + processPlugin(appDirectory, 0, packageJson, q); return q.promise; -}; +} -State.restorePlatforms = function restorePlatforms(appDirectory, packageJson) { +function restorePlatforms(appDirectory, packageJson) { log.debug('State.restorePlatforms', appDirectory, packageJson); var q = Q.defer(); - State.processPlatform(appDirectory, 0, packageJson, q); + processPlatform(appDirectory, 0, packageJson, q); return q.promise; -}; +} -State.processPlatform = function processPlatform(appDirectory, index, packageJson, promise) { +function processPlatform(appDirectory, index, packageJson, promise) { if (index >= packageJson.cordovaPlatforms.length) { promise.resolve(); return; @@ -507,16 +503,16 @@ State.processPlatform = function processPlatform(appDirectory, index, packageJso // var platformCommand = State.createAddRemoveStatement(platform); log.info(platformCommand); shelljs.exec(platformCommand, function() { - State.processPlatform(appDirectory, index + 1, packageJson, promise); + processPlatform(appDirectory, index + 1, packageJson, promise); }); } catch (ex) { log.error('An error happened processing the previous cordova plugins'); log.error(ex); promise.reject(ex); } -}; +} -State.createAddRemoveStatement = function createAddRemoveStatement(plugin) { +function createAddRemoveStatement(plugin) { // log.info('Creating add/remove statement', plugin) try { @@ -537,9 +533,9 @@ State.createAddRemoveStatement = function createAddRemoveStatement(plugin) { // log.info('plugin cmd', pluginCmd) return pluginCmd; -}; +} -State.processPlugin = function processPlugin(appDirectory, index, packageJson, promise) { +function processPlugin(appDirectory, index, packageJson, promise) { if (index >= packageJson.cordovaPlugins.length) { promise.resolve(); return; @@ -549,7 +545,7 @@ State.processPlugin = function processPlugin(appDirectory, index, packageJson, p // log.info('processing plugin', index, packageJson) var plugin = packageJson.cordovaPlugins[index]; - var pluginCommand = State.createAddRemoveStatement(plugin); + var pluginCommand = createAddRemoveStatement(plugin); log.info(pluginCommand); @@ -557,16 +553,16 @@ State.processPlugin = function processPlugin(appDirectory, index, packageJson, p if (code !== 0) { throw 'Error executing "' + pluginCommand + '":\n' + output; } - State.processPlugin(appDirectory, index + 1, packageJson, promise); + processPlugin(appDirectory, index + 1, packageJson, promise); }); } catch (ex) { log.error('An error happened processing the previous cordova plugins'); log.error(ex); promise.reject(ex); } -}; +} -State.removePlatform = function removePlatform(appDirectory, platform) { +function removePlatform(appDirectory, platform) { // log.info('Args:', platformArgs); // Expecting - ionic platform remove [ios|android] @@ -574,7 +570,7 @@ State.removePlatform = function removePlatform(appDirectory, platform) { // TODO - check if they pass multiple platforms // ionic platform remove ios android - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); var platformEntry; for (var i = 0, j = packageJson.cordovaPlatforms.length; i < j; i += 1) { @@ -590,10 +586,10 @@ State.removePlatform = function removePlatform(appDirectory, platform) { } } - State.savePackageJson(appDirectory, packageJson); -}; + savePackageJson(appDirectory, packageJson); +} -State.getPluginParameters = function getPluginParameters(configXmlData, pluginName) { +function getPluginParameters(configXmlData, pluginName) { if (!configXmlData || !configXmlData.widget || !configXmlData.widget.feature) { throw 'Invalid Config XML Data'; } @@ -612,9 +608,9 @@ State.getPluginParameters = function getPluginParameters(configXmlData, pluginNa } return null; -}; +} -State.getPluginPreferences = function getPluginPreferences(fetchJson, pluginName) { +function getPluginPreferences(fetchJson, pluginName) { if (!fetchJson || !fetchJson[pluginName]) { throw 'Invalid fetch.json Data'; } @@ -625,9 +621,8 @@ State.getPluginPreferences = function getPluginPreferences(fetchJson, pluginName } return null; -}; +} -// /** * Used after `ionic plugin add ` to save the plugin * to package.json and config.xml. @@ -637,7 +632,7 @@ State.getPluginPreferences = function getPluginPreferences(fetchJson, pluginName variable: [ 'APP_ID=123456789', 'APP_NAME=myApplication' ], '$0': '/usr/local/bin/ionic' } */ -State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { +function savePlugin(appDirectory, pluginId, variables) { log.debug('State.savePlugin - appDirectory:', appDirectory, 'pluginId', pluginId, 'variables', variables); // Expects - either simple ID for plugin registry @@ -649,7 +644,7 @@ State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { // If its a git resource locator, we'll have to look at fetch.json // Idea: this is run after platform add/rm is done - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); var pluginInfo = {}; // This is necessary to ensure variables is actually an array @@ -673,38 +668,38 @@ State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { // Check and save for variables if (!variables) { - State.addOrUpdatePluginToPackageJson(packageJson, pluginId); + addOrUpdatePluginToPackageJson(packageJson, pluginId); } else { pluginInfo.locator = pluginId; - pluginInfo.id = pluginId = State.getPluginFromFetchJsonByLocator(appDirectory, pluginInfo.locator); - State.addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); + pluginInfo.id = pluginId = getPluginFromFetchJsonByLocator(appDirectory, pluginInfo.locator); + addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); } - return State.savePackageJson(appDirectory, packageJson); + return savePackageJson(appDirectory, packageJson); } // By here, we know its not a registry plugin (git/local) // Its a locator, local file path or https://github.com repo pluginInfo.locator = pluginId; - pluginInfo.id = pluginId = State.getPluginFromFetchJsonByLocator(appDirectory, pluginInfo.locator); + pluginInfo.id = pluginId = getPluginFromFetchJsonByLocator(appDirectory, pluginInfo.locator); // If there are no variables, we just add to package, then save if (!variables) { - State.addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); - return State.savePackageJson(appDirectory, packageJson); + addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); + return savePackageJson(appDirectory, packageJson); } - State.addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); + addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); log.info('Save plugin to package.json completed'); // By now we assume pluginId is set, and locator might be set. - return State.savePackageJson(appDirectory, packageJson); -}; + return savePackageJson(appDirectory, packageJson); +} -State.removePlugin = function removePlugin(appDirectory, pluginId) { +function removePlugin(appDirectory, pluginId) { log.debug('State.removePlugin - ', appDirectory, pluginId); - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); for (var i = 0, j = packageJson.cordovaPlugins.length; i < j; i += 1) { if (typeof packageJson.cordovaPlugins[i] == 'string' && packageJson.cordovaPlugins[i] === pluginId) { packageJson.cordovaPlugins.splice(i, 1); @@ -715,10 +710,10 @@ State.removePlugin = function removePlugin(appDirectory, pluginId) { } } - State.savePackageJson(appDirectory, packageJson); -}; + savePackageJson(appDirectory, packageJson); +} -State.saveXmlFile = function saveXmlFile(xmlData, xmlPath) { +function saveXmlFile(xmlData, xmlPath) { try { var xml2js = require('xml2js'); var xmlBuilder = new xml2js.Builder(); @@ -727,9 +722,9 @@ State.saveXmlFile = function saveXmlFile(xmlData, xmlPath) { } catch (ex) { log.error('Could not save your xml file to path:', xmlPath); } -}; +} -State.getPluginFromFetchJsonByLocator = function getPluginFromFetchJsonByLocator(appDirectory, pluginLocator) { +function getPluginFromFetchJsonByLocator(appDirectory, pluginLocator) { var fetchJson = require(path.join(appDirectory, 'plugins', 'fetch.json')); var lookupId; var lookupPlugin; @@ -772,32 +767,32 @@ State.getPluginFromFetchJsonByLocator = function getPluginFromFetchJsonByLocator } return pluginId; -}; +} -State.resetState = function resetState(appDirectory, options) { +function resetState(appDirectory, options) { var platformPath = path.join(appDirectory, 'platforms'); var pluginPath = path.join(appDirectory, 'plugins'); shelljs.rm('-rf', [platformPath, pluginPath]); log.info('Removed platforms and plugins'); - State.restoreState(appDirectory, options) + restoreState(appDirectory, options) .then(function() { log.info('Ionic reset state complete'); }); -}; +} -State.clearState = function clearState(appDirectory) { +function clearState(appDirectory) { log.info('Clearing out your Ionic app of platforms, plugins, and package.json entries'); var platformPath = path.join(appDirectory, 'platforms'); var pluginPath = path.join(appDirectory, 'plugins'); shelljs.rm('-rf', [platformPath, pluginPath]); - var packageJson = State.getPackageJson(appDirectory); + var packageJson = getPackageJson(appDirectory); packageJson.cordovaPlatforms = packageJson.cordovaPlugins = []; - State.savePackageJson(appDirectory, packageJson); + savePackageJson(appDirectory, packageJson); log.info('Ionic app state cleared'); -}; +} -State.getPluginsFromFetchJson = function getPluginsFromFetchJson(appDirectory) { +function getPluginsFromFetchJson(appDirectory) { var fetchJson; var pluginId; var installedPlugins = {}; @@ -834,7 +829,7 @@ State.getPluginsFromFetchJson = function getPluginsFromFetchJson(appDirectory) { } pluginXmlPath = path.join(appDirectory, 'plugins', pluginId, 'plugin.xml'); - pluginXml = State.getXmlData(pluginXmlPath); + pluginXml = getXmlData(pluginXmlPath); pluginDescription = pluginXml.plugin.description[0]; pluginName = pluginXml.plugin.name[0]; @@ -854,4 +849,36 @@ State.getPluginsFromFetchJson = function getPluginsFromFetchJson(appDirectory) { } return installedPlugins; +} + +module.exports = { + readInPackageJson: readInPackageJson, + getPackageJson: getPackageJson, + getPackageJsonReadStream: getPackageJsonReadStream, + addOrUpdatePluginToPackageJson: addOrUpdatePluginToPackageJson, + saveState: saveState, + platformExists: platformExists, + saveExistingPlatforms: saveExistingPlatforms, + saveExistingPlugins: saveExistingPlugins, + getXmlData: getXmlData, + getPlatformVersion: getPlatformVersion, + addOrUpdatePlatformToPackageJson: addOrUpdatePlatformToPackageJson, + savePlatform: savePlatform, + savePackageJson: savePackageJson, + restoreState: restoreState, + restorePlugins: restorePlugins, + restorePlatforms: restorePlatforms, + processPlatform: processPlatform, + createAddRemoveStatement: createAddRemoveStatement, + processPlugin: processPlugin, + removePlatform: removePlatform, + getPluginParameters: getPluginParameters, + getPluginPreferences: getPluginPreferences, + savePlugin: savePlugin, + removePlugin: removePlugin, + saveXmlFile: saveXmlFile, + getPluginFromFetchJsonByLocator: getPluginFromFetchJsonByLocator, + resetState: resetState, + clearState: clearState, + getPluginsFromFetchJson: getPluginsFromFetchJson }; diff --git a/lib/stats.js b/lib/stats.js deleted file mode 100644 index 44d8678..0000000 --- a/lib/stats.js +++ /dev/null @@ -1,750 +0,0 @@ -/* eslint-disable camelcase, no-underscore-dangle */ - -var Buffer = require('buffer').Buffer; -var http = require('http'); -var IonicConfig = require('./config'); -var path = require('path'); -var util = require('util'); -var Q = require('q'); -var querystring = require('querystring'); - -/* - Heavily inspired by the original js library copyright Mixpanel, Inc. - (http://mixpanel.com/) - - Copyright (c) 2012 Carl Sverre - - Released under the MIT license. -*/ - -var Stats = module.exports; - - -// Old code - previously used exclusively by CLI. This is changing -// Now we want a create client for a token passed. -// No longer do we want to assume a default client. -// Instead, we initialize one with a token passed in. -function create_client(token, config) { - var metrics = {}; - - if (!token) { - throw new Error('The Mixpanel Client needs a Mixpanel token: `init(token)`'); - } - - metrics.config = { - test: false, - debug: false, - verbose: false - }; - - metrics.token = token; - - /** - send_request(data) - --- - this function sends an async GET request to mixpanel - - data:object the data to send in the request - callback:function(err:Error) callback is called when the request is - finished or an error occurs - */ - metrics.send_request = function(endpoint, data, callback) { - callback = callback || function() {}; - var event_data = new Buffer(JSON.stringify(data)); - var request_data = { - data: event_data.toString('base64'), - ip: 0, - verbose: metrics.config.verbose ? 1 : 0 - }; - - if (endpoint === '/import') { - var key = metrics.config.key; - if (!key) { - throw new Error('The Mixpanel Client needs a Mixpanel api key when importing ' + - 'old events: `init(token, { key: ... })`'); - } - request_data.api_key = key; - } - - var request_options = { - host: 'api.mixpanel.com', - port: 80, - headers: {} - }; - - if (metrics.config.test) { request_data.test = 1; } - - var query = querystring.stringify(request_data); - - request_options.path = [endpoint, '?', query].join(''); - - http.get(request_options, function(res) { - var data = ''; - res.on('data', function(chunk) { - data += chunk; - }); - - res.on('end', function() { - var e; - if (metrics.config.verbose) { - try { - var result = JSON.parse(data); - if (result.status !== 1) { - e = new Error('Mixpanel Server Error: ' + result.error); - } - } catch (ex) { - e = new Error('Could not parse response from Mixpanel'); - } - } else { - e = (data !== '1') ? new Error('Mixpanel Server Error: ' + data) : undefined; - } - - callback(e); - }); - }).on('error', function(e) { - if (metrics.config.debug) { - console.log('Got Error: ' + e.message); - } - callback(e); - }); - }; - - /** - track(event, properties, callback) - --- - this function sends an event to mixpanel. - - event:string the event name - properties:object additional event properties to send - callback:function(err:Error) callback is called when the request is - finished or an error occurs - */ - metrics.track = function(event, properties, callback) { - if (typeof(properties) === 'function' || !properties) { - callback = properties; - properties = {}; - } - - // if properties.time exists, use import endpoint - var endpoint = (typeof(properties.time) === 'number') ? '/import' : '/track'; - - properties.token = metrics.token; - properties.mp_lib = 'node'; - - var data = { - event: event, - properties: properties - }; - - if (metrics.config.debug) { - console.log('Sending the following event to Mixpanel:'); - console.log(data); - } - - metrics.send_request(endpoint, data, callback); - }; - - /** - import(event, properties, callback) - --- - This function sends an event to mixpanel using the import - endpoint. The time argument should be either a Date or Number, - and should signify the time the event occurred. - - It is highly recommended that you specify the distinct_id - property for each event you import, otherwise the events will be - tied to the IP address of the sending machine. - - For more information look at: - https://mixpanel.com/docs/api-documentation/importing-events-older-than-31-days - - event:string the event name - time:date|number the time of the event - properties:object additional event properties to send - callback:function(err:Error) callback is called when the request is - finished or an error occurs - */ - metrics.import = function(event, time, properties, callback) { - if (typeof(properties) === 'function' || !properties) { - callback = properties; - properties = {}; - } - - if (time === void 0) { - throw new Error('The import method requires you to specify the time of the event'); - } else if (Object.prototype.toString.call(time) === '[object Date]') { - time = Math.floor(time.getTime() / 1000); - } - - properties.time = time; - - metrics.track(event, properties, callback); - }; - - /** - alias(distinct_id, alias) - --- - This function creates an alias for distinct_id - - For more information look at: - https://mixpanel.com/docs/integration-libraries/using-mixpanel-alias - - distinct_id:string the current identifier - alias:string the future alias - */ - metrics.alias = function(distinct_id, alias, callback) { - var properties = { - distinct_id: distinct_id, - alias: alias - }; - - metrics.track('$create_alias', properties, callback); - }; - - metrics.people = { - - /** people.set_once(distinct_id, prop, to, callback) - --- - The same as people.set but in the words of mixpanel: - mixpanel.people.set_once - - " This method allows you to set a user attribute, only if - it is not currently set. It can be called multiple times - safely, so is perfect for storing things like the first date - you saw a user, or the referrer that brought them to your - website for the first time. " - - */ - set_once: function(distinct_id, prop, to, callback) { - var $set = {}; - - if (typeof(prop) === 'object') { - callback = to; - $set = prop; - } else { - $set[prop] = to; - } - - this._set(distinct_id, $set, callback, { set_once: true }); - }, - - /** - people.set(distinct_id, prop, to, callback) - --- - set properties on an user record in engage - - usage: - - mixpanel.people.set('bob', 'gender', 'm'); - - mixpanel.people.set('joe', { - 'company': 'acme', - 'plan': 'premium' - }); - */ - set: function(distinct_id, prop, to, callback) { - var $set = {}; - - if (typeof(prop) === 'object') { - callback = to; - $set = prop; - } else { - $set[prop] = to; - } - - this._set(distinct_id, $set, callback); - }, - - // used internally by set and set_once - _set: function(distinct_id, $set, callback, options) { - var set_key = (options && options.set_once) ? '$set_once' : '$set'; - - var data = { - $token: metrics.token, - $distinct_id: distinct_id - }; - data[set_key] = $set; - - if ('ip' in $set) { - data.$ip = $set.ip; - delete $set.ip; - } - - if ($set.$ignore_time) { - data.$ignore_time = $set.$ignore_time; - delete $set.$ignore_time; - } - - if (metrics.config.debug) { - console.log('Sending the following data to Mixpanel (Engage):'); - console.log(data); - } - - metrics.send_request('/engage', data, callback); - }, - - /** - people.increment(distinct_id, prop, to, callback) - --- - increment/decrement properties on an user record in engage - - usage: - - mixpanel.people.increment('bob', 'page_views', 1); - - // or, for convenience, if you're just incrementing a counter by 1, you can - // simply do - mixpanel.people.increment('bob', 'page_views'); - - // to decrement a counter, pass a negative number - mixpanel.people.increment('bob', 'credits_left', -1); - - // like mixpanel.people.set(), you can increment multiple properties at once: - mixpanel.people.increment('bob', { - counter1: 1, - counter2: 3, - counter3: -2 - }); - */ - increment: function(distinct_id, prop, by, callback) { - var $add = {}; - - if (typeof(prop) === 'object') { - callback = by; - Object.keys(prop).forEach(function(key) { - var val = prop[key]; - - if (isNaN(parseFloat(val))) { - if (metrics.config.debug) { - console.error('Invalid increment value passed to mixpanel.people.increment - must be a number'); - console.error('Passed ' + key + ':' + val); - } - return; - } else { - $add[key] = val; - } - }); - } else { - if (!by) { by = 1; } - $add[prop] = by; - } - - var data = { - $add: $add, - $token: metrics.token, - $distinct_id: distinct_id - }; - - if (metrics.config.debug) { - console.log('Sending the following data to Mixpanel (Engage):'); - console.log(data); - } - - metrics.send_request('/engage', data, callback); - }, - - /** - people.track_charge(distinct_id, amount, properties, callback) - --- - Record that you have charged the current user a certain - amount of money. - - usage: - - // charge a user $29.99 - mixpanel.people.track_charge('bob', 29.99); - - // charge a user $19 on the 1st of february - mixpanel.people.track_charge('bob', 19, { '$time': new Date('feb 1 2012') }); - */ - track_charge: function(distinct_id, amount, properties, callback) { - if (!properties) { properties = {}; } - - if (typeof(amount) !== 'number') { - amount = parseFloat(amount); - if (isNaN(amount)) { - console.error('Invalid value passed to mixpanel.people.track_charge - must be a number'); - return; - } - } - - properties.$amount = amount; - - if (properties.hasOwnProperty('$time')) { - var time = properties.$time; - if (Object.prototype.toString.call(time) === '[object Date]') { - properties.$time = time.toISOString(); - } - } - - var data = { - $append: { - $transactions: properties - }, - $token: metrics.token, - $distinct_id: distinct_id - }; - - if (metrics.config.debug) { - console.log('Sending the following data to Mixpanel (Engage):'); - console.log(data); - } - - metrics.send_request('/engage', data, callback); - }, - - /** - people.clear_charges(distinct_id, callback) - --- - Clear all the current user's transactions. - - usage: - - mixpanel.people.clear_charges('bob'); - */ - clear_charges: function(distinct_id, callback) { - var data = { - $set: { - $transactions: [] - }, - $token: metrics.token, - $distinct_id: distinct_id - }; - - if (metrics.config.debug) { - console.log("Clearing this user's charges:", distinct_id); - } - - metrics.send_request('/engage', data, callback); - }, - - /** - people.delete_user(distinct_id, callback) - --- - delete an user record in engage - - usage: - - mixpanel.people.delete_user('bob'); - */ - delete_user: function(distinct_id, callback) { - var data = { - $delete: distinct_id, - $token: metrics.token, - $distinct_id: distinct_id - }; - - if (metrics.config.debug) { - console.log('Deleting the user from engage:', distinct_id); - } - - metrics.send_request('/engage', data, callback); - }, - - /** - people.unset(distinct_id, prop, callback) - --- - delete a property on an user record in engage - - usage: - - mixpanel.people.unset('bob', 'page_views'); - - mixpanel.people.unset('bob', ['page_views', 'last_login']); - */ - unset: function(distinct_id, prop, callback) { - var $unset = []; - - if (util.isArray(prop)) { - $unset = prop; - } else if (typeof(prop) === 'string') { - $unset = [prop]; - } else { - if (metrics.config.debug) { - console.error('Invalid argument passed to mixpanel.people.unset - must be a string or array'); - console.error('Passed: ' + prop); - } - return; - } - - var data = { - $unset: $unset, - $token: metrics.token, - $distinct_id: distinct_id - }; - - if (metrics.config.debug) { - console.log('Sending the following data to Mixpanel (Engage):'); - console.log(data); - } - - metrics.send_request('/engage', data, callback); - } - }; - - /** - set_config(config) - --- - Modifies the mixpanel config - - config:object an object with properties to override in the - mixpanel client config - */ - metrics.set_config = function(config) { - for (var c in config) { - if (config.hasOwnProperty(c)) { - metrics.config[c] = config[c]; - } - } - }; - - if (config) { - metrics.set_config(config); - } - - return metrics; -} - -// module exporting -/* -module.exports = { - Client: function(token) { - console.warn("The function `Client(token)` is deprecated. It is now called `init(token)`."); - return create_client(token); - }, - init: create_client -}; -*/ - -var mixpanel = create_client('69f7271aa8f3d43f2e1b6baf698159b7'); - -var ionicConfig = IonicConfig.load(); - - -exports.IonicStats = { - t: function(additionalData) { - try { - - if (process.argv.length < 3) return; - - if (ionicConfig.get('statsOptOut') === true) { - return; - } - - var cmdName = process.argv[2].toLowerCase(); - var cmdArgs = (process.argv.length > 3 ? process.argv.slice(3) : []); // skip the cmdName - - var statsData = additionalData || {}; - var platforms = []; - var x; - var y; - var cmd; - - // update any aliases with the full cmd so there's a common property - var aliasMap = { - rm: 'remove', - ls: 'list', - up: 'update', - '-w': '--no-cordova', - '-b': '--nobrowser', - '-r': '--nolivereload', - '-x': '--noproxy', - '-l': '--livereload', - '-c': '--consolelogs', - '-s': '--serverlogs', - '-n': '--no-email' - }; - for (x = 0; x < cmdArgs.length; x += 1) { - for (y in aliasMap) { - if (cmdArgs[x].toLowerCase() === y) { - cmdArgs[x] = aliasMap[y]; - } - } - } - - var platformWhitelist = [ - 'android', - 'ios', - 'firefoxos', - 'wp7', - 'wp8', - 'amazon-fireos', - 'blackberry10', - 'tizen' - ]; - var argsWhitelist = [ - 'add', - 'remove', - 'list', - 'update', - 'check', - 'debug', - 'release', - 'search', - '--livereload', - '--consolelogs', - '--serverlogs', - '--no-cordova', - '--nobrowser', - '--nolivereload', - '--noproxy', - '--no-email', - '--debug', - '--release', - '--device', - '--emulator', - '--sass', - '--splash', - '--icon' - ]; - - // collect only certain args, skip over everything else - for (x = 0; x < cmdArgs.length; x += 1) { - cmd = cmdArgs[x].toLowerCase(); - - // gather what platforms this is targeting - for (y = 0; y < platformWhitelist.length; y += 1) { - if (cmd === platformWhitelist[y]) { - platforms.push(cmd); // group them together - statsData[cmd] = true; // also give them their own property - break; - } - } - - // gather only args that are in our list of valid stat args - for (y = 0; y < argsWhitelist.length; y += 1) { - if (cmd === argsWhitelist[y]) { - statsData[cmd] = true; - break; - } - } - } - - // create a platform property only when there is 1 or more - if (platforms.length) { - statsData.platform = platforms.sort().join(','); - } - - // add which ionic lib version they're using - try { - statsData.ionic_version = require(path.resolve('www/lib/ionic/version.json')).version; - } catch (e2) {} // eslint-disable-line no-empty - - // add which cli version is being used - try { - statsData.cli_version = require('../../package.json').version; - if (statsData.cli_version.indexOf('beta') > -1) return; - } catch (e2) {} // eslint-disable-line no-empty - - this.mp(cmdName, statsData); - - } catch (e) { - console.log(('Error stats: ' + e)); - } - }, - mp: function(e, d) { - var unique_id = ionicConfig.get('ank'); - if (!unique_id) { - this.createId(); - unique_id = ionicConfig.get('ank'); - } - d.distinct_id = unique_id; - mixpanel.track(e, d, function() {}); // eslint-disable-line no-empty - }, - createId: function() { - var d = new Date().getTime(); - var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = (d + Math.random() * 16) % 16 | 0; - d = Math.floor(d / 16); - return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); - }); - - ionicConfig.set('ank', uuid); - } -}; - -// Default null client -Stats.client = null; - -// New Stats code -Stats.initClient = function initClient(token) { - if (!token) { - throw new Error('You must pass a token back to initialize a stat client'); - } - return Stats.client = create_client(token); -}; - -Stats.createId = function createId() { - var d = new Date().getTime(); - var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = (d + Math.random() * 16) % 16 | 0; - d = Math.floor(d / 16); - return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); - }); - - ionicConfig.set('ank', uuid); - return uuid; -}; - -Stats.getUniqueId = function getUniqueId() { - var uid = ionicConfig.get('ank'); - - if (!uid) { - uid = Stats.createId(); - } - return uid; -}; - -Stats.trackAction = function trackAction(appDirectory, command, additionalData) { - if (!Stats.client) { - throw new Error('No client is available'); - } - - var statsOptOut = ionicConfig.get('statsOptOut'); - - if (statsOptOut === true) { - return Q.resolve('Stats opt out'); - } - - var q = Q.defer(); - - var statsData = additionalData || {}; - - statsData = Stats.gatherAdditionalruntimeStats(appDirectory, statsData); - - Stats.client.track(command, statsData, function(err, data) { - if (err) { - q.reject(err); - } else { - q.resolve(data); - } - }); - - return q.promise; -}; - -Stats.gatherAdditionalruntimeStats = function gatherAdditionalruntimeStats(appDirectory, additionalData) { - var statsData = additionalData || {}; - statsData.distinct_id = Stats.getUniqueId(); - - // add which ionic lib version they're using - try { - var appJsonPath = path.join(appDirectory, 'www', 'lib', 'ionic', 'version.json'); - statsData.ionic_version = require(appJsonPath).version; - } catch (e2) { - console.log('coulndt get ionic version'); - } - - // add which cli version is being used - try { - statsData.gui_version = require('../../package.json').version; - if (statsData.gui_version.indexOf('beta') > -1) return; - } catch (e2) {} // eslint-disable-line no-empty - - console.log('Additional stats:', statsData); - console.log('Additional stats:', statsData); - console.log('Additional stats:', statsData); - - return statsData; -}; - diff --git a/lib/store.js b/lib/store.js index 92c7eac..c8cc150 100644 --- a/lib/store.js +++ b/lib/store.js @@ -53,4 +53,6 @@ IonicStore.prototype.save = function() { } }; -exports.IonicStore = IonicStore; +module.exports = { + IonicStore: IonicStore +}; diff --git a/lib/task.js b/lib/task.js deleted file mode 100644 index c18b9b2..0000000 --- a/lib/task.js +++ /dev/null @@ -1,8 +0,0 @@ -function Task() {} - -Task.prototype = { - run: function() { - } -}; - -exports.Task = Task; diff --git a/lib/upload.js b/lib/upload.js index 053a492..a93c256 100644 --- a/lib/upload.js +++ b/lib/upload.js @@ -13,9 +13,8 @@ var shelljs = require('shelljs'); var log = require('./logging').logger; var TEMP_FILENAME = 'www.zip'; -var Upload = module.exports; -Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { +function doUpload(appDirectory, jar, note, deploy) { log.info('Uploading app....'); log.debug('Upload doUpload - ', appDirectory, jar); @@ -29,15 +28,15 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { var indexPath = path.join(appDirectory, documentRoot, 'index.html'); var upload; try { - return Upload.addCacheBusters(indexPath) + return addCacheBusters(indexPath) .then(function() { - return Upload.zipContents(appDirectory, documentRoot); + return zipContents(appDirectory, documentRoot); }) .then(function() { - return Upload.removeCacheBusters(indexPath); + return removeCacheBusters(indexPath); }) .then(function() { - return Upload.getDirectUploadKey(project, jar, note); + return getDirectUploadKey(project, jar, note); }) .then(function(key) { @@ -53,10 +52,10 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { // Set project vars project.set('app_id', key.app_id); project.save(); - return Upload.uploadToS3(appDirectory, key); + return uploadToS3(appDirectory, key); }) .then(function() { // receives status - return Upload.signalDashUpload(project, jar); + return signalDashUpload(project, jar); }) .then(function(status) { upload = status; @@ -72,10 +71,10 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { }); } } - return Upload.verify_tag(project, jar, deploy, version); + return verify_tag(project, jar, deploy, version); }) .then(function(deploy) { - return Upload.deploy(project, jar, deploy); + return deploy(project, jar, deploy); }) .then(function() { // receives status return upload; @@ -87,9 +86,9 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { } catch (ex) { log.error('Upload errors occurred - %s', ex, {}); } -}; +} -Upload.uploadToS3 = function uploadToS3(appDirectory, keyInfo) { +function uploadToS3(appDirectory, keyInfo) { var q = Q.defer(); log.debug('Uploading zip file to S3'); @@ -123,9 +122,9 @@ Upload.uploadToS3 = function uploadToS3(appDirectory, keyInfo) { }); return q.promise; -}; +} -Upload.signalDashUpload = function signalDashUpload(project, jar) { +function signalDashUpload(project, jar) { var q = Q.defer(); log.debug('Signaling to ionic.io completion of the upload'); @@ -154,9 +153,9 @@ Upload.signalDashUpload = function signalDashUpload(project, jar) { }); return q.promise; -}; +} -Upload.verify_tag = function verify_tag(project, jar, deploy, version) { // eslint-disable-line camelcase +function verify_tag(project, jar, deploy, version) { // eslint-disable-line camelcase var q = Q.defer(); log.debug('Checking if we need to deploy the upload'); @@ -191,9 +190,9 @@ Upload.verify_tag = function verify_tag(project, jar, deploy, version) { // esli } return q.promise; -}; +} -Upload.deploy = function deploy(project, jar, deploy) { +function deploy(project, jar, deploy) { var q = Q.defer(); log.debug('Check for a deploy...'); @@ -232,9 +231,9 @@ Upload.deploy = function deploy(project, jar, deploy) { } return q.promise; -}; +} -Upload.getDirectUploadKey = function getDirectUploadKey(project, jar, note) { +function getDirectUploadKey(project, jar, note) { var q = Q.defer(); note = note ? note : ''; @@ -315,16 +314,16 @@ Upload.getDirectUploadKey = function getDirectUploadKey(project, jar, note) { }); return q.promise; -}; +} -Upload.zipContents = function zipContents(appDirectory, documentRoot) { +function zipContents(appDirectory, documentRoot) { return Utils.createArchive(appDirectory, documentRoot); -}; +} // If your Webview's strange, and its cache is no good? Who you gonna call? // // Cachebusters! -Upload.addCacheBusters = function addCacheBusters(indexPath) { +function addCacheBusters(indexPath) { var q = Q.defer(); log.debug('When your webview is acting crazy who do you call? Cachebusters!'); @@ -364,9 +363,9 @@ Upload.addCacheBusters = function addCacheBusters(indexPath) { } return q.promise; -}; +} -Upload.removeCacheBusters = function removeCacheBusters(indexPath) { +function removeCacheBusters(indexPath) { var q = Q.defer(); log.debug('Removing cachebusting ', indexPath); @@ -403,4 +402,16 @@ Upload.removeCacheBusters = function removeCacheBusters(indexPath) { q.reject(e); } return q.promise; +} + +module.exports = { + doUpload: doUpload, + uploadToS3: uploadToS3, + signalDashUpload: signalDashUpload, + verify_tag: verify_tag, // eslint-disable-line camelcase + deploy: deploy, + getDirectUploadKey: getDirectUploadKey, + zipContents: zipContents, + addCacheBusters: addCacheBusters, + removeCacheBusters: removeCacheBusters }; diff --git a/lib/utils.js b/lib/utils.js index 10da0ca..a79b14f 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -9,20 +9,18 @@ var Q = require('q'); var shelljs = require('shelljs'); var log = require('./logging').logger; -var Utils = module.exports; +var errorHandler = null; -Utils.errorHandler = null; - -Utils.transformCookies = function transformCookies(jar) { +function transformCookies(jar) { if (!jar) { throw new Error('You parse out cookies if they are null'); } return jar.map(function(c) { return c.key + '=' + encodeURIComponent(c.value); }).join('; '); -}; +} -Utils.retrieveCsrfToken = function retrieveCsrfToken(jar) { +function retrieveCsrfToken(jar) { var csrftoken = ''; if (!jar || typeof jar == 'undefined' || jar.length === 0) { @@ -36,7 +34,7 @@ Utils.retrieveCsrfToken = function retrieveCsrfToken(jar) { } } return csrftoken; -}; +} /** * Utils.createArchive will zip up a subdirectory in the app directory @@ -49,7 +47,7 @@ Utils.retrieveCsrfToken = function retrieveCsrfToken(jar) { * * @return {Promise} */ -Utils.createArchive = function(appDirectory, documentRoot) { +function createArchive(appDirectory, documentRoot) { var q = Q.defer(); var zipPath = path.join(appDirectory, documentRoot); @@ -81,9 +79,9 @@ Utils.createArchive = function(appDirectory, documentRoot) { }); return q.promise; -}; +} -Utils.fetchArchive = function fetchArchive(targetPath, archiveUrl, isGui) { +function fetchArchive(targetPath, archiveUrl, isGui) { var os = require('os'); var fs = require('fs'); var path = require('path'); @@ -147,9 +145,9 @@ Utils.fetchArchive = function fetchArchive(targetPath, archiveUrl, isGui) { }); return q.promise; -}; +} -Utils.preprocessOptions = function preprocessOptions(options) { +function preprocessOptions(options) { var result = {}; result.appDirectory = options.appDirectory; @@ -169,9 +167,9 @@ Utils.preprocessOptions = function preprocessOptions(options) { result.setupSass = options.setupSass || true; return result; -}; +} -Utils.preprocessCliOptions = function preprocessCliOptions(argv) { +function preprocessCliOptions(argv) { log.debug('Utils.preprocessCliOptions', argv); try { var options = {}; @@ -198,7 +196,7 @@ Utils.preprocessCliOptions = function preprocessCliOptions(argv) { options.template = (argv.template || argv.t || argv._[2] || 'tabs'); // figure out the full path - options.targetPath = Utils.getProjectDirectory(options); + options.targetPath = getProjectDirectory(options); options.typescript = argv.typescript || argv.ts; options.v2 = argv.v2 || argv.v; @@ -207,15 +205,15 @@ Utils.preprocessCliOptions = function preprocessCliOptions(argv) { return options; } catch (ex) { log.debug('An error occrured processing the CLI arguments', ex); - Utils.fail('There was an error parsing out options from the Command Line'); + fail('There was an error parsing out options from the Command Line'); } -}; +} -Utils.getProjectDirectory = function getProjectDirectory(options) { +function getProjectDirectory(options) { return path.resolve(options.appDirectory); -}; +} -Utils.getContentSrc = function getContentSrc(appDirectory) { +function getContentSrc(appDirectory) { log.debug('Utils.getContentSrc', appDirectory); var contentSrc; try { @@ -237,23 +235,23 @@ Utils.getContentSrc = function getContentSrc(appDirectory) { var parseString = xml2js.parseString; parseString(configString, function(err, jsonConfig) { if (err) { - return Utils.fail('Error parsing config.xml: ' + err); + return fail('Error parsing config.xml: ' + err); } try { contentSrc = jsonConfig.widget.content[0].$.src; } catch (e) { - return Utils.fail('Error parsing ' + configXmlPath + ': ' + e.stack); + return fail('Error parsing ' + configXmlPath + ': ' + e.stack); } }); } catch (e) { - return Utils.fail('Error loading ' + configXmlPath + ': ' + e.stack); + return fail('Error loading ' + configXmlPath + ': ' + e.stack); } return contentSrc; -}; +} -Utils.mergeOptions = function mergeOptions(obj1, obj2) { +function mergeOptions(obj1, obj2) { var obj3 = {}; for (var attrname in obj1) { if (obj1.hasOwnProperty(attrname)) { @@ -266,17 +264,17 @@ Utils.mergeOptions = function mergeOptions(obj1, obj2) { } } return obj3; -}; +} -Utils.fail = function fail(msg, taskHelp) { +function fail(msg, taskHelp) { try { - log.debug('Utils.fail', msg, taskHelp); + log.debug('fail', msg, taskHelp); log.debug('Utils.fail stack', msg.stack); // If an error handler is set, use it. Otherwise, just print basic info. - if (Utils.errorHandler) { - log.debug('Utils.errorHandler is set, calling that now'); - return Utils.errorHandler(msg, taskHelp); + if (errorHandler) { + log.debug('errorHandler is set, calling that now'); + return errorHandler(msg, taskHelp); } log.error('An error occurred in Ionic App Lib and no error handler was set.'); @@ -286,35 +284,35 @@ Utils.fail = function fail(msg, taskHelp) { } catch (ex) { log.debug('Utils.fail: ', ex); } -}; +} -Utils.gulpInstalledGlobally = function gulpInstalledGlobally() { +function gulpInstalledGlobally() { var result = shelljs.exec('gulp -v', { silent: true }); if (result.code !== 0) { return false; } return true; -}; +} -Utils.cordovaInstalled = function cordovaInstalled() { +function cordovaInstalled() { var Info = require('./info'); var info = {}; Info.getCordovaInfo(info); return info.cordova !== 'Not installed'; -}; +} -Utils.findIonicRoot = function findIonicRoot(dir) { +function findIonicRoot(dir) { var IonicProject = require('./project'); if (!dir) { var pwd = process.env.PWD; var cwd = process.cwd(); if (pwd && pwd !== cwd && pwd !== 'undefined') { - return Utils.findIonicRoot(pwd) || Utils.findIonicRoot(cwd); + return findIonicRoot(pwd) || findIonicRoot(cwd); } - return Utils.findIonicRoot(cwd); + return findIonicRoot(cwd); } for (var i = 0; i < 1000; i += 1) { if (fs.existsSync(path.join(dir, IonicProject.PROJECT_FILE))) { @@ -341,13 +339,13 @@ Utils.findIonicRoot = function findIonicRoot(dir) { } log.error('Hit an unhandled case in utils.findIonicRoot'); return null; -}; +} -Utils.cdIonicRoot = function cdIonicRoot() { +function cdIonicRoot() { var IonicProject = require('./project'); log.debug('Looking up Ionic root, cwd:', process.cwd()); - var rootDir = this.findIonicRoot(); + var rootDir = findIonicRoot(); if (!rootDir) { log.error('Couldn\'t find ' + IonicProject.PROJECT_FILE + ' file. Are you in an Ionic project?'); process.exit(1); @@ -357,4 +355,22 @@ Utils.cdIonicRoot = function cdIonicRoot() { process.chdir(rootDir); return rootDir; +} + +module.exports = { + errorHandler: errorHandler, + transformCookies: transformCookies, + retrieveCsrfToken: retrieveCsrfToken, + createArchive: createArchive, + fetchArchive: fetchArchive, + preprocessOptions: preprocessOptions, + prepreocessCliOptions: preprocessCliOptions, + getProjectDirectory: getProjectDirectory, + getContentSrc: getContentSrc, + mergeOptions: mergeOptions, + fail: fail, + gulpInstalledGlobally: gulpInstalledGlobally, + cordovaInstalled: cordovaInstalled, + findIonicRoot: findIonicRoot, + cdIonicRoot: cdIonicRoot }; diff --git a/package.json b/package.json index 3b9354a..784d19e 100644 --- a/package.json +++ b/package.json @@ -28,14 +28,13 @@ "name": "Adam Bradley", "web": "https://twitter.com/adamdbradley" }, - { - "name": "Josh Bavari", - "web": "https://twitter.com/jbavari", - "email": "josh@drifty.com" - }, { "name": "Tim Lancina", "web": "https://twitter.com/timlancina" + }, + { + "name": "Josh Thomas", + "web": "https://twitter.com/jthoms1" } ], "license": "MIT", @@ -72,13 +71,15 @@ "coveralls": "^2.11.9", "eslint": "^2.8.0", "istanbul": "^0.4.3", - "jasmine-node": "1.14.5", + "jasmine-node": "^1.14.5", "rewire": "2.5.1" }, "scripts": { - "test": "npm run jasmine", + "test": "istanbul cover node_modules/jasmine-node/bin/jasmine-node --captureExceptions spec/", "jasmine": "jasmine-node --captureExceptions spec/", "lint": "eslint .", "coveralls": "istanbul cover node_modules/jasmine-node/bin/jasmine-node --captureExceptions spec/ && cat coverage/lcov.info | node_modules/coveralls/bin/coveralls.js && rm -rf coverage" - } + }, + "cordovaPlugins": [], + "cordovaPlatforms": [] } diff --git a/spec/bomindex.html b/spec/artifacts/bomindex.html similarity index 100% rename from spec/bomindex.html rename to spec/artifacts/bomindex.html diff --git a/spec/cachebustedindex.html b/spec/artifacts/cachebustedindex.html similarity index 100% rename from spec/cachebustedindex.html rename to spec/artifacts/cachebustedindex.html diff --git a/spec/config.xml b/spec/artifacts/config.xml similarity index 100% rename from spec/config.xml rename to spec/artifacts/config.xml diff --git a/spec/index.html b/spec/artifacts/index.html similarity index 100% rename from spec/index.html rename to spec/artifacts/index.html diff --git a/spec/config-xml.spec.js b/spec/config-xml.spec.js index e80fb85..4a25a89 100644 --- a/spec/config-xml.spec.js +++ b/spec/config-xml.spec.js @@ -2,6 +2,7 @@ var ConfigXml = require('../lib/config-xml'); var fs = require('fs'); var helpers = require('./helpers'); var options = {}; +var path = require('path'); var Q = require('q'); var logging = require('../lib/logging'); @@ -16,7 +17,7 @@ describe('ConfigXml', function() { describe('#setConfigXml', function() { var writeFile; - var xmlPath = __dirname; + var xmlPath = path.join(__dirname, 'artifacts'); beforeEach(function() { writeFile = spyOn(fs, 'writeFileSync'); diff --git a/spec/cordova.spec.js b/spec/cordova.spec.js index 719cb7e..624d100 100644 --- a/spec/cordova.spec.js +++ b/spec/cordova.spec.js @@ -14,16 +14,23 @@ describe('Cordova', function() { it('should have Cordova defined', function() { expect(Cordova).toBeDefined(); + expect(Cordova.Lib).toBeDefined(); + expect(Cordova.runCordova).toEqual(jasmine.any(Function)); + expect(Cordova.setupLiveReload).toEqual(jasmine.any(Function)); + expect(Cordova.addPlatform).toEqual(jasmine.any(Function)); + expect(Cordova.removePlatform).toEqual(jasmine.any(Function)); + expect(Cordova.runPlatform).toEqual(jasmine.any(Function)); + expect(Cordova.addPlugin).toEqual(jasmine.any(Function)); + expect(Cordova.removePlugin).toEqual(jasmine.any(Function)); + expect(Cordova.buildPlatform).toEqual(jasmine.any(Function)); + expect(Cordova.preparePlatform).toEqual(jasmine.any(Function)); }); describe('#removePlatform', function() { it('should call cordova.platform when removePlatform is called', function(done) { spyOn(cordova, 'platform').andReturn(Q()); - Q() - .then(function() { - return Cordova.removePlatform(testDirectory, 'ios'); - }) - .then(function() { + + Cordova.removePlatform(testDirectory, 'ios').then(function() { expect(cordova.platform).toHaveBeenCalledWith('remove', ['ios'], {}); }) .catch(function() { @@ -35,11 +42,8 @@ describe('Cordova', function() { it('should call state.removePlatform when removePlatform is called to save platform', function(done) { spyOn(cordova, 'platform').andReturn(Q()); spyOn(state, 'removePlatform').andReturn(Q()); - Q() - .then(function() { - return Cordova.removePlatform(testDirectory, 'ios', true); - }) - .then(function() { + + Cordova.removePlatform(testDirectory, 'ios', true).then(function() { expect(state.removePlatform).toHaveBeenCalledWith(testDirectory, 'ios'); }) .catch(function() { @@ -51,11 +55,8 @@ describe('Cordova', function() { it('should not call state.savePlatform when removePlatform is called to save platform', function(done) { spyOn(cordova, 'platform').andReturn(Q()); spyOn(state, 'removePlatform').andReturn(Q()); - Q() - .then(function() { - return Cordova.removePlatform(testDirectory, 'ios'); - }) - .then(function() { + + Cordova.removePlatform(testDirectory, 'ios').then(function() { expect(state.removePlatform).not.toHaveBeenCalled(); }) .catch(function() { @@ -68,11 +69,8 @@ describe('Cordova', function() { describe('#addPlugin', function() { it('should call cordova.plugin when addPlugin is called', function(done) { spyOn(cordova, 'plugin').andReturn(Q()); - Q() - .then(function() { - return Cordova.addPlugin(testDirectory, testPluginId); - }) - .then(function() { + + Cordova.addPlugin(testDirectory, testPluginId).then(function() { expect(cordova.plugin).toHaveBeenCalledWith('add', testPluginId, { stdio:'pipe' }); }) .catch(function(data) { @@ -85,11 +83,7 @@ describe('Cordova', function() { it('should not call state.savePlugin when addPlugin is not called to save plugin', function(done) { spyOn(cordova, 'plugin').andReturn(Q()); spyOn(state, 'savePlugin').andReturn(Q()); - Q() - .then(function() { - return Cordova.addPlugin(testDirectory, 'org.apache.cordova.device'); - }) - .then(function() { + Cordova.addPlugin(testDirectory, 'org.apache.cordova.device').then(function() { expect(state.savePlugin).not.toHaveBeenCalled(); }) .catch(function() { @@ -101,11 +95,8 @@ describe('Cordova', function() { it('should call state.savePlugin when addPlugin is called to save plugin', function(done) { spyOn(cordova, 'plugin').andReturn(Q()); spyOn(state, 'savePlugin').andReturn(Q()); - Q() - .then(function() { - return Cordova.addPlugin(testDirectory, 'org.apache.cordova.device', null, true); - }) - .then(function() { + + Cordova.addPlugin(testDirectory, 'org.apache.cordova.device', null, true).then(function() { expect(state.savePlugin).toHaveBeenCalled(); }) .catch(function() { @@ -118,11 +109,8 @@ describe('Cordova', function() { describe('#removePlugin', function() { it('should call cordova.plugin when removePlugin is called', function(done) { spyOn(cordova, 'plugin').andReturn(Q()); - Q() - .then(function() { - return Cordova.removePlugin(testDirectory, testPluginId); - }) - .then(function() { + + Cordova.removePlugin(testDirectory, testPluginId).then(function() { expect(cordova.plugin).toHaveBeenCalledWith('remove', testPluginId, { stdio:'pipe' }); }) .catch(function(data) { diff --git a/spec/index.spec.js b/spec/index.spec.js index 9101edc..d312f04 100644 --- a/spec/index.spec.js +++ b/spec/index.spec.js @@ -15,7 +15,7 @@ describe('index', function() { var objs = ['configXml', 'cordova', 'events', 'hooks', 'info', 'ioConfig', 'login', 'logging', 'multibar', 'project', 'share', 'semver', 'serve', 'settings', 'start', 'state', - 'stats', 'upload', 'utils']; + 'upload', 'utils']; // Doing it this way to give better failure messages. // Ensures all commands are available currently from diff --git a/spec/info.spec.js b/spec/info.spec.js index 37bb7bf..5661505 100644 --- a/spec/info.spec.js +++ b/spec/info.spec.js @@ -1,27 +1,26 @@ -var Info = require('../lib/info'); +var rewire = require('rewire'); +var Info = rewire('../lib/info'); describe('Info', function() { it('should have info defined', function() { expect(Info).toBeDefined(); + expect(Info.getMacInfo).toEqual(jasmine.any(Function)); + expect(Info.getCordovaInfo).toEqual(jasmine.any(Function)); + expect(Info.getXcodeInfo).toEqual(jasmine.any(Function)); + expect(Info.getIosSimInfo).toEqual(jasmine.any(Function)); + expect(Info.getIosDeployInfo).toEqual(jasmine.any(Function)); + expect(Info.getIonicCliVersion).toEqual(jasmine.any(Function)); + expect(Info.getIonicLibVersion).toEqual(jasmine.any(Function)); + expect(Info.getIonicVersion).toEqual(jasmine.any(Function)); + expect(Info.getWindowsEnvironmentInfo).toEqual(jasmine.any(Function)); + expect(Info.getLinuxEnvironmentInfo).toEqual(jasmine.any(Function)); + expect(Info.getOsEnvironment).toEqual(jasmine.any(Function)); + expect(Info.getNodeVersion).toEqual(jasmine.any(Function)); + expect(Info.gatherGulpInfo).toEqual(jasmine.any(Function)); + expect(Info.gatherInfo).toEqual(jasmine.any(Function)); + expect(Info.printInfo).toEqual(jasmine.any(Function)); + expect(Info.checkRuntime).toEqual(jasmine.any(Function)); + expect(Info.run).toEqual(jasmine.any(Function)); }); - - it('should have gatherInfo defined', function() { - expect(Info.gatherInfo).toBeDefined(); - }); - - it('should have gatherInfo call other helper methods', function() { - spyOn(Info, 'getIonicLibVersion'); - spyOn(Info, 'getNodeVersion'); - spyOn(Info, 'getOsEnvironment'); - spyOn(Info, 'getCordovaInfo'); - - Info.gatherInfo(); - - expect(Info.getIonicLibVersion).toHaveBeenCalled(); - expect(Info.getNodeVersion).toHaveBeenCalled(); - expect(Info.getOsEnvironment).toHaveBeenCalled(); - expect(Info.getCordovaInfo).toHaveBeenCalled(); - }); - }); diff --git a/spec/stats.spec.js b/spec/stats.spec.js deleted file mode 100644 index 5420622..0000000 --- a/spec/stats.spec.js +++ /dev/null @@ -1,133 +0,0 @@ -var helpers = require('./helpers'); -var logging = require('../lib/logging'); -var Q = require('q'); -var rewire = require('rewire'); - -logging.logger = helpers.testingLogger; - -describe('Stats', function() { - var Stats = rewire('../lib/stats'); - - beforeEach(function() { - Stats = rewire('../lib/stats'); - }); - - it('should have Stats defined', function() { - - // console.log(Stats); - expect(Stats).toBeDefined(); - expect(Stats.client).toBeNull(); - expect(Stats.initClient).toBeDefined(); - expect(Stats.trackAction).toBeDefined(); - expect(Stats.createId).toBeDefined(); - expect(Stats.getUniqueId).toBeDefined(); - expect(Stats.gatherAdditionalruntimeStats).toBeDefined(); - - }); - - describe('#client', function() { - - beforeEach(function() { - Stats.client = null; - }); - - it('should throw an error to init a client without a token', function() { - expect(function() { - Stats.initClient(); - }).toThrow('You must pass a token back to initialize a stat client'); - }); - - it('should init a client with token', function() { - Stats.initClient('some-token'); - - expect(Stats.client).not.toBeNull(); - expect(Stats.client.token).toBe('some-token'); - }); - - it('should throw an error if attempting to track actions before client is init', function() { - expect(function() { - expect(Stats.client).toBeNull(); - Stats.trackAction(); - }).toThrow('No client is available'); - }); - - it('should not track events if stats opt out', function() { - var ionicConfigSpy = jasmine.createSpyObj('ionicConfig', ['get', 'set']); - - // get call for stats opt out - ionicConfigSpy.get.andReturn(true); - spyOn(Stats, 'gatherAdditionalruntimeStats'); - - Stats.__set__('ionicConfig', ionicConfigSpy); - - Stats.initClient('token'); - Stats.trackAction('/some/path', 'build', {}); - - expect(ionicConfigSpy.get).toHaveBeenCalledWith('statsOptOut'); - expect(Stats.gatherAdditionalruntimeStats).not.toHaveBeenCalled(); - - }); - - it('should call stats client track when properly initialized', function(done) { - var ionicConfigSpy = jasmine.createSpyObj('ionicConfig', ['get', 'set']); - - // get call for stats opt out - ionicConfigSpy.get.andReturn(false); - spyOn(Stats, 'gatherAdditionalruntimeStats'); - - Stats.__set__('ionicConfig', ionicConfigSpy); - - Stats.initClient('token'); - - spyOn(Stats.client, 'track').andCallFake(function(command, data, cb) { - cb(null, 'result-data'); - }); - - Q() - .then(function() { - return Stats.trackAction('/some/path', 'docs', {}); - }) - .then(function() { - expect(ionicConfigSpy.get).toHaveBeenCalledWith('statsOptOut'); - expect(Stats.gatherAdditionalruntimeStats).toHaveBeenCalled(); - expect(Stats.client.track).toHaveBeenCalled(); - expect(Stats.client.track.calls[0].args[0]).toBe('docs'); - }) - .catch(function(ex) { - expect('this').toBe(ex.stack); - }) - .fin(done); - - }); - - it('should call reject promise if client fails to track', function(done) { - var ionicConfigSpy = jasmine.createSpyObj('ionicConfig', ['get', 'set']); - - // get call for stats opt out - ionicConfigSpy.get.andReturn(false); - spyOn(Stats, 'gatherAdditionalruntimeStats'); - - Stats.__set__('ionicConfig', ionicConfigSpy); - - Stats.initClient('token'); - - spyOn(Stats.client, 'track').andCallFake(function(command, data, cb) { - cb('Error!', null); - }); - - Q() - .then(function() { - return Stats.trackAction('/some/path', 'docs', {}); - }) - .catch(function(ex) { - expect(ionicConfigSpy.get).toHaveBeenCalledWith('statsOptOut'); - expect(Stats.gatherAdditionalruntimeStats).toHaveBeenCalled(); - expect(Stats.client.track).toHaveBeenCalled(); - expect(Stats.client.track.calls[0].args[0]).toBe('docs'); - - expect(ex).toBe('Error!'); - }) - .fin(done); - }); - }); -}); diff --git a/spec/task.spec.js b/spec/task.spec.js deleted file mode 100644 index 620c09a..0000000 --- a/spec/task.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -var Task = require('../lib/task'); -var helpers = require('./helpers'); -var logging = require('../lib/logging'); - -logging.logger = helpers.testingLogger; - -describe('Task', function() { - - it('should have Task defined', function() { - expect(Task).toBeDefined(); - }); -}); diff --git a/spec/upload.spec.js b/spec/upload.spec.js index 371e3eb..ac2f886 100644 --- a/spec/upload.spec.js +++ b/spec/upload.spec.js @@ -42,7 +42,7 @@ describe('Upload', function() { }); it('should add ionic cache buster attributes', function(done) { - var indexPath = path.join(__dirname, 'index.html'); + var indexPath = path.join(__dirname, 'artifacts/index.html'); spyOn(Math, 'floor').andReturn(5555); Q() @@ -78,7 +78,7 @@ describe('Upload', function() { it('should add ionic cache buster attributes with bom', function(done) { // Fix for https://github.com/driftyco/ionic-cli/issues/452 - var indexPath = path.join(__dirname, 'bomindex.html'); + var indexPath = path.join(__dirname, 'artifacts/bomindex.html'); spyOn(Math, 'floor').andReturn(5555); Q() @@ -108,7 +108,7 @@ describe('Upload', function() { }); it('should remove ionic cache buster attributes', function(done) { - var indexPath = path.join(__dirname, 'cachebustedindex.html'); + var indexPath = path.join(__dirname, 'artifacts/cachebustedindex.html'); Q() .then(function() {