diff --git a/lib/config-xml.js b/lib/config-xml.js index f94b8dd..61b0dc5 100644 --- a/lib/config-xml.js +++ b/lib/config-xml.js @@ -2,7 +2,7 @@ var fs = require('fs'), path = require('path'), Q = require('q'), xml2js = require('xml2js'), - logging = require('./logging'); + log = require('./logging').logger; var ConfigXml = module.exports; @@ -44,7 +44,7 @@ ConfigXml.setConfigXml = function setConfigXml(appDirectory, options) { appDirectory = process.cwd(); } - logging.logger.debug('ConfigXml.setConfigXml', appDirectory, options); + log.debug('ConfigXml.setConfigXml', appDirectory, options); var configXmlPath = path.join(appDirectory, 'config.xml'); diff --git a/lib/cordova.js b/lib/cordova.js index 88ba067..d5ddbe7 100644 --- a/lib/cordova.js +++ b/lib/cordova.js @@ -5,7 +5,7 @@ var argv = require('optimist').boolean(['nohooks', 'n', 'r', 'noresources', 'nos // Hooks = require('./hooks'), State = require('./state'), Q = require('q'), - logging = require('./logging'); + log = require('./logging').logger; var Cordova = module.exports; @@ -136,7 +136,7 @@ Cordova.runCordova = function runCordova(cmdName) { Cordova.setupLiveReload = function() { var d = Q.defer(); - logging.logger.info('Setup Live Reload'.green.bold); + log.info('Setup Live Reload'); var self = this; var serve = new require('./serve'); @@ -179,7 +179,7 @@ Cordova.setupLiveReload = function() { Cordova.addPlatform = function addPlatform(projectRoot, platform, savePlatform) { - logging.logger.debug('Cordova.addPlatform: ', projectRoot, platform, savePlatform); + log.debug('Cordova.addPlatform: ', projectRoot, platform, savePlatform); // var opts = { // searchpath : args.searchpath // , noregistry : args.noregistry @@ -202,7 +202,7 @@ Cordova.addPlatform = function addPlatform(projectRoot, platform, savePlatform) //logging.logger.info(('Added ' + platform + ' platform').green); process.env.PWD = originalPwd; if (savePlatform) { - logging.logger.debug('Cordova.addPlatform call specified to save platform. Saving to package.json now.'); + log.debug('Cordova.addPlatform call specified to save platform. Saving to package.json now.'); return State.savePlatform(projectRoot, platform); } }); @@ -247,7 +247,7 @@ Cordova.runPlatform = function runPlatform(projectRoot, platform) { Cordova.addPlugin = function addPlugin(projectRoot, pluginId, pluginVariables, savePlugin) { - logging.logger.debug('Cordova.addPlugin: projectRoot', projectRoot, 'pluginId', pluginId, 'pluginVariables', pluginVariables, 'savePlugin', savePlugin); + log.debug('Cordova.addPlugin: projectRoot', projectRoot, 'pluginId', pluginId, 'pluginVariables', pluginVariables, 'savePlugin', savePlugin); var originalPwd = process.env.PWD; process.env.PWD = projectRoot; @@ -262,7 +262,7 @@ Cordova.addPlugin = function addPlugin(projectRoot, pluginId, pluginVariables, s } }) .catch(function(error) { - logging.logger.error('Error occurred while adding plugin: ', error); + log.error('Error occurred while adding plugin: ', error); throw error; }); }; diff --git a/lib/hooks.js b/lib/hooks.js index 2190219..840127d 100644 --- a/lib/hooks.js +++ b/lib/hooks.js @@ -1,7 +1,7 @@ var fs = require('fs'), path = require('path'), shelljs = require('shelljs'), - logging = require('./logging'); + log = require('./logging').logger; var Hooks = module.exports; @@ -42,7 +42,7 @@ Hooks.addHookScript = function addHookScript(appDirectory, cliHookPath, hookDire var cliScript = path.join(cliHookPath, hookFilename); fs.writeFileSync(projectScript, fs.readFileSync(cliScript)); } catch(e) { - logging.logger.error('addCliHookDirectory fs.createReadStream: %'.error, e, {}); + log.error('addCliHookDirectory fs.createReadStream: %', e, {}); return; } } @@ -51,16 +51,16 @@ Hooks.addHookScript = function addHookScript(appDirectory, cliHookPath, hookDire try { fs.chmodSync(projectScript, '755'); } catch(e) { - logging.logger.error('addCliHookDirectory fs.chmodSync: %s'.error, e, {}); + log.error('addCliHookDirectory fs.chmodSync: %s', e, {}); } } catch(e) { - logging.logger.error('Error adding hook script ' + hookDirectoryName + '/' + hookFilename + ', %s', e, {}); + log.error('Error adding hook script ' + hookDirectoryName + '/' + hookFilename + ', %s', e, {}); } }; Hooks.add = function add(appDirectory) { - logging.logger.info('Adding in default Ionic Cordova hooks'.blue.bold); + log.info('Adding in default Ionic Cordova hooks'); // Add hooks which this Ionic project doesn't already have // note: hook scripts must be executable! @@ -80,12 +80,11 @@ Hooks.add = function add(appDirectory) { } }); - logging.logger.info('Added default Ionic Cordova hooks'.green.bold) - + log.info('Added default Ionic Cordova hooks'); }; Hooks.remove = function remove(appDirectory) { - logging.logger.info('Removing the Ionic Cordova plugin hooks'.blue.bold) + log.info('Removing the Ionic Cordova plugin hooks') var oldPluginHooks = [ 'after_platform_add/010_install_plugins.js', 'after_plugin_add/010_register_plugin.js', @@ -99,8 +98,7 @@ Hooks.remove = function remove(appDirectory) { } catch(ex) { } }) - logging.logger.info('Removed the Ionic Cordova hooks'.green.bold); - + log.info('Removed the Ionic Cordova hooks'); }; @@ -127,13 +125,13 @@ Hooks.setHooksPermission = function setHooksPermission(appDirectory) { try { fs.chmodSync(path.resolve(hooksPath, hookDir, hook), '755'); } catch(e) { - logging.logger.error('Hooks.setHooksPermission fs.chmodSync: %s'.error, e, {}); + log.error('Hooks.setHooksPermission fs.chmodSync: %s', e, {}); } }) }); } catch (ex) { - logging.logger.error('Error: %s', ex); + log.error('Error: %s', ex); } - logging.logger.debug('Updated the hooks directory to have execute permissions'.green); + log.debug('Updated the hooks directory to have execute permissions'); }; diff --git a/lib/info.js b/lib/info.js index c7ff569..aa88076 100644 --- a/lib/info.js +++ b/lib/info.js @@ -2,7 +2,7 @@ var path = require('path'), shelljs = require('shelljs'), os = require('os'), semver = require('semver'), - logging = require('./logging'); + log = require('./logging').logger; var Info = module.exports; @@ -252,42 +252,42 @@ Info.gatherInfo = function gatherInfo() { }; Info.printInfo = function printInfo(info) { - logging.logger.info('\nYour system information:\n'); + log.info('\nYour system information:\n'); - logging.logger.info('Cordova CLI:', info.cordova); + log.info('Cordova CLI:', info.cordova); if (info.gulp) { - logging.logger.info('Gulp version:', info.gulp); - logging.logger.info('Gulp local: ', info.gulp_local); + log.info('Gulp version:', info.gulp); + log.info('Gulp local: ', info.gulp_local); } if (info.ionic) { - logging.logger.info('Ionic Framework Version:', info.ionic); + log.info('Ionic Framework Version:', info.ionic); } if (info.ionic_cli) { - logging.logger.info('Ionic CLI Version:', info.ionic_cli); + log.info('Ionic CLI Version:', info.ionic_cli); } if (info.ionic_lib) { - logging.logger.info('Ionic App Lib Version:', info.ionic_lib); + log.info('Ionic App Lib Version:', info.ionic_lib); } if (info.ios_deploy) { - logging.logger.info('ios-deploy version:', info.ios_deploy) + log.info('ios-deploy version:', info.ios_deploy) } if(info.ios_sim) { - logging.logger.info('ios-sim version:', info.ios_sim); + log.info('ios-sim version:', info.ios_sim); } - logging.logger.info('OS:', info.os); - logging.logger.info('Node Version:', info.node); + log.info('OS:', info.os); + log.info('Node Version:', info.node); if(info.xcode) { - logging.logger.info('Xcode version:', info.xcode); + log.info('Xcode version:', info.xcode); } - logging.logger.info('\n'); + log.info('\n'); }; Info.checkRuntime = function checkRuntime() { @@ -306,7 +306,7 @@ Info.checkRuntime = function checkRuntime() { } catch (ex) { } - logging.logger.debug('System Info:', info); + log.debug('System Info:', info); if (info.ios_sim !== 'Not installed') { iosSimInstalled = true; @@ -323,33 +323,33 @@ Info.checkRuntime = function checkRuntime() { var showDepdencyWarning = nodeUpgrade || (!cordovaInstalled || cordovaUpgrade) || checkOsxDeps; if (showDepdencyWarning) { - logging.logger.info('******************************************************'.yellow.bold); - logging.logger.info(' Dependency warning - for the CLI to run correctly, '.yellow.bold); - logging.logger.info(' it is highly recommended to install/upgrade the following: '.yellow.bold); - logging.logger.info(''); + log.warn('******************************************************'); + log.warn(' Dependency warning - for the CLI to run correctly, '); + log.warn(' it is highly recommended to install/upgrade the following: '); + log.warn(''); if(nodeUpgrade) { var updateMessage = [' Please update your Node runtime to version ', requirements.node].join(' '); - logging.logger.info(updateMessage.yellow.bold); + log.warn(updateMessage); validRuntime = false; } if(!cordovaInstalled || cordovaUpgrade) { var action = cordovaInstalled ? 'update' : 'install'; updateMessage = [' Please', action, 'your Cordova CLI to version ', requirements.cordova, '`npm install -g cordova`'].join(' ') - logging.logger.info(updateMessage.yellow.bold); + log.warn(updateMessage); validRuntime = false; } if (info.ios_sim === 'Not installed') { - logging.logger.info(' Install ios-sim to deploy iOS applications. `npm install -g ios-sim` (may require sudo)'.yellow.bold); + log.warn(' Install ios-sim to deploy iOS applications. `npm install -g ios-sim` (may require sudo)'); } if (info.ios_deploy === 'Not installed') { - logging.logger.info(' Install ios-deploy to deploy iOS applications to devices. `npm install -g ios-deploy` (may require sudo)'.yellow.bold); + log.warn(' Install ios-deploy to deploy iOS applications to devices. `npm install -g ios-deploy` (may require sudo)'); } - logging.logger.info(''); - logging.logger.info('******************************************************'.yellow.bold); + log.warn(''); + log.warn('******************************************************'); } return validRuntime; diff --git a/lib/io-config.js b/lib/io-config.js index 3d5ce2a..dc73fc3 100644 --- a/lib/io-config.js +++ b/lib/io-config.js @@ -6,7 +6,7 @@ var fs = require('fs'), Q = require('q'), settings = require('./settings'), cheerio = require('cheerio'), - logging = require('./logging'); + log = require('./logging').logger; var IoConfig = module.exports; @@ -105,7 +105,7 @@ IoConfig.listConfig = function listConfig() { fs.readFile(CONFIG_BACKUP, function(err, data) { if (err) { if (!err.code === 'ENOENT') { - logging.logger.error('Error reading config', err); + log.error('Error reading config', err); } } else if (data) { var jsonObj = JSON.parse(data); @@ -123,7 +123,7 @@ IoConfig.listConfig = function listConfig() { while (item.key.length < longest) { item.key += ' '; } - logging.logger.info(item.key + item.value); + log.info(item.key + item.value); }); } }); @@ -200,9 +200,9 @@ IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { deferred.reject(new Error(error)); } else { if (key) { - logging.logger.info("Saved " + key + ", writing to ionic.io.bundle.min.js..."); + log.info("Saved " + key + ", writing to ionic.io.bundle.min.js..."); } else { - logging.logger.info('Building platform config...') + log.info('Building platform config...') } IoConfig.isCoreAvailable().then(function(available) { if (available) { @@ -218,7 +218,7 @@ IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { deferred.resolve(key); }); } else { - console.error('Unable to build the config factory'.red); + log.error('Unable to build the config factory'); deferred.resolve(key); } }); @@ -235,7 +235,7 @@ IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { deferred.resolve(key); }); } else { - logging.logger.error('Unable to build the config factory'.red); + log.error('Unable to build the config factory'); deferred.resolve(key); } }); @@ -247,7 +247,7 @@ IoConfig.writeIoConfig = function writeIoConfig(key, val, set) { }); }); } else { - logging.logger.error('Unauthorized configuration value'.red); + log.error('Unauthorized configuration value'); deferred.reject("Unauthorized configuration value"); } return deferred.promise; @@ -287,7 +287,7 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { if (!disable) { fs.readFile(INDEX_FILE, function(err, data) { if (err) { - logging.logger.error("ERROR: ", err); + log.error("ERROR: ", err); deferred.reject(new Error(err)); } else { var exists = false; @@ -303,10 +303,10 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { if ($(this).attr('src') === "cordova.js" && name === "ionic.service.core" && set) { $(this).replaceWith("\n"); } else if (!set && $(this).attr('src') === ioPath) { - logging.logger.info("Deleting component from index.html"); + log.info("Deleting component from index.html"); $(this).remove(); } else if (!set && $(this).attr('src') === ioMinPath) { - console.log("Deleting component from index.html"); + log.info("Deleting component from index.html"); $(this).remove(); } else if (set && $(this).attr('src') === ioMinPath) { exists = true; @@ -315,7 +315,7 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { } }); if (set && !exists) { - logging.logger.info('Adding component to index.html'); + log.info('Adding component to index.html'); var newScript = "\n"; if (coreScript && name !== 'ionic.service.core') { $(coreScript).after(newScript); @@ -337,7 +337,7 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { } fs.writeFile(INDEX_FILE, $.html(), function(error) { if (err) { - logging.logger.error("ERROR: ", error); + log.error("ERROR: ", error); deferred.reject(new Error(error)); } }); @@ -345,8 +345,8 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { }); fs.readFile(APP_FILE, function(err, data) { if (err) { - logging.logger.error("ERROR: ", err); - logging.logger.error("Is your app declaration contained in 'app.js'?"); + log.error("ERROR: ", err); + log.error("Is your app declaration contained in 'app.js'?"); deferred.reject(new Error(err)); } else { // Parse the file to string and remove existing references to the component @@ -354,7 +354,7 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { jsFile = jsFile.replace("\'" + name + "\',", ''); jsFile = jsFile.replace('\"' + name + '\",', ''); if (set) { - logging.logger.info('Injecting ' + name + ' into app.js'); + log.info('Injecting ' + name + ' into app.js'); if (name === 'ionic.service.core') { jsFile = jsFile.replace("\'ionic\',", "\'ionic\'," + "\'" + name + "\',"); jsFile = jsFile.replace('\"ionic\",', '\"ionic\",' + "\'" + name + "\',"); @@ -363,11 +363,11 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { jsFile = jsFile.replace('\"ionic.service.core\",', '\"ionic.service.core\",' + "\'" + name + "\',"); } } else { - logging.logger.info('Removing ' + name + ' from app.js'); + log.info('Removing ' + name + ' from app.js'); } fs.writeFile(APP_FILE, jsFile, function(error) { if (err) { - logging.logger.error("ERROR: ", error); + log.error("ERROR: ", error); deferred.reject(new Error(error)); } else { deferred.resolve(true); @@ -376,7 +376,7 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { } }); } else { - logging.logger.warn('Automatic file manipulation disabled, please manually inject components.'.yellow); + log.warn('Automatic file manipulation disabled, please manually inject components.'); deferred.resolve(true); } }); @@ -385,7 +385,7 @@ IoConfig.injectIoComponent = function injectIoComponent(set, component) { }; IoConfig.initIoPlatform = function initIoPlatform(appDirectory, jar) { - logging.logger.info('Initializing app with ionic.io....'.green.bold); + log.info('Initializing app with ionic.io....'); var project = IonicProject.load(appDirectory); var documentRoot = project.get('documentRoot') || 'www'; @@ -397,29 +397,29 @@ IoConfig.initIoPlatform = function initIoPlatform(appDirectory, jar) { IoConfig.writeIoConfig('api_key', key.api_key, true).then(function(apiKey){ IoConfig.warnMissingData(); }, function(error) { - logging.logger.error('Error saving API key:', error); + log.error('Error saving API key:', error); }); } }, function(error) { - logging.logger.error('Error saving app ID:', error); + log.error('Error saving app ID:', error); }); // Set project vars project.set('app_id', key.app_id); project.save(); }) .catch(function(ex) { - logging.logger.error('An error occurred initializing the app: %s', ex, {}); + log.error('An error occurred initializing the app: %s', ex, {}); throw ex; }); } catch(ex) { - logging.logger.error("Error initializing app: %s", ex, {}); + log.error("Error initializing app: %s", ex, {}); } } IoConfig.dashInit = function dashInit(project, jar) { var q = Q.defer(); - logging.logger.debug('Getting app information from ', settings.IONIC_DASH); + log.debug('Getting app information from ', settings.IONIC_DASH); var csrftoken = Utils.retrieveCsrfToken(jar); request.post({ diff --git a/lib/logging.js b/lib/logging.js index e288f98..8ad9331 100644 --- a/lib/logging.js +++ b/lib/logging.js @@ -8,6 +8,7 @@ Logging.logger = new winston.Logger({ transports: [ new (winston.transports.Console)({ name: 'console', + colorize: 'all', showLevel: false }) ] @@ -18,6 +19,7 @@ Logging.createLogger = function createLogger(transports, level) { level = level || 'info'; return Logging.logger = new winston.Logger({ exitOnError: false, + colors: { info: 'strip' }, level: level, transports: transports }); @@ -28,6 +30,7 @@ Logging.createDefaultLogger = function createDefaultLogger(level) { var transports = [ new (winston.transports.Console)({ name: 'console', + colorize: 'all', showLevel: false }) ]; @@ -38,7 +41,7 @@ Logging.createLoggerWithFile = function createLoggerWithFile(logFilePath, level) var transports = [ new (winston.transports.File)({ filename: logFilePath, - name: 'file' + name: 'file' }) ]; return Logging.createLogger(transports, level); diff --git a/lib/login.js b/lib/login.js index b747fd6..3c028c6 100644 --- a/lib/login.js +++ b/lib/login.js @@ -5,7 +5,7 @@ var request = require('request'), Q = require('q'), settings = require('./settings'), Utils = require('./utils'), - logging = require('./logging'); + log = require('./logging').logger; var Login = module.exports; @@ -76,8 +76,8 @@ Login.run = function(ionic, callback) { }]; // prompt for log - logging.logger.info('\nTo continue, please login to your Ionic account.'.bold.green); - logging.logger.info('Don\'t have one? Create a one at: '.bold + (settings.IONIC_DASH + '/signup').bold + '\n'); + log.info('\nTo continue, please login to your Ionic account.'); + log.info('Don\'t have one? Create a one at: '.bold + (settings.IONIC_DASH + '/signup').bold + '\n'); prompt.override = argv; prompt.message = ''; @@ -135,7 +135,7 @@ Login.requestLogIn = function requestLogin(email, password, saveCookies) { var jsonString = JSON.stringify(jar.getCookies(settings.IONIC_DASH, null, 2)); transformedCookies = JSON.parse(jsonString); } catch(ex) { - logging.logger.error('Invalid cookies from jar.getCookies'.red.bold); + log.error('Invalid cookies from jar.getCookies'); } } @@ -169,7 +169,7 @@ Login.saveCookies = function saveCookies(jar) { // save in memory Login.jar = transformedCookies; } catch (ex) { - logging.logger.error('Invalid cookies from jar.getCookies'.red.bold); + log.error('Invalid cookies from jar.getCookies'); } return transformedCookies; @@ -203,7 +203,7 @@ Login.getUserInfo = function getUserInfo(jar) { var data = JSON.parse(body); q.resolve(data); } catch (ex) { - logging.logger.error('Error: ', ex); + log.error('Error: ', ex); q.reject(ex); } }); @@ -236,7 +236,7 @@ Login.getUserApps = function getUserApps(jar) { var data = JSON.parse(body); q.resolve(data); } catch (ex) { - logging.logger.error('Error: ', ex); + log.error('Error: ', ex); q.reject(ex); } }); @@ -269,7 +269,7 @@ Login.getDownloadLink = function getDownloadLink(jar, appId) { var data = JSON.parse(body); q.resolve(data.download_url); } catch (ex) { - logging.logger.error('Error: ', ex); + log.error('Error: ', ex); q.reject(ex); } }); diff --git a/lib/package.js b/lib/package.js index 3d2092e..8a88634 100644 --- a/lib/package.js +++ b/lib/package.js @@ -11,24 +11,24 @@ var fs = require('fs'), IonicResources = require('./resources'), Utils = require('./utils'), settings = require('./settings'), - logging = require('./logging'); + log = require('./logging').logger; var Package = module.exports; events.on('package-start', function() { - var logLevel = logging.logger.level; - logging.logger.level = 'error'; + var logLevel = log.level; + log.level = 'error'; events.on('package-post-default-resources', function() { - logging.logger.level = logLevel; + log.level = logLevel; }); events.on('package-pre-prepare-resources', function() { - logging.logger.level = 'error'; + log.level = 'error'; }); events.on('package-post-prepare-resources', function() { - logging.logger.level = logLevel; + log.level = logLevel; }); }); @@ -71,12 +71,12 @@ Package.listBuilds = function(appId, jar) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } if (response.statusCode != 200) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in package service."); } @@ -104,12 +104,12 @@ Package.getBuild = function(appId, jar, buildId, extraQueryParams) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } if (response.statusCode != 200) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in package service."); } @@ -187,7 +187,7 @@ function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { return promise .then(function() { - logging.logger.info("Uploading your app to Ionic..."); + log.info("Uploading your app to Ionic..."); return Upload.doUpload(appDirectory, jar, 'Ionic Package Upload'); }) .then(function(upload) { @@ -196,7 +196,7 @@ function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { } events.emit('package-post-upload'); - logging.logger.info("Upload complete!"); + log.info("Upload complete!"); uploadUrl = upload.url; }) @@ -213,7 +213,7 @@ function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { .then(function(url) { if (typeof options.noresources === 'undefined') { events.emit('package-post-default-resources'); - logging.logger.info('Preparing your resources...'); + log.info('Preparing your resources...'); events.emit('package-pre-prepare-resources'); return IonicResources.generate(appDirectory, { platforms: ['all'] }); } @@ -281,7 +281,7 @@ function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { .then(function(body) { projectZipId = body.data.id; - logging.logger.info("Uploading your project to Ionic..."); + log.info("Uploading your project to Ionic..."); return uploadProjectZip( body.data.presigned_post.url, @@ -299,7 +299,7 @@ function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { _.extend(formData, { security_profile_tag: profileTag }); } - logging.logger.info("Submitting your app to Ionic Package..."); + log.info("Submitting your app to Ionic Package..."); return sendToPackageService(appId, jar, _.extend(formData, formDataExtra)); }) @@ -307,9 +307,9 @@ function build(appDirectory, jar, appId, profileTag, formDataExtra, options) { var buildId = body.data.id; events.emit('package-post-submit'); - logging.logger.info("Your app has been successfully submitted to Ionic Package!".green); - logging.logger.info('Build ID:', buildId); - logging.logger.info("We are now packaging your app."); + log.info("Your app has been successfully submitted to Ionic Package!".green); + log.info('Build ID:', buildId); + log.info("We are now packaging your app."); fs.unlinkSync(projectZipPath); @@ -334,12 +334,12 @@ function sendProjectZip(appId, jar) { } }, function (err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } if (response.statusCode != 200) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in package service."); } @@ -362,12 +362,12 @@ function uploadProjectZip(url, formData, projectZipPath) { proxy: process.env.PROXY || process.env.http_proxy || null }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } if (response.statusCode != 204) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in package service."); } @@ -395,17 +395,17 @@ function sendToPackageService(appId, jar, formData) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } if (response.statusCode == 400) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Bad request to package service."); } if (response.statusCode != 202) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in package service."); } diff --git a/lib/resources.js b/lib/resources.js index fa155c9..737e963 100644 --- a/lib/resources.js +++ b/lib/resources.js @@ -8,7 +8,7 @@ var fs = require('fs'), crc = require('crc'), shelljs = require('shelljs'), Utils = require('./utils'), - logging = require('./logging'); + log = require('./logging').logger; var appDirectory; var tmpDir = os.tmpdir(); @@ -140,14 +140,14 @@ function generate(dir, options) { orientation = 'default'; if (!fs.existsSync(path.join(appDirectory, Settings.configFile))) { - logging.logger.error('Invalid ' + Settings.configFile + ' file. Make sure the working directory is a Cordova project.'); + log.error('Invalid ' + Settings.configFile + ' file. Make sure the working directory is a Cordova project.'); return Q.reject('INVALID_CONFIG_FILE'); } if (options.default) { if (hasExistingResources(appDirectory) && !options.force) { - logging.logger.info('The resources folder already exists. We will not overwrite your files unless you pass the --force argument.'.red.bold); - logging.logger.info('Running with the force flag will overwrite your resources directory and modify your config.xml file'.red.bold) + log.error('The resources folder already exists. We will not overwrite your files unless you pass the --force argument.'); + log.error('Running with the force flag will overwrite your resources directory and modify your config.xml file') return Q.reject('RESOURCES_EXISTS'); } @@ -182,9 +182,9 @@ function generate(dir, options) { } if (!hasPlatforms) { - logging.logger.error('No platforms have been added.'); - logging.logger.error('Please add a platform, for example: ionic platform add ios'); - logging.logger.error('Or provide a platform name, for example: ionic resources android'); + log.error('No platforms have been added.'); + log.error('Please add a platform, for example: ionic platform add ios'); + log.error('Or provide a platform name, for example: ionic resources android'); return Q.reject('NO_PLATFORMS'); } @@ -216,13 +216,13 @@ function generate(dir, options) { var promises = []; if (options.icon || options.i) { - logging.logger.info('Ionic icon resources generator'); + log.info('Ionic icon resources generator'); promises.push(queueResTypeImages('icon')); } else if (options.splash || options.s) { - logging.logger.info('Ionic splash screen resources generator'); + log.info('Ionic splash screen resources generator'); promises.push(queueResTypeImages('splash')); } else { - logging.logger.info('Ionic icon and splash screen resources generator'); + log.info('Ionic icon and splash screen resources generator'); promises.push(queueResTypeImages('icon')); promises.push(queueResTypeImages('splash')); } @@ -331,8 +331,8 @@ function queueResTypeImages(resType) { msg += 'the resources directory'; } - logging.logger.error(msg); - logging.logger.error('valid ' + resType + ' source files: ' + validSourceFiles.join(', ')); + log.error(msg); + log.error('valid ' + resType + ' source files: ' + validSourceFiles.join(', ')); deferred.reject('MISSING_SOURCE_FILE'); } @@ -382,14 +382,14 @@ function queueResTypeImages(resType) { } if (Settings.cacheImages && fs.existsSync(image.tmpPath)) { - logging.logger.info(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') from cache'); + log.info(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') from cache'); } else { loadCachedSourceImageData(sourceFile); if (sourceFile.cachedData && !sourceFile.cachedData.vector && (sourceFile.cachedData.width < image.width || sourceFile.cachedData.height < image.height)) { image.skip = true; - logging.logger.error(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') skipped, source image ' + sourceFile.filename + ' (' + sourceFile.cachedData.width + 'x' + sourceFile.cachedData.height + ') too small'); + log.error(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') skipped, source image ' + sourceFile.filename + ' (' + sourceFile.cachedData.width + 'x' + sourceFile.cachedData.height + ') too small'); } else { sourceFile.upload = true; @@ -420,7 +420,7 @@ function loadSourceImages() { var deferred = Q.defer(); - logging.logger.info(' uploading ' + sourceFile.filename + '...'); + log.info(' uploading ' + sourceFile.filename + '...'); var postData = { url: Settings.apiUrl + Settings.apiUploadPath, @@ -469,9 +469,9 @@ function loadSourceImages() { sourceFile.height = d.Height; sourceFile.vector = d.Vector; if (sourceFile.vector) { - logging.logger.info(sourceFile.filename + ' (vector image) upload complete'); + log.info(sourceFile.filename + ' (vector image) upload complete'); } else { - logging.logger.info(sourceFile.filename + ' (' + d.Width + 'x' + d.Height + ') upload complete'); + log.info(sourceFile.filename + ' (' + d.Width + 'x' + d.Height + ') upload complete'); } cacheSourceImageData(sourceFile); @@ -498,10 +498,10 @@ function cacheSourceImageData(sourceFile) { }); var cachedImagePath = path.join(tmpDir, sourceFile.imageId + '.json'); fs.writeFile(cachedImagePath, data, function(err) { - if (err) logging.logger.error('Error writing cacheSourceImageData: ' + err); + if (err) log.error('Error writing cacheSourceImageData: ' + err); }); } catch (e) { - logging.logger.error('Error cacheSourceImageData: ' + e); + log.error('Error cacheSourceImageData: ' + e); } } @@ -560,15 +560,15 @@ function generateResourceImage(image) { if (!sourceFile.vector && (sourceFile.width < image.width || sourceFile.height < image.height)) { image.skip = true; - logging.logger.error(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') skipped, source image ' + sourceFile.filename + ' (' + sourceFile.width + 'x' + sourceFile.height + ') too small'); + log.error(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') skipped, source image ' + sourceFile.filename + ' (' + sourceFile.width + 'x' + sourceFile.height + ') too small'); deferred.resolve(); } else if (generatingImages[image.tmpPath]) { - logging.logger.info(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') generated'); + log.info(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') generated'); deferred.resolve(); } else { - logging.logger.info(' generating ' + image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ')...'); + log.info(' generating ' + image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ')...'); generatingImages[image.tmpPath] = true; var postData = { @@ -588,12 +588,12 @@ function generateResourceImage(image) { var wr = fs.createWriteStream(image.tmpPath, { flags: 'w' }); wr.on("error", function(err) { - logging.logger.error('Error copying to ' + image.tmpPath + ': ' + err); + log.error('Error copying to ' + image.tmpPath + ': ' + err); deferred.resolve(); }); wr.on("finish", function() { if (!image.skip) { - logging.logger.info(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') generated'); + log.info(image.resType + ' ' + image.platform + ' ' + image.name + ' (' + image.width + 'x' + image.height + ') generated'); deferred.resolve(); } }); @@ -666,7 +666,7 @@ function getConfigData(appDirectory) { fs.readFile(path.join(appDirectory, Settings.configFile), function(err, data) { if (err) { - logging.logger.error('Error reading config file: ' + err); + log.error('Error reading config file: ' + err); deferred.reject(); return; } @@ -675,14 +675,14 @@ function getConfigData(appDirectory) { var parser = new xml2js.Parser(); parser.parseString(data, onXmlParse); } catch (e) { - logging.logger.error('Error xml2js parseString: ' + e); + log.error('Error xml2js parseString: ' + e); deferred.reject(); } }); function onXmlParse(err, parsedData) { if (err) { - logging.logger.error('Error parsing config file: ' + err); + log.error('Error parsing config file: ' + err); deferred.reject(); return; } @@ -837,7 +837,7 @@ function writeConfigData(appDirectory, configData) { fs.writeFile(path.join(appDirectory, Settings.configFile), xmlString, function(err) { if (err) { var msg = 'Error writing config data: ' + err; - logging.logger.error(msg); + log.error(msg); return deferred.reject(msg); } @@ -859,7 +859,7 @@ function addIonicIcons(appDirectory, platform, forceAddResources) { var promise = null; if(forceAddResources) { - logging.logger.info('forceAddResources') + log.info('forceAddResources') promise = copyIconFilesIntoResources(appDirectory, forceAddResources); } else { promise = Q(); @@ -871,7 +871,7 @@ function addIonicIcons(appDirectory, platform, forceAddResources) { }) .then(function(data) { if(!data.widget.platform || (data.widget.platform.length == 1 && data.widget.platform[0]['$'].name != platform)) { - logging.logger.debug('Adding icons for platform:'.blue.bold, platform.green) + log.debug('Adding icons for platform:'.blue.bold, platform.green) addPlatformIcons(platform, data) addSplashScreenPreferences(data) @@ -901,19 +901,19 @@ function copyIconFilesIntoResources(appDirectory, forceAddResources) { var unzipPath = path.join(appDirectory, 'resources'); if (hasExistingResources(appDirectory) && !forceAddResources) { - // logging.logger.info('Not copying over default resources, the resources directory already exist. Please pass the --force argument to overwrite that folder'.red.bold); + // log.info('Not copying over default resources, the resources directory already exist. Please pass the --force argument to overwrite that folder'.red.bold); return Q(); } var ionicResourcesUrl = 'https://github.com/driftyco/ionic-default-resources/archive/master.zip'; - logging.logger.debug('uzip to: ', unzipPath) - //logging.logger.info('Downloading Default Ionic Resources'.yellow); + log.debug('uzip to: ', unzipPath) + //log.info('Downloading Default Ionic Resources'.yellow); return Utils.fetchArchive(unzipPath, ionicResourcesUrl) .then(function() { shelljs.config.silent = true shelljs.mv('resources/ionic-default-resources-master/*', 'resources') shelljs.rm('-rf', 'resources/ionic-default-resources-master') - //logging.logger.info('Done adding default Ionic resources'.yellow) + //log.info('Done adding default Ionic resources'.yellow) }) } diff --git a/lib/security.js b/lib/security.js index 76ee64c..848f96a 100644 --- a/lib/security.js +++ b/lib/security.js @@ -2,7 +2,7 @@ var Q = require('q'), request = require('request'), Utils = require('./utils'), settings = require('./settings'), - logging = require('./logging'); + log = require('./logging').logger; var Security = module.exports; @@ -27,7 +27,7 @@ Security.addProfile = function(appId, jar, name) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } @@ -36,7 +36,7 @@ Security.addProfile = function(appId, jar, name) { } if (response.statusCode != 201) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in security service."); } @@ -63,12 +63,12 @@ Security.listProfiles = function(appId, jar) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } if (response.statusCode != 200) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in security service."); } @@ -95,7 +95,7 @@ Security.getProfile = function(appId, jar, tag) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } @@ -104,7 +104,7 @@ Security.getProfile = function(appId, jar, tag) { } if (response.statusCode != 200) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in security service."); } @@ -151,7 +151,7 @@ function sendCredentials(appId, jar, profileTag, formData) { } }, function(err, response, body) { if (err) { - logging.logger.error("Error:", err); + log.error("Error:", err); return q.reject(err); } @@ -160,7 +160,7 @@ function sendCredentials(appId, jar, profileTag, formData) { } if (response.statusCode != 201) { - logging.logger.error("Body:", body); + log.error("Body:", body); return q.reject("Error in security service."); } diff --git a/lib/serve.js b/lib/serve.js index 210fa7c..dcf9319 100644 --- a/lib/serve.js +++ b/lib/serve.js @@ -16,7 +16,7 @@ var fs = require('fs'), Utils = require('./utils'), events = require('./events'), ports = require('./ports'), - logging = require('./logging'); + log = require('./logging').logger; var Serve = module.exports; @@ -68,7 +68,7 @@ Serve.listenForServerCommands = function listenForServerCommands(options) { } else if(input == 'consolelogs' || input == 'c') { options.printConsoleLogs = !options.printConsoleLogs; - logging.logger.info('Console log output: '.green + (options.printConsoleLogs ? 'enabled' : 'disabled')); + log.info('Console log output: ' + (options.printConsoleLogs ? 'enabled' : 'disabled')); if (options.printConsoleLogs) { events.removeAllListeners('consoleLog'); events.on('consoleLog', console.log); @@ -79,7 +79,7 @@ Serve.listenForServerCommands = function listenForServerCommands(options) { } else if(input == 'serverlogs' || input == 's') { options.printServerLogs = !options.printServerLogs; - logging.logger.info('Server log output: '.green + (options.printServerLogs ? 'enabled' : 'disabled')); + log.info('Server log output: ' + (options.printServerLogs ? 'enabled' : 'disabled')); } else if(input.match(/^go\([+\-]?[0-9]{1,9}\)$/)) { Serve._goToHistory(input, options); @@ -90,15 +90,15 @@ Serve.listenForServerCommands = function listenForServerCommands(options) { process.stdout.write("\u001b[2J\u001b[0;0H"); } else { - logging.logger.error('\nInvalid ionic server command'.error.bold); + log.error('\nInvalid ionic server command'); Serve.printCommandTips(); } - // logging.logger.debug('input: ', input); + // log.debug('input: ', input); rl.prompt(); }).on('close', function() { if (options.childProcess) { - logging.logger.info('Closing Gulp process'.yellow); + log.info('Closing Gulp process'); options.childProcess.kill('SIGTERM'); } process.exit(0); @@ -108,7 +108,7 @@ Serve.listenForServerCommands = function listenForServerCommands(options) { //isIonicServer = true when serving www directory, false when live reload Serve.checkPorts = function(isIonicServer, testPort, testHost, options) { - logging.logger.debug('Serve.checkports isIonicServer', isIonicServer, 'testPort:', testPort, 'testHost', testHost, 'options:', options); + log.debug('Serve.checkports isIonicServer', isIonicServer, 'testPort:', testPort, 'testHost', testHost, 'options:', options); var q = Q.defer(); var message = []; @@ -116,13 +116,13 @@ Serve.checkPorts = function(isIonicServer, testPort, testHost, options) { testHost = null; } - logging.logger.debug('Testing port:', testPort, 'Testing host:', testHost); + log.debug('Testing port:', testPort, 'Testing host:', testHost); ports.getPort({port: testPort, host: testHost}, function(err, port) { if(port != testPort) { message = ['The port ', testPort, ' was taken on the host ', options.address, ' - using port ', port, ' instead'].join(''); - logging.logger.info(message.yellow.bold); + log.warn(message); if(isIonicServer) { options.port = port; } else { @@ -140,12 +140,10 @@ Serve.loadSettings = function loadSettings(argv, project) { if (!argv) { var errorMessage = 'Serve.loadSettings - You must pass proper arguments to load settings from'; - logging.logger.info(errorMessage); throw new Error(errorMessage); } if (!project) { var errorMessage = 'Serve.loadSettings - You must pass a project object to pull out project specific settings from'; - logging.logger.info(errorMessage); throw new Error(errorMessage); } @@ -205,13 +203,13 @@ Serve.loadSettings = function loadSettings(argv, project) { Serve.printCommandTips = function(ionic) { - logging.logger.info('Ionic server commands, enter:'.green.bold); - logging.logger.info(' restart' + ' or '.green + 'r' + ' to restart the client app from the root'.green); - logging.logger.info(' goto' + ' or '.green + 'g' + ' and a url to have the app navigate to the given url'.green); - logging.logger.info(' consolelogs' + ' or '.green + 'c' + ' to enable/disable console log output'.green); - logging.logger.info(' serverlogs' + ' or '.green + 's' + ' to enable/disable server log output'.green); - logging.logger.info(' quit' + ' or '.green + 'q' + ' to shutdown the server and exit'.green); - logging.logger.info(''); + log.info('Ionic server commands, enter:'); + log.info(' restart' + ' or ' + 'r' + ' to restart the client app from the root'); + log.info(' goto' + ' or ' + 'g' + ' and a url to have the app navigate to the given url'); + log.info(' consolelogs' + ' or ' + 'c' + ' to enable/disable console log output'); + log.info(' serverlogs' + ' or ' + 's' + ' to enable/disable server log output'); + log.info(' quit' + ' or ' + 'q' + ' to shutdown the server and exit'); + log.info(''); }; Serve.openBrowser = function openBrowser(options) { @@ -230,7 +228,7 @@ Serve.openBrowser = function openBrowser(options) { try { open(openUrl.join(''), options.browser); } catch (ex) { - logging.logger.info('Error opening the browser - ', ex); + log.error('Error opening the browser - ', ex); } } } @@ -240,7 +238,7 @@ Serve.checkForDocumentRoot = function checkForDocumentRoot(options) { if (options.createDocumentRoot) { fs.mkdirSync(options.documentRoot); } else { - logging.logger.info('"' + options.documentRoot + '" directory cannot be found. Please make sure the working directory is an Ionic project.'); + log.info('"' + options.documentRoot + '" directory cannot be found. Please make sure the working directory is an Ionic project.'); return false; // return Utils.fail('"' + options.documentRoot + '" directory cannot be found. Please make sure the working directory is an Ionic project.'); } @@ -251,7 +249,7 @@ Serve.checkForDocumentRoot = function checkForDocumentRoot(options) { Serve.runLivereload = function runLivereload(options, app) { var q = Q.defer(); - logging.logger.debug('Running Live Reload with options', options); + log.debug('Running Live Reload with options', options); try { @@ -268,7 +266,7 @@ Serve.runLivereload = function runLivereload(options, app) { // absoluteWatchPaths.push(path.join(options.appDirectory, watchPath)); // }); - // logging.logger.debug('Absolute watch paths:', absoluteWatchPaths); + // log.debug('Absolute watch paths:', absoluteWatchPaths); vfs.watch(options.watchPatterns, {}, function(f) { //TODO: Move prototype to Serve._changed @@ -294,7 +292,7 @@ Serve.runLivereload = function runLivereload(options, app) { } catch (ex) { q.reject(ex); - logging.logger.error('Live Reload failed to start, error: %s', ex, {}); + log.error('Live Reload failed to start, error: %s', ex, {}); throw ex; // Utils.fail('Live Reload failed to start, error: ', ex.message); } @@ -315,14 +313,14 @@ Serve.setupProxy = function setupProxy(options, app) { opts.rejectUnauthorized = !(proxy.rejectUnauthorized === false); app.use(proxy.path, proxyMiddleware(opts)); - logging.logger.info('Proxy added:'.green.bold, proxy.path + " => " + url.format(proxy.proxyUrl)); + log.info('Proxy added:', proxy.path + " => " + url.format(proxy.proxyUrl)); } } }; Serve.startServer = function startServer(options, app) { options.devServer = Serve.host(options.address, options.port); - logging.logger.debug('Starting server at host address - ' + options.devServer); + log.debug('Starting server at host address - ' + options.devServer); var rootDirectory = path.join(options.appDirectory, options.documentRoot); // Serve up the www folder by default @@ -463,7 +461,7 @@ Serve.startServer = function startServer(options, app) { Utils.fail('Failed to start the Ionic server: ', ex.message); } - logging.logger.info('√ Running dev server: '.green.bold, options.devServer); + log.info('√ Running dev server: ', options.devServer); }; Serve.start = function start(options) { @@ -490,8 +488,8 @@ Serve.start = function start(options) { return Serve.runLivereload(options, app); }) .then(function(data) { - logging.logger.info('Running live reload server:'.green.bold, options.liveReloadServer); - logging.logger.info('Watching:'.green.bold, options.watchPatterns); + log.info('Running live reload server:', options.liveReloadServer); + log.info('Watching:', options.watchPatterns); return Serve.startServer(options, app); }) .then(function() { @@ -500,21 +498,21 @@ Serve.start = function start(options) { } }) .catch(function(error) { - logging.logger.error('Ionic serve failed - error: %s', error, {}); + log.error('Ionic serve failed - error: %s', error, {}); }); } catch(e) { var msg; if(e && (e + '').indexOf('EMFILE') > -1) { - msg = (e + '\n').error.bold + - 'The watch process has exceed the default number of files to keep open.\n'.error.bold + - 'You can change the default with the following command:\n\n'.error.bold + + msg = (e + '\n') + + 'The watch process has exceed the default number of files to keep open.\n' + + 'You can change the default with the following command:\n\n' + ' ulimit -n 1000\n\n' + - 'In the command above, it\'s setting the default to watch a max of 1000 files.\n\n'.error.bold; + 'In the command above, it\'s setting the default to watch a max of 1000 files.\n\n'; } else { - msg = ('server start error: ' + e.stack).error.bold; + msg = ('server start error: ' + e.stack); } - logging.logger.info(msg); + log.error(msg); throw msg; // process.exit(1); } @@ -527,12 +525,12 @@ Serve.showFinishedServeMessage = function showFinishedServeMessage(options) { Serve.serverLog = function(req, msg, options) { if (options.printServerLogs) { - var log = 'serve '.yellow; + var log = 'serve '; - log += (req.url.length > 60 ? req.url.substr(0, 57) + '...' : req.url).yellow; + log += (req.url.length > 60 ? req.url.substr(0, 57) + '...' : req.url); if(msg) { - log += ' ' + msg.yellow; + log += ' ' + msg; } var ua = (req.headers && req.headers['user-agent'] || ''); @@ -750,13 +748,13 @@ Serve._changed = function(filePath, options) { filePath = filePath.replace(pwd + '/', ''); if( filePath.indexOf('.css') > 0 ) { - logging.logger.info(('CSS changed: ' + filePath).green); + log.info('CSS changed: ' + filePath); } else if( filePath.indexOf('.js') > 0 ) { - logging.logger.info(('JS changed: ' + filePath).green); + log.info('JS changed: ' + filePath); } else if( filePath.indexOf('.html') > 0 ) { - logging.logger.info(('HTML changed: ' + filePath).green); + log.info('HTML changed: ' + filePath); } else { - logging.logger.info(('File changed: ' + filePath).green); + log.info('File changed: ' + filePath); } Serve._postToLiveReload( [filePath], options ); @@ -764,14 +762,14 @@ Serve._changed = function(filePath, options) { Serve._goToUrl = function(url, options) { - logging.logger.info(('Loading: ' + url).green); + log.info('Loading: ' + url); Serve._postToLiveReload( ['__ionic_goto_url__' + url], options ); }; Serve._goToHistory = function(goHistory, options) { goHistory = goHistory.replace('go(', '').replace(')', ''); - logging.logger.info(('History Go: ' + goHistory).green); + log.info('History Go: ' + goHistory); Serve._postToLiveReload( ['__ionic_history_go__' + goHistory], options ); }; @@ -786,7 +784,7 @@ Serve._postToLiveReload = function(files, options) { }) }, function(err, res, body) { if(err) { - logging.logger.error('Unable to update live reload: %s', err, {}); + log.error('Unable to update live reload: %s', err, {}); } }); @@ -866,21 +864,21 @@ Serve.getAddress = function(options) { return q.promise; } - logging.logger.info('\nMultiple addresses available.'.error.bold); - logging.logger.info('Please select which address to use by entering its number from the list below:'.error.bold); + log.info('\nMultiple addresses available.'); + log.info('Please select which address to use by entering its number from the list below:'); if (options.isPlatformServe) { - logging.logger.info('Note that the emulator/device must be able to access the given IP address'.small); + log.info('Note that the emulator/device must be able to access the given IP address'.small); } for (var x=0; x < addresses.length; x++) { - logging.logger.info((' ' + (x+1) + ') ' + addresses[x].address + ( addresses[x].dev ? ' (' + addresses[x].dev + ')' : '' )).yellow); + log.info((' ' + (x+1) + ') ' + addresses[x].address + ( addresses[x].dev ? ' (' + addresses[x].dev + ')' : '' ))); } var prompt = require('prompt'); var promptProperties = { selection: { name: 'selection', - description: 'Address Selection: '.yellow.bold, + description: 'Address Selection: ', required: true } }; @@ -892,9 +890,9 @@ Serve.getAddress = function(options) { prompt.get({properties: promptProperties}, function (err, promptResult) { if(err && err.message !== 'canceled') { - logging.logger.debug('User prompted to select address - an error occured: %s', err, {}); + log.debug('User prompted to select address - an error occured: %s', err, {}); q.reject(err); - return logging.logger.error(err); + return log.error(err); } // } else { // return q.resolve(false); @@ -905,7 +903,7 @@ Serve.getAddress = function(options) { if(selection == (x + 1) || selection == addresses[x].address || selection == addresses[x].dev) { options.address = addresses[x].address; if(!options.isAddressCmd) { - logging.logger.info('Selected address: '.green.bold + options.address); + log.info('Selected address: ' + options.address); } ionicConfig.set(addressConfigKey, options.address); prompt.resume(); @@ -950,8 +948,8 @@ Serve.stopServer = function stopServer() { if (runningServer) { runningServer.close(); lrServer.close(); - logging.logger.info('Server closed'); + log.info('Server closed'); } else { - logging.logger.info('Server not running'); + log.info('Server not running'); } } diff --git a/lib/share.js b/lib/share.js index 5f59c8a..4af5a80 100644 --- a/lib/share.js +++ b/lib/share.js @@ -4,7 +4,7 @@ var parseUrl = require('url').parse, Utils = require('./utils'), IonicProject = require('./project'), Settings = require('./settings'), - logging = require('./logging'); + log = require('./logging').logger; var Share = module.exports; @@ -39,7 +39,7 @@ Share.shareApp = function shareApp(appDirectory, jar, email) { // console.log(data); return q.reject('Error sharing: ' + err); } - logging.logger.info('An invite to view your app was sent.'.green); + log.info('An invite to view your app was sent.'); return q.resolve('An invite to view your app was sent.') }) }); diff --git a/lib/start.js b/lib/start.js index 5bfe080..2287f6e 100644 --- a/lib/start.js +++ b/lib/start.js @@ -18,7 +18,7 @@ var fs = require('fs'), Cordova = require('./cordova'), Hooks = require('./hooks'), ioLib = require('./io-config'), - logging = require('./logging'), + log = require('./logging').logger, IonicResources = require('./resources'), State = require('./state'); @@ -53,20 +53,20 @@ Start.runSpawnCommand = function runSpawnCommand(cmd, args) { var command = cmd + args.join(' '); var spawn = require('cross-spawn-async'); - logging.logger.debug('Running exec command:', command); + log.debug('Running exec command:', command); var spawned = spawn(cmd, args); spawned.on('error', function(err){ Utils.fail('Unable to run spawn command' + err); }) spawned.stdout.on('data', function(data){ - logging.logger.debug(data.toString()); + log.debug(data.toString()); }); spawned.stderr.on('data', function(data){ - logging.logger.debug(data.toString()); + log.debug(data.toString()); }); spawned.on('exit', function(code){ - logging.logger.debug('Spawn command completed'); + log.debug('Spawn command completed'); if (code !== 0) { return q.reject('There was an error with the spawned command: ' + command); } @@ -99,7 +99,7 @@ Start.startApp = function startApp(options) { var createMessage = ['Creating Ionic app in folder ', options.targetPath, ' based on ', options.template.bold, ' project'].join(''); var errorWithStart = false; - logging.logger.info(createMessage); + log.info(createMessage); return Start.fetchWrapper(options) .then(function(data){ @@ -107,7 +107,7 @@ Start.startApp = function startApp(options) { }) .then(function() { if (!options.skipNpm) { - logging.logger.info('Installing npm packages...'); + log.info('Installing npm packages...'); return Start.runSpawnCommand('npm', ['install']); } }) @@ -152,7 +152,7 @@ Start.startApp = function startApp(options) { return Start.finalize(options); }) .catch(function(err) { - logging.logger.error('Error Initializing app: %s', err, {}); + log.error('Error Initializing app: %s', err, {}); // throw new Error('Unable to initalize app:') throw err; }) @@ -164,7 +164,7 @@ Start.startApp = function startApp(options) { Start.addDefaultPlatforms = function addDefaultPlatforms(options) { var currOs = os.type().toLowerCase(); if (currOs == 'darwin') { - logging.logger.info('\nAdding in iOS application by default'.green); + log.info('\nAdding in iOS application by default'); //Try to install default platform return Cordova.addPlatform(options.targetPath, 'ios', true) .then(function(v) { @@ -264,7 +264,7 @@ Start.loadAppSetup = function loadAppSetup(options) { appSetup = JSON.parse( fs.readFileSync(appJsonPath) ); rm('-rf', appJsonPath); } catch(e) { - logging.logger.error('app.json error: %s', e, {}); + log.error('app.json error: %s', e, {}); } } @@ -288,7 +288,7 @@ Start.fetchCreatorApp = function(options) { } if(!sessionId) { - logging.logger.error('\nPlease log in before starting a creator project. Run:\n\nionic login\n\n'); + log.error('\nPlease log in before starting a creator project. Run:\n\nionic login\n\n'); process.exit(1); } else { return _fetchCreatorApp(); @@ -301,7 +301,7 @@ Start.fetchCreatorApp = function(options) { var downloadUrl = IONIC_CREATOR_API_URL + path.join('/creator/' + appId + '/download-start/cordova?sid=' + sessionId); var wwwPath = path.join(options.targetPath, 'www/'); - logging.logger.info('\nDownloading Creator Project:'.bold, downloadUrl); + log.info('\nDownloading Creator Project:'.bold, downloadUrl); var q = Q.defer(); @@ -319,7 +319,7 @@ Start.fetchCreatorApp = function(options) { var readStream = fs.createReadStream(tempZipFilePath); readStream.on('error', function(err) { - logging.logger.debug(('unzipRepo readStream: ' + err).error); + log.debug('unzipRepo readStream error: ' + err); q.reject(err); }); @@ -328,7 +328,7 @@ Start.fetchCreatorApp = function(options) { q.resolve(); }); writeStream.on('error', function(err) { - logging.logger.debug(('unzipRepo writeStream: ' + err).error); + log.debug('unzipRepo writeStream: ' + err); q.reject(err); }); readStream.pipe(writeStream); @@ -353,7 +353,7 @@ Start.fetchCodepen = function(options) { codepenUrl = codepenUrl.substr(0, codepenUrl.length - 1); } - logging.logger.info('Downloading Codepen: ', codepenUrl.green.bold); + log.info('Downloading Codepen: ', codepenUrl); var qHTML = Q.defer(); var qCSS = Q.defer(); @@ -490,7 +490,7 @@ Start.fetchLocalStarter = function(options) { return q.promise; } - logging.logger.info('\nCopying files to www from:'.bold, localStarterPath); + log.info('\nCopying files to www from:'.bold, localStarterPath); // Move the content of this repo into the www folder cp('-Rf', path.join(localStarterPath, '*'), path.join(options.targetPath, 'www')); @@ -534,8 +534,8 @@ Start.fetchGithubStarter = function(options, repoUrl) { var urlParse = parseUrl(repoUrl); var pathSplit = urlParse.pathname.replace(/\//g, ' ').trim().split(' '); if(!urlParse.hostname || urlParse.hostname.toLowerCase() !== 'github.com' || pathSplit.length !== 2) { - logging.logger.error(('Invalid Github URL: ' + repoUrl).error ); - logging.logger.error(('Example of a valid URL: https://github.com/driftyco/ionic-starter-tabs/').error ); + log.error('Invalid Github URL: ' + repoUrl); + log.error('Example of a valid URL: https://github.com/driftyco/ionic-starter-tabs/'); Utils.fail(''); q.reject(); return q.promise; @@ -570,9 +570,9 @@ Start.fetchGithubStarter = function(options, repoUrl) { } }).catch(function(err) { - logging.logger.error('Please verify you are using a valid URL or a valid ionic starter.'); - logging.logger.error('View available starter templates: `ionic start --list`'); - logging.logger.error('More info available at: \nhttp://ionicframework.com/getting-started/\nhttps://github.com/driftyco/ionic-cli'); + log.error('Please verify you are using a valid URL or a valid ionic starter.'); + log.error('View available starter templates: `ionic start --list`'); + log.error('More info available at: \nhttp://ionicframework.com/getting-started/\nhttps://github.com/driftyco/ionic-cli'); return Utils.fail(''); }); @@ -583,7 +583,7 @@ Start.fetchZipStarter = function fetchZipStarter(options) { var q = Q.defer(); var repoFolderName = 'zipFileDownload'; - logging.logger.info('Fetching ZIP from url:', options.zipFileDownload.bold, 'to: ', options.targetPath); + log.info('Fetching ZIP from url:', options.zipFileDownload.bold, 'to: ', options.targetPath); Utils.fetchArchive(options.targetPath, options.zipFileDownload) .then(function() { @@ -602,10 +602,10 @@ Start.fetchZipStarter = function fetchZipStarter(options) { } }).catch(function(err) { - logging.logger.error(err); - logging.logger.error('Please verify you are using a valid URL or a valid ionic starter.'); - logging.logger.error('View available starter templates: `ionic templates`'); - logging.logger.error('More info available at: \nhttp://ionicframework.com/getting-started/\nhttps://github.com/driftyco/ionic-cli'); + log.error(err); + log.error('Please verify you are using a valid URL or a valid ionic starter.'); + log.error('View available starter templates: `ionic templates`'); + log.error('More info available at: \nhttp://ionicframework.com/getting-started/\nhttps://github.com/driftyco/ionic-cli'); return Utils.fail(''); }); @@ -649,7 +649,7 @@ Start.fetchPlnkr = function fetchPlnkr(options) { plnkrUrl = ['http://api.plnkr.co/plunks/', plnkrId, '.zip'].join(''); - logging.logger.info('\nDownloading Plnkr url:', plnkrUrl) + log.info('\nDownloading Plnkr url:', plnkrUrl) var extractPath = path.join(options.targetPath, 'plnkr'); @@ -675,12 +675,12 @@ Start.fetchPlnkr = function fetchPlnkr(options) { Start.initCordovaFromGui = function initCordovaFromGui(options, appSetup) { var q = Q.defer(); - logging.logger.debug('Initializing Cordova for Gui'); + log.debug('Initializing Cordova for Gui'); try { if (options.isCordovaProject) { Hooks.setHooksPermission(options.targetPath); - logging.logger.info('Update Config.xml'.green.bold); + log.info('Update Config.xml'); appSetup.bower = appSetup.bower ? appSetup.bower : []; var promises = []; @@ -699,7 +699,7 @@ Start.initCordovaFromGui = function initCordovaFromGui(options, appSetup) { promises.push(Cordova.addPlatform(options.targetPath, 'ios', true)); } - logging.logger.info('Initializing cordova project'.green.bold); + log.info('Initializing cordova project'); Q.all(promises) .then(function() { @@ -715,8 +715,8 @@ Start.initCordovaFromGui = function initCordovaFromGui(options, appSetup) { q.resolve(); } } catch (ex) { - logging.logger.debug('Exception caught in initCordova: %s', ex, {}); - logging.logger.debug('Exception details: %s', ex.stack, {}); + log.debug('Exception caught in initCordova: %s', ex, {}); + log.debug('Exception details: %s', ex.stack, {}); q.reject(ex); } @@ -742,7 +742,7 @@ Start.initCordovaNoCli = function initCordova(options, appSetup) { promises.push(Cordova.addPlatform(options.targetPath, 'ios', true)); } - logging.logger.info('Initializing cordova project without CLI'.green.bold); + log.info('Initializing cordova project without CLI'); return Q.all(promises); } catch (ex) { @@ -760,7 +760,7 @@ Start.initCordova = function(options, appSetup) { Hooks.setHooksPermission(options.targetPath); - logging.logger.info('\nAdding initial native plugins'.green.bold); + log.info('\nAdding initial native plugins'); appSetup.bower = appSetup.bower ? appSetup.bower : []; @@ -825,8 +825,8 @@ Start.initCordova = function(options, appSetup) { // Start.updateConfigXml(options.targetPath, options.packageName, options.appName, options.ios, options.android); } catch (ex) { - logging.logger.debug('Exception caught in initCordova: %s', ex, {}); - logging.logger.debug('Exception details: %s', ex.stack, {}); + log.debug('Exception caught in initCordova: %s', ex, {}); + log.debug('Exception details: %s', ex.stack, {}); q.reject(ex); } @@ -870,7 +870,7 @@ Start.updateConfigXml = function(targetPath, packageName, appName, ios, android) } catch(e) { // return self.ionic.fail('Error updating config.xml file: ' + e); - logging.logger.error('Error updating config.xml file: %s', e, {}) + log.error('Error updating config.xml file: %s', e, {}) console.error(e.stack); } @@ -901,15 +901,15 @@ Start.updateLibFiles = function(libPath) { } var libCssSymlinkPath = path.join(libSymlinkPath, 'css'); - logging.logger.info('Create www/lib/ionic/css symlink to ' + libCssSymlinkPath); + log.info('Create www/lib/ionic/css symlink to ' + libCssSymlinkPath); fs.symlinkSync(libCssSymlinkPath, wwwIonicCssPath); var libJsSymlinkPath = path.join(libSymlinkPath, 'js'); - logging.logger.info('Create www/lib/ionic/js symlink to ' + libJsSymlinkPath); + log.info('Create www/lib/ionic/js symlink to ' + libJsSymlinkPath); fs.symlinkSync(libJsSymlinkPath, wwwIonicJsPath); var libFontsSymlinkPath = path.join(libSymlinkPath, 'fonts'); - logging.logger.info('Create www/lib/ionic/fonts symlink to ' + libFontsSymlinkPath); + log.info('Create www/lib/ionic/fonts symlink to ' + libFontsSymlinkPath); fs.symlinkSync(libFontsSymlinkPath, wwwIonicFontsPath); libPath = 'lib/ionic'; @@ -990,7 +990,7 @@ Start.updateLibFiles = function(libPath) { } try { - logging.logger.info('Replacing Ionic lib references with ' + libPath); + log.info('Replacing Ionic lib references with ' + libPath); var indexPath = path.join(this.targetPath, 'www', 'index.html'); var html = fs.readFileSync(indexPath, 'utf8'); @@ -1018,14 +1018,14 @@ Start.promptLogin = function() { // Check if we already asked var didPrompt = ionicConfig.get('accountPrompt'); if(didPrompt == 'y') { - logging.logger.info('\nNew!'.bold + ' Add push notifications, update your app remotely, and package iOS and Android apps with the Ionic Platform!\n'.bold + IONIC_DASH + '/signup'); + log.info('\nNew!'.bold + ' Add push notifications, update your app remotely, and package iOS and Android apps with the Ionic Platform!\n'.bold + IONIC_DASH + '/signup'); return; } ionicConfig.set('accountPrompt', 'y'); ionicConfig.save(); } - logging.logger.info('\nCreate an Ionic Platform account to add features like User Authentication, Push Notifications, Live Updating, iOS builds, and more?'); + log.info('\nCreate an Ionic Platform account to add features like User Authentication, Push Notifications, Live Updating, iOS builds, and more?'); var promptProperties = { shouldCreate: { @@ -1042,7 +1042,7 @@ Start.promptLogin = function() { prompt.get({properties: promptProperties}, function (err, promptResult) { if(err) { q.reject(err); - return logging.logger.error(err); + return log.error(err); } var areYouSure = promptResult.shouldCreate.toLowerCase().trim(); @@ -1068,7 +1068,7 @@ Start.finalize = function(options) { packageData.description = options.appName + ': An Ionic project'; fs.writeFileSync(packageFilePath, JSON.stringify(packageData, null, 2), 'utf8'); } catch(e) { - logging.logger.error('There was an error finalizing the package.json file. %s', e, {}); + log.error('There was an error finalizing the package.json file. %s', e, {}); } try { @@ -1089,9 +1089,9 @@ Start.finalize = function(options) { } project.save(options.targetPath); - logging.logger.debug('Saved project file'); + log.debug('Saved project file'); } catch(e) { - logging.logger.error('Error saving project file'); + log.error('Error saving project file'); } try { @@ -1127,56 +1127,55 @@ Start.finalize = function(options) { }; Start.printQuickHelp = function(options) { - logging.logger.info('\n♬ ♫ ♬ ♫ Your Ionic app is ready to go! ♬ ♫ ♬ ♫'.bold) - logging.logger.info('\nMake sure to cd into your new app directory:'.bold); - logging.logger.info(' cd ' + options.appName); - logging.logger.info('\nTo run your app in the browser (great for initial development):'.bold); - logging.logger.info(' ionic serve'); - logging.logger.info('\nTo run on iOS:'.bold); - logging.logger.info(' ionic run ios'); - logging.logger.info('\nTo run on Android:'.bold); - logging.logger.info(' ionic run android'); - logging.logger.info('\nTo test your app on a device easily, try Ionic View:'.bold); - logging.logger.info(' http://view.ionic.io'); + 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); + log.info('\nTo run your app in the browser (great for initial development):'.bold); + log.info(' ionic serve'); + log.info('\nTo run on iOS:'.bold); + log.info(' ionic run ios'); + log.info('\nTo run on Android:'.bold); + 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'); /* - logging.logger.info('\n * cd into your project:', ('$ cd ' + options.appDirectory).bold); + log.info('\n * cd into your project:', ('$ cd ' + options.appDirectory).bold); if(!options.hasSass) { - logging.logger.info('\n * Setup this project to use Sass:', 'ionic setup sass'.bold); + log.info('\n * Setup this project to use Sass:', 'ionic setup sass'.bold); } - logging.logger.info('\n * Develop in the browser with live reload:', 'ionic serve'.bold); + log.info('\n * Develop in the browser with live reload:', 'ionic serve'.bold); if(options.isCordovaProject) { - logging.logger.info('\n * Add a platform (ios or Android):', 'ionic platform add ios [android]'.bold); - logging.logger.info(' Note: iOS development requires OS X currently'.small); - logging.logger.info(' See the Android Platform Guide for full Android installation instructions:'.small); - logging.logger.info(' https://cordova.apache.org/docs/en/edge/guide_platforms_android_index.md.html'.small); - logging.logger.info('\n * Build your app:', 'ionic build '.bold); - logging.logger.info('\n * Simulate your app:', 'ionic emulate '.bold); - logging.logger.info('\n * Run your app on a device:', 'ionic run '.bold); - logging.logger.info('\n * Package an app using Ionic package service:', 'ionic package '.bold); + log.info('\n * Add a platform (ios or Android):', 'ionic platform add ios [android]'.bold); + log.info(' Note: iOS development requires OS X currently'.small); + log.info(' See the Android Platform Guide for full Android installation instructions:'.small); + log.info(' https://cordova.apache.org/docs/en/edge/guide_platforms_android_index.md.html'.small); + log.info('\n * Build your app:', 'ionic build '.bold); + log.info('\n * Simulate your app:', 'ionic emulate '.bold); + log.info('\n * Run your app on a device:', 'ionic run '.bold); + log.info('\n * Package an app using Ionic package service:', 'ionic package '.bold); } - logging.logger.info('\nFor more help use', 'ionic --help'.bold, 'or', 'ionic docs'.bold); - logging.logger.info('\nVisit the Ionic docs:', 'http://ionicframework.com/docs\n'.bold); + log.info('\nFor more help use', 'ionic --help'.bold, 'or', 'ionic docs'.bold); + log.info('\nVisit the Ionic docs:', 'http://ionicframework.com/docs\n'.bold); */ }; Start.promptForOverwrite = function promptForOverwrite(targetPath) { var q = Q.defer(); - - logging.logger.info('The directory'.error.bold, targetPath, 'already exists.'.error.bold); - logging.logger.info('Would you like to overwrite the directory with this new project?'); - + log.warn('The directory', targetPath.cyan, 'already exists.'); + log.info('Would you like to overwrite the directory with this new project?'); var promptProperties = { areYouSure: { name: 'areYouSure', - description: '(yes/no):'.yellow.bold, + description: '(yes/no):', required: true } }; + prompt.colors = false; prompt.override = argv; prompt.message = ''; prompt.delimiter = ''; @@ -1185,7 +1184,7 @@ Start.promptForOverwrite = function promptForOverwrite(targetPath) { prompt.get({properties: promptProperties}, function (err, promptResult) { if(err && err.message !== 'canceled') { q.reject(err); - return logging.logger.error(err); + return log.error(err); } else if (err && err.message == 'canceled') { return q.resolve(false); } diff --git a/lib/state.js b/lib/state.js index 3921c0a..d335441 100644 --- a/lib/state.js +++ b/lib/state.js @@ -4,7 +4,7 @@ var fs = require('fs'), shelljs = require('shelljs'), Utils = require('./utils'), _ = require('underscore'), - logging = require('./logging'); + log = require('./logging').logger; var State = module.exports; @@ -28,8 +28,8 @@ State.getPackageJson = function getPackageJson(appDirectory) { packageJson.cordovaPlatforms = []; } } catch (ex) { - logging.logger.error('There was an error opening your package.json file.'); - logging.logger.error(ex); + log.error('There was an error opening your package.json file.'); + log.error(ex); Utils.fail(ex); } @@ -64,18 +64,18 @@ State.addOrUpdatePluginToPackageJson = function addOrUpdatePluginToPackageJson(p }; State.saveState = function saveState(appDirectory) { - logging.logger.info('Saving your Ionic app state of platforms and plugins'.blue.bold); + log.info('Saving your Ionic app state of platforms and plugins'); var packageJson = State.getPackageJson(appDirectory); try { State.saveExistingPlatforms(appDirectory, packageJson); - logging.logger.info('Saved platform'.green); + log.info('Saved platform'); State.saveExistingPlugins(appDirectory, packageJson); - logging.logger.info('Saved plugins'.green); + log.info('Saved plugins'); State.savePackageJson(appDirectory, packageJson); - logging.logger.info('Saved package.json'.green); + log.info('Saved package.json'); } catch (ex) { - logging.logger.error('There was an error saving your current Ionic setup'.red); - logging.logger.error(ex); + log.error('There was an error saving your current Ionic setup'); + log.error(ex); } }; @@ -109,7 +109,7 @@ State.saveExistingPlatforms = function saveExistingPlatforms(appDirectory, packa return; } - // logging.logger.info('h') + // log.info('h') platforms.forEach(function(platform) { // Ignore .git directory if it exists. if (platform.indexOf('.git') != -1) { @@ -146,7 +146,7 @@ State.saveExistingPlatforms = function saveExistingPlatforms(appDirectory, packa } } catch (ex) { - logging.logger.info('There was an error trying to save your existing state', ex); + log.info('There was an error trying to save your existing state', ex); } }); }; @@ -179,7 +179,7 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs } catch (ex) { } if (fetchJson) { - // logging.logger.info('fetchJson', fetchJson) + // log.info('fetchJson', fetchJson) //This will break with what we had before for (pluginId in fetchJson) { // cordovaPlugins.push(); @@ -189,16 +189,16 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs pluginPath = path.join(appDirectory, 'plugins', pluginId); pluginPathStats = fs.statSync(pluginPath); } catch (ex) { - logging.logger.info(('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping').yellow); + log.info('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping'); continue; } if (!pluginPathStats.isDirectory()) { - logging.logger.info(('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping').yellow); + log.info('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping'); continue; } - // logging.logger.info('plugin.source.type', plugin.source.type); + // log.info('plugin.source.type', plugin.source.type); if (plugin.source.type === 'registry') { locator = pluginId; @@ -224,20 +224,20 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs hasVariables = true; variableList = preferences.map(function(preference) { return preference.$.name; - // logging.logger.info('looking at preference: ', preference) + // log.info('looking at preference: ', preference) }); } - + keyValueList = {}; if (hasVariables) { - // logging.logger.info('we have avariables to look at:', variableList) + // 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); - - - // why we are searching for plugin params from the config xml? + + + // why we are searching for plugin params from the config xml? //featureParams = State.getPluginParameters(configXmlData, pluginName); // features.forEach(function(potFeature) { // if(potFeature.$.name == pluginName) { @@ -245,7 +245,7 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs // } // }) - // logging.logger.info('feature found:', feature); + // log.info('feature found:', feature); // var featureParams = feature.param; variableList.forEach(function(variable) { @@ -261,7 +261,7 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs } }); - // logging.logger.info('We have the plugin parameters with values:', keyValueList) + // log.info('We have the plugin parameters with values:', keyValueList) var pluginObj = {id: pluginId, locator: locator, variables: keyValueList}; cordovaPlugins.push(pluginObj); @@ -276,8 +276,8 @@ State.saveExistingPlugins = function saveExistingPlugins(appDirectory, packageJs packageJson.cordovaPlugins = cordovaPlugins; } else { - logging.logger.info('There was no fetch.json file available to restore plugin information from.'.red.bold); - logging.logger.info('Restoring plugins from scanning the plugins folder is still being worked on.'.red.bold); + 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 @@ -307,7 +307,7 @@ State.getPlatformVersion = function getPlatformVersion(path) { return ''; } var version = result.output - // logging.logger.info('Version for path:', path, version) + // log.info('Version for path:', path, version) return version.replace(/\n/g, ''); }; @@ -337,12 +337,12 @@ State.addOrUpdatePlatformToPackageJson = function addOrUpdatePlatformToPackageJs if (!existingPlatform) { packageJson.cordovaPlatforms.push(platformInfo); } else if (platformInfo) { - logging.logger.debug('A platform already exists - now updating the entry:', existingPlatform, platformInfo); + log.debug('A platform already exists - now updating the entry:', existingPlatform, platformInfo); packageJson.cordovaPlatforms[existingPlatformIndex] = platformInfo; } - // logging.logger.info('platformExists:', platformExists) + // log.info('platformExists:', platformExists) // if (!platformExists && requiresLocator) { // packageJson.cordovaPlatforms.push({platform: platform, locator: locator}); // // packageJson.cordovaPlatforms.push({platform: platform, version: version, locator: locator}); @@ -355,13 +355,13 @@ State.addOrUpdatePlatformToPackageJson = function addOrUpdatePlatformToPackageJs }; State.savePlatform = function savePlatform(appDirectory, locator) { - logging.logger.debug('State.savePlatform', appDirectory, locator); + log.debug('State.savePlatform', appDirectory, locator); // Locator may be: // Name: ios, android // Name with version: ios@3.8.0, android@4.0.0 // Local path: ./engine/cordova-android-c0.6.1 // Http url: https://github.com/apache/cordova-android.git - // logging.logger.info('platform args:', platformArgs); + // log.info('platform args:', platformArgs); // var locator = platformArgs._[2]; var platform = 'ios', version; @@ -398,28 +398,28 @@ State.savePlatform = function savePlatform(appDirectory, locator) { }; State.savePackageJson = function savePackageJson(appDirectory, packageJsonData) { - logging.logger.debug('State.savePackageJson', appDirectory, packageJsonData); + log.debug('State.savePackageJson', appDirectory, packageJsonData); try { var packageJsonPath = path.join(appDirectory, 'package.json'); fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonData, null, 2) + "\n"); } catch (e) { - logging.logger.error(('Error saving ' + packageJsonPath + ': %s').bold, e, {}); + log.error(('Error saving ' + packageJsonPath + ': %s').bold, e, {}); } }; State.restoreState = function restoreState(appDirectory, options) { - logging.logger.debug('State.restoreState', appDirectory, options); + log.debug('State.restoreState', appDirectory, options); if (!options || !appDirectory) { throw 'You must pass an application directory and options to restore state.'; } if (!options.platforms && !options.plugins) { - logging.logger.error('You must specify either platforms or plugins to restore the state of your Ionic application.'); + log.error('You must specify either platforms or plugins to restore the state of your Ionic application.'); return; } - logging.logger.info('Attempting to restore your Ionic application from package.json\n'.yellow.bold); + log.info('Attempting to restore your Ionic application from package.json\n'); // var packageJsonPath = path.join(appDirectory, 'package.json'); // var packageJson = require(packageJsonPath); @@ -427,11 +427,11 @@ State.restoreState = function restoreState(appDirectory, options) { var restorePromise; if (options.platforms) { - logging.logger.info('Restoring Platforms\n'.blue.bold) + log.info('Restoring Platforms\n') restorePromise = State.restorePlatforms(appDirectory, packageJson) .then(function() { - logging.logger.info('\nRestore platforms is complete\n'.green.bold); + log.info('\nRestore platforms is complete\n'); }); } else { restorePromise = Q(); @@ -441,33 +441,33 @@ State.restoreState = function restoreState(appDirectory, options) { return restorePromise .then(function() { if (options.plugins) { - logging.logger.info('\rRestoring Plugins\n'.blue.bold) + log.info('\rRestoring Plugins\n') return State.restorePlugins(appDirectory, packageJson) .then(function(){ - logging.logger.info('Restore plugins is complete\n'.green.bold); + log.info('Restore plugins is complete\n'); }); } else { return Q(); } }) .then(function() { - logging.logger.info('Ionic state restore completed\n'.blue.bold) + log.info('Ionic state restore completed\n') }) .catch(function(ex) { - logging.logger.error('Ionic state restore failed\n'.red.bold) - logging.logger.error(ex); + log.error('Ionic state restore failed\n') + log.error(ex); }); }; State.restorePlugins = function restorePlugins(appDirectory, packageJson) { - logging.logger.debug('State.restorePlugins', appDirectory, packageJson); + log.debug('State.restorePlugins', appDirectory, packageJson); var q = Q.defer(); State.processPlugin(appDirectory, 0, packageJson, q); return q.promise; }; State.restorePlatforms = function restorePlatforms(appDirectory, packageJson) { - logging.logger.debug('State.restorePlatforms', appDirectory, packageJson); + log.debug('State.restorePlatforms', appDirectory, packageJson); var q = Q.defer(); State.processPlatform(appDirectory, 0, packageJson, q); @@ -482,7 +482,7 @@ State.processPlatform = function processPlatform(appDirectory, index, packageJso } try { - // logging.logger.info('processing platform', index, packageJson) + // log.info('processing platform', index, packageJson) var platform = packageJson.cordovaPlatforms[index]; var platformCommand; @@ -494,19 +494,19 @@ State.processPlatform = function processPlatform(appDirectory, index, packageJso platformCommand = 'cordova platform add ' + platform.locator; } // var platformCommand = State.createAddRemoveStatement(platform); - logging.logger.info(platformCommand); + log.info(platformCommand); shelljs.exec(platformCommand, function() { State.processPlatform(appDirectory, index + 1, packageJson, promise); }); } catch (ex) { - logging.logger.error('An error happened processing the previous cordova plugins') - logging.logger.error(ex) + log.error('An error happened processing the previous cordova plugins') + log.error(ex) promise.reject(ex) } }; State.createAddRemoveStatement = function createAddRemoveStatement(plugin) { - // logging.logger.info('Creating add/remove statement', plugin) + // log.info('Creating add/remove statement', plugin) try { var pluginCmd = 'cordova plugin add '; if (typeof plugin === 'string') { @@ -520,10 +520,10 @@ State.createAddRemoveStatement = function createAddRemoveStatement(plugin) { } } } catch (ex) { - logging.logger.error('Failed to create add plugin statement: %s', ex, {}) + log.error('Failed to create add plugin statement: %s', ex, {}) } - // logging.logger.info('plugin cmd', pluginCmd) + // log.info('plugin cmd', pluginCmd) return pluginCmd; }; @@ -534,10 +534,10 @@ State.processPlugin = function processPlugin(appDirectory, index, packageJson, p return } try { - // logging.logger.info('processing plugin', index, packageJson) + // log.info('processing plugin', index, packageJson) var plugin = packageJson.cordovaPlugins[index]; var pluginCommand = State.createAddRemoveStatement(plugin); - logging.logger.info(pluginCommand); + log.info(pluginCommand); shelljs.exec(pluginCommand, {async: true}, function(code, output) { if (code != 0) { throw 'Error executing "' + pluginCommand + '":\n' + output; @@ -545,14 +545,14 @@ State.processPlugin = function processPlugin(appDirectory, index, packageJson, p State.processPlugin(appDirectory, index + 1, packageJson, promise) }); } catch (ex) { - logging.logger.error('An error happened processing the previous cordova plugins') - logging.logger.error(ex) + log.error('An error happened processing the previous cordova plugins') + log.error(ex) promise.reject(ex) } }; State.removePlatform = function removePlatform(appDirectory, platform) { - // logging.logger.info('Args:', platformArgs); + // log.info('Args:', platformArgs); //Expecting - ionic platform remove [ios|android] //TODO - check if they pass multiple platforms @@ -601,14 +601,14 @@ State.getPluginPreferences = function getPluginPreferences(fetchJson, pluginName if(!fetchJson || !fetchJson[pluginName]){ throw 'Invalid fetch.json Data'; } - + var preferences = fetchJson[pluginName].variables; if(Object.keys(preferences).length !== 0){ return preferences; } - + return null; - + }; // @@ -622,7 +622,7 @@ State.getPluginPreferences = function getPluginPreferences(fetchJson, pluginName '$0': '/usr/local/bin/ionic' } */ State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { - logging.logger.debug('State.savePlugin - appDirectory:', appDirectory, 'pluginId', pluginId, 'variables', variables); + log.debug('State.savePlugin - appDirectory:', appDirectory, 'pluginId', pluginId, 'variables', variables); //Expects - either simple ID for plugin registry //or a local path, with or without variables //ionic plugin add org.apache.cordova.splashscreen @@ -650,12 +650,12 @@ State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { pluginInfo.variables[splits[0]] = splits[1]; } } - + // pluginId could be org.ionic.keyboard or ./engine/facebook-plugin if (pluginId.indexOf('/') === -1) { //its just an id - + //Check and save for variables - if(!variables){ + if(!variables){ State.addOrUpdatePluginToPackageJson(packageJson, pluginId); } else{ @@ -663,7 +663,7 @@ State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { pluginInfo.id = pluginId = State.getPluginFromFetchJsonByLocator(appDirectory, pluginInfo.locator); State.addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); } - + return State.savePackageJson(appDirectory, packageJson); } @@ -680,14 +680,14 @@ State.savePlugin = function savePlugin(appDirectory, pluginId, variables) { State.addOrUpdatePluginToPackageJson(packageJson, pluginId, pluginInfo); - logging.logger.info('Save plugin to package.json completed'); + 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); }; State.removePlugin = function removePlugin(appDirectory, pluginId) { - logging.logger.debug('State.removePlugin - ', appDirectory, pluginId); + log.debug('State.removePlugin - ', appDirectory, pluginId); var packageJson = State.getPackageJson(appDirectory); for (var i = 0, j = packageJson.cordovaPlugins.length; i < j; i++) { if (typeof packageJson.cordovaPlugins[i] == 'string' && packageJson.cordovaPlugins[i] == pluginId) { @@ -709,7 +709,7 @@ State.saveXmlFile = function saveXmlFile(xmlData, xmlPath) { var configString = xmlBuilder.buildObject(xmlData); fs.writeFileSync(xmlPath, configString); } catch (ex) { - logging.logger.error('Could not save your xml file to path:', xmlPath); + log.error('Could not save your xml file to path:', xmlPath); } }; @@ -768,7 +768,7 @@ State.checkAndSaveConfigXml = function checkAndSaveConfigXml(appDirectory, plugi var pluginXmlData = State.getXmlData(pluginXmlPath); var configXmlData = State.getXmlData(configXmlPath); - // logging.logger.info('xml data:', pluginXmlData); + // log.info('xml data:', pluginXmlData); var pluginName = pluginXmlData.plugin.name[0], feature, @@ -800,15 +800,15 @@ State.resetState = function resetState(appDirectory, options) { var platformPath = path.join(appDirectory, 'platforms'); var pluginPath = path.join(appDirectory, 'plugins'); shelljs.rm('-rf', [platformPath, pluginPath]); - logging.logger.info('Removed platforms and plugins'.blue.bold); + log.info('Removed platforms and plugins'); State.restoreState(appDirectory, options) .then(function() { - logging.logger.info('Ionic reset state complete'.green.bold); + log.info('Ionic reset state complete'); }) }; State.clearState = function clearState(appDirectory) { - logging.logger.info('Clearing out your Ionic app of platforms, plugins, and package.json entries'.blue.bold); + 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]); @@ -816,7 +816,7 @@ State.clearState = function clearState(appDirectory) { var packageJson = State.getPackageJson(appDirectory); packageJson.cordovaPlatforms = packageJson.cordovaPlugins = []; State.savePackageJson(appDirectory, packageJson); - logging.logger.info('Ionic app state cleared'.green.bold); + log.info('Ionic app state cleared'); }; State.getPluginsFromFetchJson = function getPluginsFromFetchJson(appDirectory) { @@ -846,12 +846,12 @@ State.getPluginsFromFetchJson = function getPluginsFromFetchJson(appDirectory) { pluginPath = path.join(appDirectory, 'plugins', pluginId); pluginPathStats = fs.statSync(pluginPath); } catch (ex) { - logging.logger.info(('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping').yellow); + log.info('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping'); continue; } if (pluginPathStats && !pluginPathStats.isDirectory()) { - logging.logger.info(('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping').yellow); + log.info('Plugin ' + pluginId + ' does not exist in the plugins directory. Skipping'); continue; } diff --git a/lib/templates.js b/lib/templates.js index 6443e6a..c87f700 100644 --- a/lib/templates.js +++ b/lib/templates.js @@ -5,7 +5,7 @@ var colors = require('colors'), Task = require('./task').Task, IonicStats = require('./stats').IonicStats, request = require('request'), - logging = require('./logging'); + log = require('./logging').logger; // starterTemplates = require('./starter-templates') var IonicTask = function() {}; @@ -15,12 +15,12 @@ IonicTask.prototype = new Task(); IonicTask.prototype.fetchStarterTemplates = function() { var self = this; - // logging.logger.info('About to fetch template'); + // log.info('About to fetch template'); var downloadUrl = 'http://code.ionicframework.com/content/starter-templates.json'; var starterTemplateJsonPath = path.resolve(__dirname, 'starter-templates.json'); - // logging.logger.info('\nDownloading Starter Templates'.bold, downloadUrl, starterTemplateJsonPath); - logging.logger.info('\nDownloading Starter Templates'.bold, '-', downloadUrl); + // log.info('\nDownloading Starter Templates'.bold, downloadUrl, starterTemplateJsonPath); + log.info('\nDownloading Starter Templates'.bold, '-', downloadUrl); var q = Q.defer(); @@ -31,14 +31,14 @@ IonicTask.prototype.fetchStarterTemplates = function() { try { templatesJson = JSON.parse(html); }catch(ex) { - logging.logger.error('Error: ', ex) + log.error('Error: ', ex) q.reject('Error occured in download templates:', ex) self.ionic.fail(ex); return; } q.resolve(templatesJson); } else { - logging.logger.error('Unable to fetch the starter templates. Please check your internet connection'.red); + log.error('Unable to fetch the starter templates. Please check your internet connection'); q.reject(res); } }); @@ -47,7 +47,7 @@ IonicTask.prototype.fetchStarterTemplates = function() { IonicTask.prototype.list = function list(templates) { //Should have array of [{ name: 'name', description: 'desc' }] - logging.logger.info('\n') + log.info('\n') _.each(templates, function(template) { var rightColumn = 20, dots = ''; var shortName = template.name.replace('ionic-starter-', ''); @@ -55,7 +55,7 @@ IonicTask.prototype.list = function list(templates) { dots += '.'; } var outStr = [] - logging.logger.info(shortName.green, dots, template.description); + log.info(shortName, dots, template.description); }) } @@ -68,7 +68,7 @@ IonicTask.prototype.run = function(ionic) { }) var templates = _.sortBy(starterTemplates.items, function(template){ return template.name; }); - logging.logger.info('Ionic Starter templates'.green); + log.info('Ionic Starter templates'); this.list(templates); } diff --git a/lib/upload.js b/lib/upload.js index ffa4bfc..6fc6931 100644 --- a/lib/upload.js +++ b/lib/upload.js @@ -10,17 +10,17 @@ var fs = require('fs'), ioLib = require('./io-config'), request = require('request'), shelljs = require('shelljs'), - logging = require('./logging'); + log = require('./logging').logger; var TEMP_FILENAME = 'www.zip'; var Upload = module.exports; Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { - logging.logger.info('Uploading app....'.green.bold); - logging.logger.debug('Upload doUpload - ', appDirectory, jar); + log.info('Uploading app....'); + log.debug('Upload doUpload - ', appDirectory, jar); if (deploy && deploy === true) { - logging.logger.info('Deploy channel not provided; defaulting to dev.'); + log.info('Deploy channel not provided; defaulting to dev.'); deploy = 'dev'; // this is the default channel_tag } @@ -45,7 +45,7 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { .then(function(key){ // Do nothing }, function(error) { - logging.logger.error('Error saving app ID:', error); + log.error('Error saving app ID:', error); }); // Set project vars @@ -66,7 +66,7 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { ioLib.writeIoConfig('api_key', status.api_key, true).then(function(apiKey){ ioLib.warnMissingData(); }, function(error) { - logging.logger.error('Error saving API key:', error); + log.error('Error saving API key:', error); }); } } @@ -79,23 +79,23 @@ Upload.doUpload = function doUpload(appDirectory, jar, note, deploy) { return upload; }) .catch(function(ex) { - logging.logger.error('An error occurred uploading the build: %s', ex, {}); + log.error('An error occurred uploading the build: %s', ex, {}); throw ex; }); } catch(ex) { - logging.logger.error('Upload errors occurred - %s', ex, {}); + log.error('Upload errors occurred - %s', ex, {}); } }; Upload.uploadToS3 = function uploadToS3(appDirectory, keyInfo) { var q = Q.defer(); - logging.logger.debug('Uploading zip file to S3'); + log.debug('Uploading zip file to S3'); var proxy = process.env.PROXY || process.env.HTTP_PROXY || null; var zipFile = path.join(appDirectory, TEMP_FILENAME); // Now we upload with the signed URL the dash returned - logging.logger.debug(zipFile); + log.debug(zipFile); request({ method: 'PUT', @@ -126,7 +126,7 @@ Upload.uploadToS3 = function uploadToS3(appDirectory, keyInfo) { Upload.signalDashUpload = function signalDashUpload(project, jar) { var q = Q.defer(); - logging.logger.debug('Signaling to ionic.io completion of the upload'); + log.debug('Signaling to ionic.io completion of the upload'); var proxy = process.env.PROXY || process.env.HTTP_PROXY || null; @@ -145,8 +145,8 @@ Upload.signalDashUpload = function signalDashUpload(project, jar) { if (error || response.statusCode != 200) { q.reject("Upload Failed:", error || "Server Error: " + response.statusCode); } else { - logging.logger.info(('Successfully uploaded (' + project.get('app_id') + ')\n').bold); - logging.logger.info(('Share your beautiful app with someone:\n\n$ ionic share EMAIL\n').bold); + log.info(('Successfully uploaded (' + project.get('app_id') + ')\n').bold); + log.info(('Share your beautiful app with someone:\n\n$ ionic share EMAIL\n').bold); q.resolve(JSON.parse(body)); } }); @@ -157,7 +157,7 @@ Upload.signalDashUpload = function signalDashUpload(project, jar) { Upload.verify_tag = function verify_tag(project, jar, deploy, version) { var q = Q.defer(); - logging.logger.debug('Checking if we need to deploy the upload'); + log.debug('Checking if we need to deploy the upload'); if (deploy && version) { @@ -177,7 +177,7 @@ Upload.verify_tag = function verify_tag(project, jar, deploy, version) { if (error || response.statusCode != 200) { q.reject("Deploy failed to verify the channel tag"); } else { - logging.logger.debug('Verified channel tag...'); + log.debug('Verified channel tag...'); q.resolve({ 'version': version, 'channel': JSON.parse(body)}); } }); @@ -191,10 +191,10 @@ Upload.verify_tag = function verify_tag(project, jar, deploy, version) { Upload.deploy = function deploy(project, jar, deploy) { var q = Q.defer(); - logging.logger.debug('Check for a deploy...'); + log.debug('Check for a deploy...'); if (deploy) { - logging.logger.info('Deploying to channel: ' + deploy.channel.label.green.bold); + log.info('Deploying to channel: ' + deploy.channel.label.green.bold); var proxy = process.env.PROXY || process.env.HTTP_PROXY || null; @@ -217,7 +217,7 @@ Upload.deploy = function deploy(project, jar, deploy) { if (error || response.statusCode != 200) { q.reject("Deploy failed: " + (error || response.statusCode)); } else { - logging.logger.info('Deploy Successful!'.green.bold) + log.info('Deploy Successful!'.green.bold) q.resolve(true); } }); @@ -233,7 +233,7 @@ Upload.getDirectUploadKey = function getDirectUploadKey(project, jar, note) { note = note ? note : ''; - logging.logger.debug('Getting Upload information from ', settings.IONIC_DASH); + log.debug('Getting Upload information from ', settings.IONIC_DASH); var csrftoken = ''; @@ -259,7 +259,7 @@ Upload.getDirectUploadKey = function getDirectUploadKey(project, jar, note) { }) }, function(err, response) { if (err) { - logging.logger.info('There was an error trying to upload your app.'.red.bold); + log.error('There was an error trying to upload your app.'); var errorMessage; if(err.code === 'ENOTFOUND' || err.code === 'EPIPE') { errorMessage = 'The address you are trying to reach could not be found. \n' + @@ -323,7 +323,7 @@ Upload.zipContents = function zipContents(appDirectory, documentRoot) { Upload.addCacheBusters = function addCacheBusters(indexPath) { var q = Q.defer(); - logging.logger.debug('When your webview is acting crazy who do you call? Cachebusters!'); + log.debug('When your webview is acting crazy who do you call? Cachebusters!'); var randomString = Math.floor(Math.random() * 100000); var indexHtml = fs.readFileSync(indexPath, 'utf8'); @@ -365,7 +365,7 @@ Upload.addCacheBusters = function addCacheBusters(indexPath) { Upload.removeCacheBusters = function removeCacheBusters(indexPath) { var q = Q.defer(); - logging.logger.debug('Removing cachebusting ', indexPath); + log.debug('Removing cachebusting ', indexPath); var indexHtml = fs.readFileSync(indexPath, 'utf8'); var $ = cheerio.load(indexHtml); diff --git a/lib/utils.js b/lib/utils.js index 6db0dc7..be56087 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -7,7 +7,7 @@ var fs = require('fs'), path = require('path'), Q = require('q'), shelljs = require('shelljs'), - logging = require('./logging'); + log = require('./logging').logger; var Utils = module.exports; @@ -53,7 +53,7 @@ Utils.createArchive = function(appDirectory, documentRoot) { var q = Q.defer(); var zipPath = path.join(appDirectory, documentRoot); - logging.logger.debug('Now zipping contents of ' + zipPath); + log.debug('Now zipping contents of ' + zipPath); if (!fs.existsSync(zipPath)) { q.reject(documentRoot + ' directory cannot be found. Make sure the working directory is at the top level of an Ionic project.', 'upload'); @@ -91,7 +91,7 @@ Utils.fetchArchive = function fetchArchive(targetPath, archiveUrl, isGui) { // The folder name the project will be downloaded and extracted to var message = ['Downloading:'.bold, archiveUrl].join(' '); - logging.logger.info(message); + log.info(message); var tmpFolder = os.tmpdir(); var tempZipFilePath = path.join(tmpFolder, 'ionic-starter-' + new Date().getTime() + '.zip'); @@ -100,7 +100,7 @@ Utils.fetchArchive = function fetchArchive(targetPath, archiveUrl, isGui) { var unzipRepo = function unzipRepo(fileName) { var readStream = fs.createReadStream(fileName); readStream.on('error', function(err) { - logging.logger.debug(('unzipRepo readStream: ' + err).error); + log.debug('unzipRepo readStream error: ' + err); q.reject(err); }); @@ -109,7 +109,7 @@ Utils.fetchArchive = function fetchArchive(targetPath, archiveUrl, isGui) { q.resolve(); }); writeStream.on('error', function(err) { - logging.logger.debug(('unzipRepo writeStream: ' + err).error); + log.debug('unzipRepo writeStream error: ' + err); q.reject(err); }); readStream.pipe(writeStream); @@ -142,7 +142,7 @@ Utils.fetchArchive = function fetchArchive(targetPath, archiveUrl, isGui) { fs.writeFileSync(tempZipFilePath, body); unzipRepo(tempZipFilePath); } catch(e) { - logging.logger.debug('fetchArchive request write: ', e); + log.debug('fetchArchive request write: ', e); q.reject(e); } }).on('response', function(res){ @@ -190,7 +190,7 @@ Utils.preprocessOptions = function preprocessOptions(options) { }; Utils.preprocessCliOptions = function preprocessCliOptions(argv) { - logging.logger.debug('Utils.preprocessCliOptions', argv); + log.debug('Utils.preprocessCliOptions', argv); try { var options = {}; @@ -225,7 +225,7 @@ Utils.preprocessCliOptions = function preprocessCliOptions(argv) { return options; } catch (ex) { - logging.logger.debug('An error occrured processing the CLI arguments', ex); + log.debug('An error occrured processing the CLI arguments', ex); Utils.fail('There was an error parsing out options from the Command Line'); } }; @@ -235,7 +235,7 @@ Utils.getProjectDirectory = function getProjectDirectory(options) { }; Utils.getContentSrc = function getContentSrc(appDirectory) { - logging.logger.debug('Utils.getContentSrc', appDirectory); + log.debug('Utils.getContentSrc', appDirectory); var contentSrc; try { var fs = require('fs'); @@ -266,7 +266,7 @@ Utils.getContentSrc = function getContentSrc(appDirectory) { }); } catch(e) { - logging.logger.debug('Utils.getContentSrc failed', e); + log.debug('Utils.getContentSrc failed', e); console.log(e.stack); return Utils.fail('Error loading ' + configXmlPath + ': ' + e); } @@ -283,21 +283,21 @@ Utils.mergeOptions = function mergeOptions(obj1, obj2) { Utils.fail = function fail(msg, taskHelp) { try { - logging.logger.debug('Utils.fail', msg, taskHelp); - logging.logger.debug('Utils.fail stack', msg.stack); + log.debug('Utils.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) { - logging.logger.debug('Utils.errorHandler is set, calling that now'); + log.debug('Utils.errorHandler is set, calling that now'); return Utils.errorHandler(msg, taskHelp); } - logging.logger.error('An error occurred in Ionic App Lib and no error handler was set.'); - logging.logger.error(msg); + log.error('An error occurred in Ionic App Lib and no error handler was set.'); + log.error(msg); process.exit(1); return ''; } catch (ex) { - logging.logger.debug('Utils.fail: ', ex); + log.debug('Utils.fail: ', ex); } } @@ -356,13 +356,13 @@ Utils.findIonicRoot = function findIonicRoot(dir) { Utils.cdIonicRoot = function cdIonicRoot(isV2) { var IonicProject = require('./project'); - logging.logger.debug('Looking up Ionic root, cwd:', process.cwd()); + log.debug('Looking up Ionic root, cwd:', process.cwd()); var rootDir = this.findIonicRoot(); if (!rootDir) { console.error('Couldn\'t find ' + IonicProject.PROJECT_FILE + ' file. Are you in an Ionic project?'); process.exit(1); } - logging.logger.debug('Ionic root directory: ', process.cwd()); + log.debug('Ionic root directory: ', process.cwd()); process.env.PWD = rootDir; process.chdir(rootDir); return rootDir;