From c5809460e59233e1f585a5a0cf1b550ea7c13a42 Mon Sep 17 00:00:00 2001 From: "Tara Z. Manicsic" Date: Tue, 16 Feb 2016 16:13:32 -0500 Subject: [PATCH] Lint `commands` directory files. issue #71 --- lib/commands/addOn.js | 254 ++++----- lib/commands/config.js | 30 +- lib/commands/env.js | 227 ++++---- lib/commands/help.js | 4 +- lib/commands/misc.js | 34 +- lib/commands/mongo.js | 324 +++++------ lib/commands/project.js | 1126 ++++++++++++++++++++------------------- lib/commands/servo.js | 86 +-- lib/commands/status.js | 28 +- lib/commands/user.js | 376 +++++++------ package.json | 1 - 11 files changed, 1297 insertions(+), 1193 deletions(-) diff --git a/lib/commands/addOn.js b/lib/commands/addOn.js index 0e85350..1f7c949 100644 --- a/lib/commands/addOn.js +++ b/lib/commands/addOn.js @@ -1,83 +1,91 @@ -var modulus = require('../modulus'), - addOnController = require('../controllers/addOn'), - projectController = require('../controllers/project'), - projectCommands = require('../commands/project'), - async = require('async'), - userConfig = require('../common/api').userConfig, - error = require('../common/error'), - util = require('util'); +const Async = require('async'); +const Util = require('util'); + +const Modulus = require('../modulus'); +const AddOnController = require('../controllers/addOn'); +const ProjectController = require('../controllers/project'); +const ProjectCommands = require('../commands/project'); +const UserConfig = require('../common/api').userConfig; +const Errors = require('../common/error'); var addOn = {}; +var print = Modulus.io.print; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- // Gets a project via project name param or project prompt -//----------------------------------------------------------------------------- -addOn.getProject = function(projectName, callback) { - projectController.find({ - userId : userConfig.data.userId +// ---------------------------------------------------------------------------- +addOn.getProject = function (projectName, callback) { + ProjectController.find({ + userId: UserConfig.data.userId }, - function(err, projects) { - if(err) { - err = error.handleApiError(err, 'GET_PROJECTS', callback); + function (err, projects) { + if (err) { + err = Errors.handleApiError(err, 'GET_PROJECTS', callback); - if(err.length > 0) { + if (err.length > 0) { return callback(err); } } - if(projects.length === 0) { + if (projects.length === 0) { return callback('You currently have no projects. One can be created using the create command.'); } - projectCommands.chooseProjectPrompt(projects, projectName, function(err, result) { - if(err) { - return callback(err); - } + ProjectCommands.chooseProjectPrompt( + projects, projectName, function (err, result) { + if (err) { + return callback(err); + } - if(!result) { - return callback('You must select a project.'); - } + if (!result) { + return callback('You must select a project.'); + } - callback(null, result); - }); + callback(null, result); + }); }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- // Prompts to choose an addon from a list -//----------------------------------------------------------------------------- -addOn.chooseAddOnPrompt = function(addons, callback) { - if(addons.length === 0) { - callback('This project has no provisioned add-ons.'); +// ---------------------------------------------------------------------------- +addOn.chooseAddOnPrompt = function (addons, callback) { + var i; + if (addons.length === 0) { + return callback('This project has no provisioned add-ons.'); } - modulus.io.print('Please choose an add-on:'.input); + print('Please choose an add-on:'.input); - for(var a = 0; a < addons.length; a++) { - modulus.io.print((' ' + (a + 1) + ') ' + addons[a].addon_name).input); + for (i = 0; i < addons.length; ++i) { + print((' ' + (i + 1) + ') ' + addons[i].addon_name).input); } - modulus.io.prompt.get([{ - name : 'addon', - description : 'Addon?', + Modulus.io.prompt.get([{ + name: 'addon', + description: 'Addon?', type: 'number', - warning : 'Add-On choice has to be between 1 and ' + addons.length, - minimum : 1, - maximum : addons.length - }], function(err, result) { - if(err) { - return error.handlePromptError(err, callback); + warning: 'Add-On choice has to be between 1 and ' + addons.length, + minimum: 1, + maximum: addons.length + }], function (err, result) { + if (err) { + return Errors.handlePromptError(err, callback); } - modulus.io.print(util.format('Selecting %s\n', addons[result.addon - 1].addon_name.data)); + print( + Util.format('Selecting %s\n', addons[result.addon - 1].addon_name.data) + ); + callback(null, addons[result.addon - 1]); }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- // Prompts to choose an add-on region from a list -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- addOn.chooseRegionPrompt = function (addon, callback) { + var i; if (!addon.regions || addon.regions.length === 0) { return callback(null, ''); } @@ -86,13 +94,13 @@ addOn.chooseRegionPrompt = function (addon, callback) { return callback(null, addon.regions[0]); } - modulus.io.print('Please choose a region:'.input); + print('Please choose a region:'.input); - for (var i = 0; i < addon.regions.length; i++) { - modulus.io.print((' ' + (i + 1) + ') ' + addon.regions[i]).input); + for (i = 0; i < addon.regions.length; ++i) { + print((' ' + (i + 1) + ') ' + addon.regions[i]).input); } - modulus.io.prompt.get([ + Modulus.io.prompt.get([ { name: 'region', description: 'Region?', @@ -102,79 +110,86 @@ addOn.chooseRegionPrompt = function (addon, callback) { maximum: addon.regions.length } ], function (err, result) { - if (err) { - return error.handlePromptError(err, callback); - } + if (err) { + return Errors.handlePromptError(err, callback); + } - modulus.io.print(util.format('Select %s\n', addon.regions[result.region - 1].data)); - callback(null, addon.regions[result.region - 1]); - }); + print(Util.format('Select %s\n', addon.regions[result.region - 1].data)); + callback(null, addon.regions[result.region - 1]); + }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- // Prints a list of Add-Ons -//----------------------------------------------------------------------------- -addOn.printList = function(projectName, addons) { - modulus.io.print('Add-Ons provisioned for ' + projectName.verbose); +// ---------------------------------------------------------------------------- +addOn.printList = function (projectName, addons) { + var addonConfig,configItem, i; + print('Add-Ons provisioned for ' + projectName.verbose); - if(addons instanceof Array === false || addons.length === 0) { - modulus.io.print('No Add-Ons provisioned.'); + if (addons instanceof Array === false || addons.length === 0) { + print('No Add-Ons provisioned.'); } else { - for(var a = 0; a < addons.length; a++) { - modulus.io.print('--------------------------------------'.grey); + for (i = 0; i < addons.length; ++i) { + print('--------------------------------------'.grey); // Capitalized name. - modulus.io.print(addons[a].addon_name.yellow); + print(addons[i].addon_name.yellow); // Id - modulus.io.print(('Id: ' + addons[a].addon_id).grey); + print(('Id: ' + addons[i].addon_id).grey); // Plan - modulus.io.print(('Plan: ' + addons[a].plan).grey); + print(('Plan: ' + addons[i].plan).grey); // Config - for(var k in addons[a].config) { - modulus.io.print((k + ' = ' + addons[a].config[k]).grey); + addonConfig = addons[i].config; + for (configItem in addonConfig) { + if ({}.hasOwnProperty.call(addonConfig, configItem)) { + print((configItem + ' = ' + addonConfig[configItem]).grey); + } } } } }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- // Gets the Add-Ons provided to a project. -//----------------------------------------------------------------------------- -addOn.getForProject = function(projectName, callback) { +// ---------------------------------------------------------------------------- +addOn.getForProject = function (projectName, callback) { var project = null; - async.waterfall([ - function(cb) { + Async.waterfall([ + function (cb) { addOn.getProject(projectName, cb); }, - function(pro, cb) { + function (pro, cb) { project = pro; - addOnController.getForProject(project.id, cb); + AddOnController.getForProject(project.id, cb); }, - function(addons, cb) { - //Newline - console.log(); + function (addons, cb) { + // Newline + print(); addOn.printList(project.name, addons); cb(null); } ], - function(err) { + function (err) { callback(err); }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- // Provisions the specified add-on for the specified project. -//----------------------------------------------------------------------------- -addOn.provision = function(projectName, addon, callback) { +// ---------------------------------------------------------------------------- +addOn.provision = function (projectName, addon, callback) { + var project; if (typeof addon !== 'string' || addon.length === 1) { - return callback('Please provide an add-on and plan. Use --help for the command format.'); + return callback( + 'Please provide an add-on and plan. Use --help for the command format.' + ); } addon = addon.split(':'); @@ -183,15 +198,14 @@ addOn.provision = function(projectName, addon, callback) { return callback('A plan is required to provision an add-on.'); } - var project, provisioned; - async.waterfall([ - function(cb) { + Async.waterfall([ + function (cb) { addOn.getProject(projectName, cb); }, - function(pro, cb) { + function (pro, cb) { project = pro; - addOnController.getById(addon[0], cb); + AddOnController.getById(addon[0], cb); }, function (addonData, cb) { @@ -199,54 +213,55 @@ addOn.provision = function(projectName, addon, callback) { }, function (region, cb) { - addOnController.provision(project.creator, project.id, addon[0], addon[1], region, cb); + AddOnController.provision( + project.creator, project.id, addon[0], addon[1], region, cb + ); }, - function(add, cb) { - provisioned = add; - addOnController.getForProject(project.id, cb); + function (add, cb) { // FIXME: ignores add; + AddOnController.getForProject(project.id, cb); }, - function(addons) { - - //Newline - console.log(); + function (addons) { + // Newline + print(); addOn.printList(project.name, addons); - console.log(); - modulus.io.success('Add-On \'' + addon[0] + '\' provisioned.'); + print(); + Modulus.io.success('Add-On \'' + addon[0] + '\' provisioned.'); } ], - function(err) { + function (err) { if (err) { - err = error.handleApiError(err, 'PROVISION_ADDON', callback); + err = Errors.handleApiError(err, 'PROVISION_ADDON', callback); } if (err.length > 0) { - callback(err); + return callback(err); } }); }; -addOn.deprovision = function(projectName, addOnId, callback) { - +addOn.deprovision = function (projectName, addOnId, callback) { var project, addon; - async.waterfall([ - function(cb) { + + Async.waterfall([ + function (cb) { addOn.getProject(projectName, cb); }, - function(pro, cb) { + function (pro, cb) { project = pro; - addOnController.getForProject(project.id, cb); + AddOnController.getForProject(project.id, cb); }, - function(addons, cb) { - if(addOnId) { - for(var a = 0; a < addons.length; a++) { - if(addons[a].addon_id === addOnId) { - return cb(null, addons[a]); + function (addons, cb) { + var i; + if (addOnId) { + for (i = 0; i < addons.length; ++i) { + if (addons[i].addon_id === addOnId) { + return cb(null, addons[i]); } } } @@ -254,14 +269,15 @@ addOn.deprovision = function(projectName, addOnId, callback) { addOn.chooseAddOnPrompt(addons, cb); }, - function(add, cb) { + function (add, cb) { addon = add; - addOnController.deprovision(project.id, addon.modulus_id, cb); + AddOnController.deprovision(project.id, addon.modulus_id, cb); } ], - function(err) { - if(!err) { - modulus.io.print('Add-On ' + addon.addon_name.data + ' has been deprovisioned.'); + function (err) { + var msg = 'Add-On ' + addon.addon_name.data + ' has been deprovisioned.'; + if (!err) { + print(msg); } callback(err); diff --git a/lib/commands/config.js b/lib/commands/config.js index 975720b..fe1b731 100644 --- a/lib/commands/config.js +++ b/lib/commands/config.js @@ -21,21 +21,21 @@ * */ -var modulus = require('../modulus'), - userConfig = require('../common/api').userConfig, - util = require('util'), - url = require('url'); +const Util = require('util'); -const invalid = ['username', 'userId', 'apiKey']; +const Modulus = require('../modulus'); +const UserConfig = require('../common/api').userConfig; + +var invalid = ['username', 'userId', 'apiKey']; exports.get = function list(name, cb) { - userConfig.load(); + UserConfig.load(); - if (!userConfig.data.hasOwnProperty(name)) { + if (!UserConfig.data.hasOwnProperty(name)) { return cb('Configuration name not found.'); } - modulus.io.print(util.format('%s: %s', name, userConfig.data[name]).input); + Modulus.io.print(Util.format('%s: %s', name, UserConfig.data[name]).input); return cb(); }; @@ -45,25 +45,25 @@ exports.set = function set(name, value, cb) { // // Don't allow username, userId, or apiKey to be set by the user. // - return cb(util.format('Cannot set value of \'%s\'', name)); + return cb(Util.format('Cannot set value of \'%s\'', name)); } - userConfig.load(); + UserConfig.load(); - if (!userConfig.data) userConfig.data = {}; + if (!UserConfig.data) UserConfig.data = {}; try { // // Attempt to parse the value to JSON. This will ensure that Booleans are // correctly stored as JSON rather than a string. // - userConfig.data[name] = JSON.parse(value); + UserConfig.data[name] = JSON.parse(value); } catch (e) { - userConfig.data[name] = value; + UserConfig.data[name] = value; } - userConfig.save(userConfig.data); - modulus.io.print(util.format('Saved \'%s\' to \'%s\'', value, name).input); + UserConfig.save(UserConfig.data); + Modulus.io.print(Util.format('Saved \'%s\' to \'%s\'', value, name).input); return cb(); }; diff --git a/lib/commands/env.js b/lib/commands/env.js index 500d4d8..5fc1a9b 100755 --- a/lib/commands/env.js +++ b/lib/commands/env.js @@ -1,3 +1,4 @@ +/* eslint-disable no-underscore-dangle */ /* * Copyright (c) 2014 Modulus * @@ -20,18 +21,20 @@ * THE SOFTWARE. * */ -var fs = require('fs'); -var path = require('path'); +const FS = require('fs'); +const Path = require('path'); -var async = require('async'); +const Async = require('async'); +const Util = require('util'); -var addOnController = require('../controllers/addOn'); -var error = require('../common/error'); -var modulus = require('../modulus'); -var projectController = require('../controllers/project'); -var userConfig = require('../common/api').userConfig; +const AddOnController = require('../controllers/addOn'); +const Errors = require('../common/error'); +const Modulus = require('../modulus'); +const ProjectController = require('../controllers/project'); +const UserConfig = require('../common/api').userConfig; -var env = {}; +var env = {}; +var print = Modulus.io.print; /** * Gets the specified environment variable for the specified project. @@ -40,11 +43,12 @@ var env = {}; * @param {String} name Environment variable name. * @param {Function} cb Callback function. */ -env.get = function(projectName, name, cb) { - env._getAndChooseProject(projectName, function(err, project) { - if (err) { return cb(err); } +env.get = function (projectName, name, cb) { + env._getAndChooseProject(projectName, function (err, project) { + var i; + if (err) return cb(err); - for (var i = 0; i < project.envVars.length; i++) { + for (i = 0; i < project.envVars.length; ++i) { if (project.envVars[i].name === name) { env._printEnv(project.envVars[i]); return cb(); @@ -63,24 +67,25 @@ env.get = function(projectName, name, cb) { * @param {String} file Path to write the environment variables to. * @param {Function} done Callback function. */ -env.export = function(projectName, file, done) { - var filePath = path.normalize(file); +env.export = function (projectName, file, done) { + var filePath = Path.normalize(file); env._getAndChooseProject(projectName, function (err, project) { - if (err) { - return done(err); - } - var envVars = {}; + if (err) return done(err); + project.envVars.forEach(function (v) { - envVars[v.name] = (typeof v.value === 'string') ? v.value : JSON.stringify(v.value) + var isString = typeof v.value === 'string'; + envVars[v.name] = isString ? v.value : JSON.stringify(v.value); }); - fs.writeFile(filePath, JSON.stringify(envVars, null, 2), function (fsErr) { + FS.writeFile(filePath, JSON.stringify(envVars, null, 2), function (fsErr) { if (fsErr) { - return done(error.handleApiError({ code: 'INVALID_FILE' }, 'EXPORT_VARS', done)); + return done( + Errors.handleApiError({ code: 'INVALID_FILE' }, 'EXPORT_VARS', done) + ); } - modulus.io.success('Successfully exported environment variables.'); + Modulus.io.success('Successfully exported environment variables.'); done(); }); }); @@ -92,39 +97,40 @@ env.export = function(projectName, file, done) { * for. * @param {Function} cb Callback function. */ -env.list = function(projectName, cb) { +env.list = function (projectName, cb) { var project; - async.waterfall([ - function(cb) { - env._getAndChooseProject(projectName, cb); + Async.waterfall([ + function (callback) { + env._getAndChooseProject(projectName, callback); }, - function(pro, cb) { + function (pro, callback) { project = pro; - modulus.io.print('Project ' + project.name.data + ' Environment Variables'); + print('Project ' + project.name.data + ' Environment Variables'); - addOnController.getConfigVars(project.id, cb); + AddOnController.getConfigVars(project.id, callback); }, - function(addonVars, cb) { - for (var i = 0; i < project.envVars.length; i++) { + function (addonVars, callback) { + var i; + for (i = 0; i < project.envVars.length; ++i) { env._printEnv(project.envVars[i]); } if (addonVars.length > 0) { - modulus.io.print('\nAdd-Ons'); + print('\nAdd-Ons'); - for (var c = 0; c < addonVars.length; c++) { - env._printEnv(addonVars[c]); + for (i = 0; i < addonVars.length; ++i) { + env._printEnv(addonVars[i]); } } - cb(null); + callback(null); } ], - function(err) { - if(err) { + function (err) { + if (err) { return cb(err); } @@ -141,16 +147,20 @@ env.list = function(projectName, cb) { * @param {String} value Value to set the environment variable to. * @param {Function} cb Callback function. */ -env.set = function(projectName, name, value, cb) { - modulus.commands.project.cmd = 'env set'; - env._getAndChooseProject(projectName, function(err, project) { - if (err) { return cb(err); } - - var newEnv = {name : name, value : value}; - var found = false; - modulus.io.print('Setting ' + newEnv.name.yellow + ' for project ' + project.name.data); - for (var i = 0; i < project.envVars.length; i++) { - if(project.envVars[i].name === newEnv.name) { +env.set = function (projectName, name, value, cb) { + Modulus.commands.project.cmd = 'env set'; + env._getAndChooseProject(projectName, function (err, project) { + var i, found, newEnv; + if (err) return cb(err); + + newEnv = { name: name, value: value }; + found = false; + print( + 'Setting ' + newEnv.name.yellow + ' for project ' + project.name.data + ); + + for (i = 0; i < project.envVars.length; ++i) { + if (project.envVars[i].name === newEnv.name) { project.envVars[i].value = newEnv.value; found = true; } @@ -160,15 +170,15 @@ env.set = function(projectName, name, value, cb) { project.envVars.push(newEnv); } - projectController.saveVars(project.id, project.envVars, function(err) { + ProjectController.saveVars(project.id, project.envVars, function (err) { if (err) { - err = error.handleApiError(err, 'SET_VARS', cb); + err = Errors.handleApiError(err, 'SET_VARS', cb); if (err.length > 0) { return cb(err); } } - modulus.io.success('Successfully set environment variable.'); + Modulus.io.success('Successfully set environment variable.'); return cb(); }); }); @@ -181,22 +191,22 @@ env.set = function(projectName, name, value, cb) { * @param {String} file Path to the file with the environment variable data. * @param {Function} cb Callback function. */ -env.load = function(projectName, file, cb) { - env._getAndChooseProject(projectName, function(err, project) { +env.load = function (projectName, file, cb) { + env._getAndChooseProject(projectName, function (err, project) { if (err) { return cb(err); } - async.waterfall([ - function(fn) { - fs.readFile(file, { encoding: 'utf8' }, function(err, fileData) { + Async.waterfall([ + function (fn) { + FS.readFile(file, { encoding: 'utf8' }, function (err, fileData) { if (err) { return fn({ code: 'INVALID_FILE' }, null); } fn(null, fileData); }); }, - function(json, fn) { + function (json, fn) { var ret = null; try { @@ -207,14 +217,14 @@ env.load = function(projectName, file, cb) { fn(null, ret); }, - function(data, fn) { - var keys = Object.keys(data); + function (data, fn) { + var i, ii, key, keys = Object.keys(data); // Update existing values. - for (var i = 0; i < project.envVars.length; i++) { + for (i = 0; i < project.envVars.length; ++i) { if (keys.indexOf(project.envVars[i].name) >= 0) { try { - var key = project.envVars[i].name; + key = project.envVars[i].name; if (typeof data[key] === 'string') { project.envVars[i].value = data[key]; @@ -230,7 +240,7 @@ env.load = function(projectName, file, cb) { } // Add new values. - for (var ii = 0; ii < keys.length; ii++) { + for (ii = 0; ii < keys.length; ++ii) { if (typeof data[keys[ii]] === 'string') { project.envVars.push({ name: keys[ii], @@ -250,8 +260,8 @@ env.load = function(projectName, file, cb) { fn(null); }, - function(fn) { - projectController.saveVars(project.id, project.envVars, function(err) { + function (fn) { + ProjectController.saveVars(project.id, project.envVars, function (err) { if (err) { return fn(err); } @@ -259,13 +269,15 @@ env.load = function(projectName, file, cb) { }); } ], - function(err) { + function (err) { if (err) { - err = error.handleApiError(err, 'LOAD_VARS', cb); + err = Errors.handleApiError(err, 'LOAD_VARS', cb); return cb(err); } - modulus.io.success('Successfully set environment variables loaded from file.'); + Modulus.io.success( + 'Successfully set environment variables loaded from file.' + ); }); }); }; @@ -276,13 +288,13 @@ env.load = function(projectName, file, cb) { * @param {String} name Environment variable to delete. * @param {Function} cb Callback function. */ -env.delete = function(projectName, name, cb) { - env._getAndChooseProject(projectName, function(err, project) { - if (err) { return cb(err); } +env.delete = function (projectName, name, cb) { + env._getAndChooseProject(projectName, function (err, project) { + var i, msg, found = false; + if (err) return cb(err); - var found = false; - modulus.io.print('Deleting ' + name.yellow + ' for project ' + project.name.data); - for (var i = 0; i < project.envVars.length; i++) { + print('Deleting ' + name.yellow + ' for project ' + project.name.data); + for (i = 0; i < project.envVars.length; ++i) { if (project.envVars[i].name === name) { project.envVars.splice(i, 1); found = true; @@ -291,18 +303,25 @@ env.delete = function(projectName, name, cb) { } if (!found) { - return cb('Variable ' + name.yellow + ' not found in project ' + project.name.data); + msg = Util.format( + 'Varibale %s not found in project %s.', name.yellow, project.name.data + ); + + return cb(msg); } - projectController.saveVars(project.id, project.envVars, function(err) { + ProjectController.saveVars(project.id, project.envVars, function (err) { if (err) { - err = error.handleApiError(err, 'SET_VARS', cb); - if(err.length > 0) { + err = Errors.handleApiError(err, 'SET_VARS', cb); + if (err.length > 0) { return cb(err); } } + msg = Util.format( + 'Successfully deleted variable %s from project %s.', name.yellow, project.name.data + ); - modulus.io.success('Successfully deleted variable ' + name.yellow + ' from project ' + project.name.data); + Modulus.io.success(msg); return cb(); }); }); @@ -315,18 +334,18 @@ env.delete = function(projectName, name, cb) { * @param {Function} cb Callback function. * @private */ -env._getAndChooseProject = function(projectName, cb) { +env._getAndChooseProject = function (projectName, cb) { if ('function' === typeof projectName) { cb = projectName; projectName = null; } - projectController.find({ - userId : userConfig.data.userId + ProjectController.find({ + userId: UserConfig.data.userId }, - function(err, projects) { + function (err, projects) { if (err) { - err = error.handleApiError(err, 'GET_PROJECTS', cb); + err = Errors.handleApiError(err, 'GET_PROJECTS', cb); if (err.length > 0) { return cb(err); } @@ -336,30 +355,33 @@ env._getAndChooseProject = function(projectName, cb) { return cb('You currently have no projects. You can create one with "project create".'); } - modulus.commands.project.chooseProjectPrompt(projects, projectName, function(err, result) { - if (err) { - return cb(err); - } - - if (!result) { - return cb('You must choose a project.'); - } - - projectController.find({ projectId: result.id }, function(err, project) { + Modulus.commands.project.chooseProjectPrompt( + projects, projectName, function (err, result) { if (err) { - err = error.handleApiError(err, 'FIND_PROJECT', cb); - if (err.length > 0) { - return cb(err); - } + return cb(err); } if (!result) { - return cb('No project found.'); + return cb('You must choose a project.'); } - return cb(null, project); + ProjectController.find( + { projectId: result.id }, + function (err, project) { + if (err) { + err = Errors.handleApiError(err, 'FIND_PROJECT', cb); + if (err.length > 0) { + return cb(err); + } + } + + if (!result) { + return cb('No project found.'); + } + + return cb(null, project); + }); }); - }); }); }; @@ -369,8 +391,9 @@ env._getAndChooseProject = function(projectName, cb) { * variable. * @private */ -env._printEnv = function(env) { - modulus.io.print(env.name.yellow + ' = ' + env.value.grey); +env._printEnv = function (envItem) { + print(envItem.name.yellow + ' = ' + envItem.value.grey); }; module.exports = env; +/* eslint-enable no-underscore-dangle */ diff --git a/lib/commands/help.js b/lib/commands/help.js index 1e11466..e77ce53 100755 --- a/lib/commands/help.js +++ b/lib/commands/help.js @@ -21,6 +21,6 @@ * */ -module.exports.text = function() { +module.exports.text = function () { -}; \ No newline at end of file +}; diff --git a/lib/commands/misc.js b/lib/commands/misc.js index 9b3687f..f92b2da 100755 --- a/lib/commands/misc.js +++ b/lib/commands/misc.js @@ -21,28 +21,30 @@ * */ -var modulus = require('../modulus'), - async = require('async'), - userConfig = require('../common/api').userConfig, - librarian = require('../common/api').librarian, - userController = require('../controllers/user'), - error = require('../common/error'), - fs = require('fs'); +const Async = require('async'); + +const Modulus = require('../modulus'); +const UserConfig = require('../common/api').userConfig; +const Librarian = require('../common/api').librarian; +const UserController = require('../controllers/user'); var misc = {}; -misc.contact = function(message, cb) { - async.waterfall([ - function(callback) { - userController.get(userConfig.data.userId, callback); +misc.contact = function (message, cb) { + Async.waterfall([ + function (callback) { + UserController.get(UserConfig.data.userId, callback); }, - function(user, callback) { - librarian.contact({userId : user.id, email : user.email, message : message}, callback); + function (user, callback) { + Librarian.contact( + { userId: user.id, email: user.email, message: message }, + callback + ); } - ], function(err, results) { - modulus.io.success('Feedback sent. Thank you for the message.'); + ], function (results) { // ignores 'error' + Modulus.io.success('Feedback sent. Thank you for the message.'); return cb(); }); }; -module.exports = misc; \ No newline at end of file +module.exports = misc; diff --git a/lib/commands/mongo.js b/lib/commands/mongo.js index 34c7316..34c9d2d 100644 --- a/lib/commands/mongo.js +++ b/lib/commands/mongo.js @@ -1,50 +1,53 @@ -var modulus = require('../modulus'), - mongoController = require('../controllers/mongo'), - util = require('util'), - error = require('../common/error'), - userConfig = require('../common/api').userConfig; +/* eslint-disable no-underscore-dangle */ +const Util = require('util'); + +const Modulus = require('../modulus'); +const MongoController = require('../controllers/mongo'); +const Errors = require('../common/error'); +const UserConfig = require('../common/api').userConfig; var mongo = {}; +var print = Modulus.io.print; // Find the index for the specified database in the specified database array. // Returns -1 if not found. // -var databaseInArray = function(databases, name) { - var database; +var databaseInArray = function (databases, name) { + var database, i, databaseLength = databases.length; - for (var i = 0; database = databases[i]; i++) { + for (i = 0; i < databaseLength; ++i) { if (database.name.toUpperCase() === name.toUpperCase()) return i; } return -1; }; -//------------------------------------------------------------------------------ -mongo.create = function(dbName, cb) { - var createDatabase = function(dname, regionData) { - mongoController.create( +// ---------------------------------------------------------------------------- +mongo.create = function (dbName, cb) { + var createDatabase = function (dname, regionData) { + MongoController.create( dname, - userConfig.data.userId, + UserConfig.data.userId, regionData, - function(err, database) { - if(err) { - err = error.handleApiError(err, 'CREATE_MONGO', cb); - if(err.length > 0) { + function (err, database) { + if (err) { + err = Errors.handleApiError(err, 'CREATE_MONGO', cb); + if (err.length > 0) { return cb(err); } } - if(!database) { + if (!database) { return cb('Could not create MongoDB database. Error from server.'); } - modulus.io.success('New MongoDB database ' + dname.data + ' created.'); - modulus.io.print('Database available at: ' + database.uri.data); + Modulus.io.success('New MongoDB database ' + dname.data + ' created.'); + print('Database available at: ' + database.uri.data); return cb(); - }); + }); }; // If project name is passed do NOT prompt for name. if (dbName && dbName !== '') { - modulus.io.print('Creating MongoDB database ' + dbName.data); + print('Creating MongoDB database ' + dbName.data); mongo.chooseRegionPrompt(function (err, regionData) { if (err) { @@ -54,7 +57,7 @@ mongo.create = function(dbName, cb) { createDatabase(dbName, regionData); }); } else { - mongo._createDatabasePrompt(function(err, name) { + mongo._createDatabasePrompt(function (err, name) { if (err) { return cb('Could not create MongoDB database.'); } @@ -70,78 +73,77 @@ mongo.create = function(dbName, cb) { } }; -//------------------------------------------------------------------------------ -mongo.createUser = function(databaseName, username, password, isReadOnly, cb) { - +// ---------------------------------------------------------------------------- +mongo.createUser = function (databaseName, username, password, isReadOnly, cb) { // All parameters are optional // if all parameters -> find database by name // Choose database // Enter Username, Password, isReadOnly - mongoController.databasesForUser( - userConfig.data.userId, - function(err, databases) { - if(err) { - err = error.handleApiError(err, 'GET_DATABASES', cb); - if(err.length > 0) { + MongoController.databasesForUser( + UserConfig.data.userId, + function (err, databases) { + if (err) { + err = Errors.handleApiError(err, 'GET_DATABASES', cb); + if (err.length > 0) { return cb(err); } } - if(databases.length === 0) { - modulus.io.error('You currently have no databases. One can be created using the `mongo create` command.'); + if (databases.length === 0) { + Modulus.io.error('You currently have no databases. One can be created using the `mongo create` command.'); return cb(); } - mongo.chooseDatabasePrompt(databases, databaseName, function(err, database) { - if(err) { - err = error.handleApiError(err, 'CREATE_MONGO_USER', cb); - if(err.length > 0) { - return cb(err); - } - } - if(!database) { - return cb('You must select a database.'); - } - modulus.io.print('Selected MongoDB database ' + database.name.data + '.'); - - mongo._userPrompt(username, password, isReadOnly, function(err, results) { - if(err) { - err = error.handleApiError(err, 'CREATE_MONGO_USER', cb); - if(err.length > 0) { + mongo.chooseDatabasePrompt( + databases, databaseName, function (err, database) { + if (err) { + err = Errors.handleApiError(err, 'CREATE_MONGO_USER', cb); + if (err.length > 0) { return cb(err); } } - mongoController.createUser( - database.id, - results.username, - results.password, - results.isReadOnly, - function(err, dbUser) { - if(err) { - err = error.handleApiError(err, 'CREATE_MONGO_USER', cb); - if(err.length > 0) { + if (!database) { + return cb('You must select a database.'); + } + print('Selected MongoDB database ' + database.name.data + '.'); + + mongo._userPrompt( + username, password, isReadOnly, function (err, results) { + if (err) { + err = Errors.handleApiError(err, 'CREATE_MONGO_USER', cb); + if (err.length > 0) { return cb(err); } } - if(!dbUser) { - return cb('Could not create MongoDB database user. Error from server.'); - } - modulus.io.success('New MongoDB database user ' + results.username.data + ' created.'); - return cb(); - }); + MongoController.createUser( + database.id, + results.username, + results.password, + results.isReadOnly, + function (err, dbUser) { + if (err) { + err = Errors.handleApiError(err, 'CREATE_MONGO_USER', cb); + if (err.length > 0) { + return cb(err); + } + } + if (!dbUser) { + return cb('Could not create MongoDB database user. Error from server.'); + } + Modulus.io.success('New MongoDB database user ' + results.username.data + ' created.'); + return cb(); + }); + }); }); - }); - }); - + }); }; +// ---------------------------------------------------------------------------- +mongo._userPrompt = function (username, password, isReadOnly, cb) { + var prompt = []; + var out = {}; -//------------------------------------------------------------------------------ -mongo._userPrompt = function(username, password, isReadOnly, cb) { - var prompt = [], - out = {}; - - if(!username || username === '') { + if (!username || username === '') { prompt.push({ name: 'username', description: 'Enter username:', @@ -150,34 +152,34 @@ mongo._userPrompt = function(username, password, isReadOnly, cb) { }); } - if(!password || password === '') { + if (!password || password === '') { prompt.push({ name: 'password', description: 'Enter password:', message: 'Password is required.', - hidden : true, + hidden: true, required: true }); } - if(typeof isReadOnly !== 'boolean') { + if (typeof isReadOnly !== 'boolean') { prompt.push({ - name : 'isReadOnly', - description : 'Read only permissions?', - message : 'Acceptable response is "yes" or "no".', - pattern : /^[yntf]{1}/i, - default : 'yes' + name: 'isReadOnly', + description: 'Read only permissions?', + message: 'Acceptable response is "yes" or "no".', + pattern: /^[yntf]{1}/i, + default: 'yes' }); } - if(prompt.length > 0) { - modulus.io.prompt.get(prompt, function (err, results) { - if(err) { - return error.handlePromptError(err, cb); + if (prompt.length > 0) { + Modulus.io.prompt.get(prompt, function (err, results) { + if (err) { + return Errors.handlePromptError(err, cb); } out.username = results.username || username; out.password = results.password || password; - if(results.isReadOnly) { + if (results.isReadOnly) { out.isReadOnly = /^[yt]{1}/i.test(results.isReadOnly); } else { out.isReadOnly = isReadOnly; @@ -185,42 +187,44 @@ mongo._userPrompt = function(username, password, isReadOnly, cb) { return cb(null, out); }); } else { - return cb(null, {username: username, password: password, isReadOnly: isReadOnly}); + return cb( + null, { username: username, password: password, isReadOnly: isReadOnly } + ); } }; -//------------------------------------------------------------------------------ -mongo._createDatabasePrompt = function(cb) { - modulus.io.prompt.get([{ - name : 'name', - description : 'Enter a database name:', - maxLength : 50, - required : true - }], function(err, results) { - if(err) { - return error.handlePromptError(err, cb); +// ---------------------------------------------------------------------------- +mongo._createDatabasePrompt = function (cb) { + Modulus.io.prompt.get([{ + name: 'name', + description: 'Enter a database name:', + maxLength: 50, + required: true + }], function (err, results) { + if (err) { + return Errors.handlePromptError(err, cb); } cb(null, results.name); }); }; -//------------------------------------------------------------------------------ +// ---------------------------------------------------------------------------- /** * Displays a prompt for choosing databases. * @param {Array} databases Array of user's database. * @param {String} [databaseName] Default selection. * @param {Function} cb */ -//------------------------------------------------------------------------------ -mongo.chooseDatabasePrompt = function(databases, databaseName, cb) { - var databaseIndex = -1; +// ---------------------------------------------------------------------------- +mongo.chooseDatabasePrompt = function (databases, databaseName, cb) { + var i, index, len, msg, selectedDatabase, databaseIndex = -1; - if(typeof databaseName === 'function') { + if (typeof databaseName === 'function') { cb = databaseName; databaseName = null; } // A default selection has been made. See if a match exists in the collection. - if(typeof databaseName === 'string' && databaseName !== '') { + if (typeof databaseName === 'string' && databaseName !== '') { databaseIndex = databaseInArray(databases, databaseName); if (databaseIndex >= 0) return cb(null, databases[databaseIndex]); @@ -228,65 +232,75 @@ mongo.chooseDatabasePrompt = function(databases, databaseName, cb) { return cb({ code: 'NO_MATCHING_DB_NAME' }); } - if(databases.length === 1) { - var selectedDatabase = databases[0]; - modulus.io.prompt.get([{ - name : 'confirm', - description : 'Are you sure you want to use database ' + selectedDatabase.name.data + '?', - message : 'Acceptable response is "yes" or "no".', - pattern : /^[yntf]{1}/i, - default : 'yes' - }], function(err, result) { - if(err) { - return error.handlePromptError(err, cb); + if (databases.length === 1) { + msg = Util.format( + 'Are you sure you want to use database %s ?', + selectedDatabase.name.data + ); + + selectedDatabase = databases[0]; + Modulus.io.prompt.get([{ + name: 'confirm', + description: msg, + message: 'Acceptable response is "yes" or "no".', + pattern: /^[yntf]{1}/i, + default: 'yes' + }], function (err, result) { + var y, p; + + if (err) { + return Errors.handlePromptError(err, cb); } - var y = /^[yt]{1}/i.test(result.confirm); - var p = y ? selectedDatabase : null; - console.log(''); + y = /^[yt]{1}/i.test(result.confirm); + p = y ? selectedDatabase : null; + print(''); return cb(null, p); }); } else { - modulus.io.print('Please choose which database to use:'.input); - for(var i = 0, len = databases.length; i < len; i++) { - var index = i + 1; - modulus.io.print(' ' + index.toString().input + ') '.input + databases[i].name.input); + print('Please choose which database to use:'.input); + for (i = 0, len = databases.length; i < len; ++i) { + index = i + 1; + print( + ' ' + index.toString().input + ') '.input + databases[i].name.input + ); } - modulus.io.prompt.get([{ - name : 'database', - description : 'Database Number?', - warning : 'Database number has to be between 1 and ' + databases.length, - required : true, - type : 'number', - minimum : 1, - maximum : databases.length - }], function(err, result) { - if(err) { - return error.handlePromptError(err, cb); + + Modulus.io.prompt.get([{ + name: 'database', + description: 'Database Number?', + warning: 'Database number has to be between 1 and ' + databases.length, + required: true, + type: 'number', + minimum: 1, + maximum: databases.length + }], function (err, result) { + if (err) { + return Errors.handlePromptError(err, cb); } return cb(null, databases[result.database - 1]); }); } }; -//------------------------------------------------------------------------------ +// ---------------------------------------------------------------------------- mongo.chooseRegionPrompt = function (callback) { - mongoController.getDeployTargets(function (err, regions) { + MongoController.getDeployTargets(function (err, regions) { + var i; if (err) { - return error.handlePromptError(err, callback); + return Errors.handlePromptError(err, callback); } - modulus.io.print('Please choose a region:'.input); - - for (var i = 0; i < regions.length; i++) { + print('Please choose a region:'.input); - modulus.io.print(util.format( - '(%s) %s - %s %s', (i + 1), + for (i = 0; i < regions.length; ++i) { + print(Util.format( + '(%s) %s - %s %s', i + 1, regions[i].version, regions[i].iaas, regions[i].region).input); } - modulus.io.prompt.get([ + Modulus.io.prompt.get([ { name: 'region', description: 'Region?', @@ -296,21 +310,23 @@ mongo.chooseRegionPrompt = function (callback) { maximum: regions.length } ], function (err, result) { - if (err) { - return error.handlePromptError(err, callback); - } + var selected; + if (err) { + return Errors.handlePromptError(err, callback); + } - var selected = util.format( - '%s (%s %s)', - regions[result.region - 1].version, - regions[result.region - 1].iaas, - regions[result.region - 1].region - ); + selected = Util.format( + '%s (%s %s)', + regions[result.region - 1].version, + regions[result.region - 1].iaas, + regions[result.region - 1].region + ); - modulus.io.print(util.format('Select %s\n', selected.data)); - callback(null, regions[result.region - 1]); - }); + print(Util.format('Select %s\n', selected.data)); + callback(null, regions[result.region - 1]); + }); }); }; module.exports = mongo; +/* eslint-enable no-underscore-dangle */ diff --git a/lib/commands/project.js b/lib/commands/project.js index 4f0d6c2..b567984 100755 --- a/lib/commands/project.js +++ b/lib/commands/project.js @@ -1,3 +1,4 @@ +/* eslint-disable no-sync, no-underscore-dangle */ /* * Copyright (c) 2014 Modulus * @@ -21,39 +22,40 @@ * */ -var fs = require('fs'); -var path = require('path'); -var util = require('util'); -var _ = require('underscore'); -var URL = require('url'); -var proc = require('child_process'); +const FS = require('fs'); +const Path = require('path'); +const Util = require('util'); +const _ = require('underscore'); +const URL = require('url'); +const Proc = require('child_process'); -var async = require('async'); -var findFileSync = require('find-file-sync'); -var createTable = require('text-table'); +const Async = require('async'); +const FindFileSync = require('find-file-sync'); +const CreateTable = require('text-table'); -var modulus = require('../modulus'); -var projectController = require('../controllers/project'); -var imagesController = require('../controllers/images'); -var userController = require('../controllers/user'); +const Modulus = require('../modulus'); +const ProjectController = require('../controllers/project'); +const ImagesController = require('../controllers/images'); +const UserController = require('../controllers/user'); -var userConfig = require('../common/api').userConfig; -var error = require('../common/error'); -var verify = require('../common/verifyPackage'); +const UserConfig = require('../common/api').userConfig; +const Errors = require('../common/error'); +const Verify = require('../common/verifyPackage'); -var project = {}; -var autoCmds = ['start', 'deploy', 'env set']; -var uploadTries = 0; -var uploadTriesMax = 5; +const UPLOADTRIES = 0; +const UPLOADTRIESMAX = 5; + +var project = {}; +var autoCmds = ['start', 'deploy', 'env set']; // Find the index for the specified project in the specified projects array. // Returns -1 if not found. // var projectInArray = function (projects, name) { - var project; + var i, projectItem, projectsLength = projects.length(); - for (var i = 0; project = projects[i]; i++) { - if (project.name.toUpperCase() === name.toUpperCase()) return i; + for (i = 0; projectsLength < i; ++i) { + if (projectItem.name.toUpperCase() === name.toUpperCase()) return i; } return -1; @@ -64,11 +66,12 @@ var projectInArray = function (projects, name) { // function sortImages(images) { images.forEach(function (image) { + const SORT = 99; var index = ['Node.js', 'Java', 'PHP', 'Static'].indexOf(image.label); // Default to sort order of 99 rather than -1 to ensure that new // images are added to the end of the list. - image.sortOrder = index >= 0 ? index : 99; + image.sortOrder = index >= 0 ? index : SORT; }); images.sort(function (a, b) { @@ -91,73 +94,75 @@ project.restart = function (projectName, cb) { }; project.stopStartRestart = function (action, projectName, cb) { - projectController.find({ - userId : userConfig.data.userId - }, + ProjectController.find({ + userId: UserConfig.data.userId + }, function (err, projects) { if (err) { - err = error.handleApiError(err, 'GET_PROJECTS', cb); + err = Errors.handleApiError(err, 'GET_PROJECTS', cb); if (err.length > 0) { return cb(err); } } if (projects.length === 0) { - modulus.io.error('You currently have no projects. One can be created using the create command.'); + Modulus.io.error('You currently have no projects. One can be created using the create command.'); return cb(); } project.cmd = action; - project.chooseProjectPrompt(projects, projectName, function (err, result) { - if (err) { - return cb(err); - } - - if (!result) { - return cb('You must select a project.'); - } + project.chooseProjectPrompt( + projects, projectName, function (err, result) { + var func, message; + if (err) { + return cb(err); + } - var func = null; - var message = null; - - switch(action) { - case 'restart' : - func = projectController.restart; - message = result.name + ' restarted at ' + result.domain; - break; - case 'stop' : - func = projectController.stop; - message = result.name + ' stopped'; - break; - case 'start' : - func = projectController.start; - message = result.name + ' started at ' + result.domain; - break; - } + if (!result) { + return cb('You must select a project.'); + } - func(result.id, function (err) { - if (!err) { - modulus.io.success(message); + switch (action) { + case 'restart' : + func = ProjectController.restart; + message = result.name + ' restarted at ' + result.domain; + break; + case 'stop' : + func = ProjectController.stop; + message = result.name + ' stopped'; + break; + case 'start' : + func = ProjectController.start; + message = result.name + ' started at ' + result.domain; + break; + default: + message = 'Please choose to start, stop or restart'; } - cb(err); + + func(result.id, function (err) { + if (!err) { + Modulus.io.success(message); + } + cb(err); + }); }); - }); }); }; project.list = function (cb) { - projectController.find({ - userId : userConfig.data.userId - }, + var owners, proj, userProjects, orgProjects; + ProjectController.find({ + userId: UserConfig.data.userId + }, function (err, projects) { var table = []; if (err) { - err = error.handleApiError(err, 'PROJECT_LIST', cb); + err = Errors.handleApiError(err, 'PROJECT_LIST', cb); if (err.length > 0) { return cb(err); } } if (projects.length === 0) { - modulus.io.print('You currently have no projects. You can create one with "project create".'); + Modulus.io.print('You currently have no projects. You can create one with "project create".'); return cb(); } @@ -178,136 +183,136 @@ project.list = function (cb) { } } - function getDomain(project) { + function getDomain(projectItem) { var ret = ''; - if (project.customDomains.length > 0) { - ret = project.customDomains[0].domain; + if (projectItem.customDomains.length > 0) { + ret = projectItem.customDomains[0].domain; } else { - ret = project.domain; + ret = projectItem.domain; } ret = ret.replace('*.', ''); - return ret.indexOf('http') >= 0 ? ret : 'http://' + ret; } projects = _.sortBy(projects, 'creator'); - var userProjects = []; - var orgProjects = []; + userProjects = []; + orgProjects = []; - projects.forEach(function (project) { - if (userConfig.data.userId === project.creator) { - userProjects.push(project); + projects.forEach(function (projectItem) { + if (UserConfig.data.userId === projectItem.creator) { + userProjects.push(projectItem); } else { - orgProjects.push(project); + orgProjects.push(projectItem); } }); // make sure the current user's projects display first - var proj = userProjects.concat(orgProjects); - - var owners = {}; - modulus.io.print('Current projects:'.input); - async.mapSeries(proj, function (project, callback) { - if (project.creator === userConfig.data.userId) { - owners[project.creator] = userConfig.data.username; - return callback(null, userConfig.data.username); + proj = userProjects.concat(orgProjects); + + owners = {}; + Modulus.io.print('Current projects:'.input); + Async.mapSeries(proj, function (projectItem, callback) { + if (projectItem.creator === UserConfig.data.userId) { + owners[projectItem.creator] = UserConfig.data.username; + return callback(null, UserConfig.data.username); } - if (owners.hasOwnProperty(project.creator)) { - return callback(null, owners[project.creator]); + if (owners.hasOwnProperty(projectItem.creator)) { + return callback(null, owners[projectItem.creator]); } - userController.get(project.creator, function (err, user) { + UserController.get(projectItem.creator, function (err, user) { if (err) { if (err.errors && err.errors.length >= 1 && err.errors[0].id === 'INVALID_AUTH') { // An invalid authorization error means that the user does not // have administrator access to the organization. In this case, // use a generic user header for the projects. - owners[project.creator] = 'User ' + project.creator; - return callback(null, 'User ' + project.creator); + owners[projectItem.creator] = 'User ' + projectItem.creator; + return callback(null, 'User ' + projectItem.creator); } return callback(err); } - owners[project.creator] = user.username; + owners[projectItem.creator] = user.username; return callback(null, user.username); }); }, function (err, results) { if (err) { - err = error.handleApiError(err, 'PROJECT_LIST', cb); - if (err.length > 0) { - cb(err); - } - - return; + err = Errors.handleApiError(err, 'PROJECT_LIST', cb); + if (err.length > 0) return cb(err); + return cb(null, results); } - proj.forEach(function (project, index) { + proj.forEach(function (eachProject, index) { + var images = eachProject.images; // display only one user/organization header - if (owners[project.creator] === results[index]) { - table.push([], [owners[project.creator].main], ['----------------------']); - delete owners[project.creator]; + if (owners[eachProject.creator] === results[index]) { + table.push([], [owners[eachProject.creator].main], ['----------------------']); + delete owners[eachProject.creator]; } table.push([ - project.name.data, - project.images && project.images.run ? project.images.run.label : 'Node.js', - colorStatus(project.status), - getDomain(project) + eachProject.name.data, + images && images.run ? images.run.label : 'Node.js', + colorStatus(eachProject.status), + getDomain(eachProject) ]); }); - modulus.io.print(createTable(table)); - - return cb(err); + Modulus.io.print(CreateTable(table)); + cb(err); }); } ); }; -project.delete = function(projectName, cb) { - async.waterfall([ - function getUserProjects (fn) { - projectController.find({ userId: userConfig.data.userId }, function (err, results) { - if (err) { - return error.handleApiError(err, 'GET_PROJECTS', fn); - } +project.delete = function (projectName, cb) { + Async.waterfall([ + function getUserProjects(fn) { + ProjectController.find( + { userId: UserConfig.data.userId }, function (err, results) { + if (err) { + return Errors.handleApiError(err, 'GET_PROJECTS', fn); + } - if (results.length === 0) { - return error.handleApiError({ code: 'PROJECTS_NOT_FOUND' }, 'GET_PROJECTS', fn); - } + if (results.length === 0) { + return Errors.handleApiError( + { code: 'PROJECTS_NOT_FOUND' }, 'GET_PROJECTS', fn + ); + } - fn(null, results); - }); + fn(null, results); + }); }, - function promptForProject (projects, fn) { + function promptForProject(projects, fn) { if (projectName && projectInArray(projects, projectName) === -1) { - modulus.io.error('Project not found'); + Modulus.io.error('Project not found'); return fn(null, projects, null); } - project.chooseProjectPrompt(projects, projectName, function(err, selectedProject) { - if (err) { - return error.handlePromptError(err, fn); - } + project.chooseProjectPrompt( + projects, projectName, function (err, selectedProject) { + if (err) { + return Errors.handlePromptError(err, fn); + } - fn(null, selectedProject); - }); + fn(null, selectedProject); + }); }, - function deleteProject(project, fn) { - projectController.delete(project.id, function(err, result) { + function deleteProject(projectToDelete, fn) { + ProjectController.delete(projectToDelete.id, function (err, result) { if (err) { - err = error.handleApiError(err, 'DELETE_PROJECT', fn); + err = Errors.handleApiError(err, 'DELETE_PROJECT', fn); if (err.length > 0) { return fn(err); } } - modulus.io.success('Project ' + project.name + ' deleted.'); + Modulus.io.success('Project ' + projectToDelete.name + ' deleted.'); fn(null, result); }); } @@ -317,11 +322,11 @@ project.delete = function(projectName, cb) { project.create = function (projectName, servoSize, runtime, cb) { var user, projects, images, imageTagIds = {}; - async.series([ + Async.series([ function getUser(fn) { - userController.get(userConfig.data.userId, function (err, result) { + UserController.get(UserConfig.data.userId, function (err, result) { if (err) { - err = error.handleApiError(err, 'GET_PROJECTS', fn); + err = Errors.handleApiError(err, 'GET_PROJECTS', fn); if (err.length > 0) { return fn(err); } @@ -332,12 +337,12 @@ project.create = function (projectName, servoSize, runtime, cb) { }); }, function findUserProjects(fn) { - projectController.find({ - userId: userConfig.data.userId + ProjectController.find({ + userId: UserConfig.data.userId }, function (err, result) { if (err) { - err = error.handleApiError(err, 'GET_PROJECTS', fn); + err = Errors.handleApiError(err, 'GET_PROJECTS', fn); if (err.length > 0) { return fn(err); } @@ -354,7 +359,7 @@ project.create = function (projectName, servoSize, runtime, cb) { }, function promptForProject(fn) { if (projectName && projectName !== '') { - modulus.io.print('Creating project ' + projectName.data); + Modulus.io.print('Creating project ' + projectName.data); return fn(); } @@ -368,9 +373,9 @@ project.create = function (projectName, servoSize, runtime, cb) { }); }, function getImages(fn) { - imagesController.getAll(function (err, result) { + ImagesController.getAll(function (err, result) { if (err) { - err = error.handleApiError(err, 'DEFAULT', fn); + err = Errors.handleApiError(err, 'DEFAULT', fn); if (err.length > 0) { return fn(err); } @@ -382,7 +387,9 @@ project.create = function (projectName, servoSize, runtime, cb) { }); }, function promptForImage(fn) { - function getImageTag (label, type) { + var filteredImages; + + function getImageTag(label, type) { var ret = ''; images.forEach(function (image) { @@ -409,8 +416,8 @@ project.create = function (projectName, servoSize, runtime, cb) { return fn(); } - modulus.io.print('Please choose which runtime to use:'.input); - var filteredImages = images.filter(function (image) { + Modulus.io.print('Please choose which runtime to use:'.input); + filteredImages = images.filter(function (image) { return 'run' === image.type && image.official; }); @@ -421,24 +428,29 @@ project.create = function (projectName, servoSize, runtime, cb) { out += (' (' + (image.stability || 'beta') + ')').input; } - modulus.io.print(out); + Modulus.io.print(out); }); - modulus.io.prompt.get([{ - name : 'runtime', - description : 'Image number?', - required : true, - type : 'number', - minimum : 1, - maximum : filteredImages.length + Modulus.io.prompt.get([{ + name: 'runtime', + description: 'Image number?', + required: true, + type: 'number', + minimum: 1, + maximum: filteredImages.length }], function (err, result) { if (err) { - return error.handlePromptError(err, fn); + return Errors.handlePromptError(err, fn); } - imageTagIds.run = getImageTag(filteredImages[result.runtime - 1].label, 'run'); - imageTagIds.build = getImageTag(filteredImages[result.runtime - 1].label, 'build'); + imageTagIds.run = getImageTag( + filteredImages[result.runtime - 1].label, 'run' + ); + + imageTagIds.build = getImageTag( + filteredImages[result.runtime - 1].label, 'build' + ); fn(); }); @@ -448,19 +460,20 @@ project.create = function (projectName, servoSize, runtime, cb) { return fn(); } - modulus.io.prompt.get([{ - name : 'servoSize', - description : 'Enter a servo size in MB [192, 396, 512, 1024, or 2048] (optional, default 512):', - message : 'Servo size should be a number (192, 396, 512, 1024, 2048) or empty', - required : false, - pattern : /^\d+$/ + Modulus.io.prompt.get([{ + name: 'servoSize', + description: 'Enter a servo size in MB [192, 396, 512, 1024, or 2048] (optional, default 512):', + message: 'Servo size should be a number (192, 396, 512, 1024, 2048) or empty', + required: false, + pattern: /^\d+$/ }], function (err, result) { + const SERVOSIZE = 512; if (err) { - return error.handlePromptError(err, cb); + return Errors.handlePromptError(err, cb); } - servoSize = result.servoSize || 512; + servoSize = result.servoSize || SERVOSIZE; fn(); }); } @@ -470,31 +483,31 @@ project.create = function (projectName, servoSize, runtime, cb) { return cb(err); } - projectController.create( + ProjectController.create( projectName, user.id, servoSize, imageTagIds, - function (err, project) { + function (err, newProject) { if (err) { - err = error.handleApiError(err, 'CREATE_PROJECT', cb); + err = Errors.handleApiError(err, 'CREATE_PROJECT', cb); if (err.length > 0) { return cb(err); } } - if (!project) { + if (!newProject) { return cb('Could not create project. Error from server.'); } - modulus.io.success('New project ' + projectName.data + ' created.'); - return cb(null, project); + Modulus.io.success('New project ' + projectName.data + ' created.'); + return cb(null, newProject); }); }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- /** * Deploys a project. * @param {string} projectName Name of the project to deploy. Specifying this skips prompts. @@ -505,36 +518,38 @@ project.create = function (projectName, servoSize, runtime, cb) { * @param {boolean} withTests Value indicating whether to run tests for the project on deploy. * @param {function} cb The callback. */ -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- project.deploy = function (projectName, dir, includeModules, registry, meteorDebug, withTests, cb) { + var isFatal, url; + if (typeof dir !== 'string') { dir = process.cwd(); } - verify(dir, function (err, probs) { + Verify(dir, function (err, probs) { if (err) { return cb(err); } if (probs && probs.length) { - var isFatal = false; - modulus.io.print(''); + isFatal = false; + Modulus.io.print(''); probs.forEach(function (problem) { isFatal = isFatal || problem.level === 'FATAL'; - if (problem.level === 'FATAL') - modulus.io.error(problem.message); - else - modulus.io.warning(problem.message); + if (problem.level === 'FATAL') Modulus.io.error(problem.message); + Modulus.io.warning(problem.message); }); - if (isFatal) return cb('There were problems with your project\'s package.json.'); + if (isFatal) { + return cb('There were problems with your project\'s package.json.'); + } } }); if (registry) { - var url = URL.parse(registry); + url = URL.parse(registry); if (!url.protocol) { return cb('You must specify the protocol for the registry URL.'); @@ -546,321 +561,333 @@ project.deploy = function (projectName, dir, includeModules, registry, meteorDeb project.cmd = 'deploy'; - dir = path.resolve(dir); + dir = Path.resolve(dir); dir = dir.replace(/\\/g, '/'); - if (!fs.existsSync(dir)) { - return cb('Directory "' + dir + '" does not exist.'); - } else { - project.dir = dir; - } + if (FS.existsSync(dir)) project.dir = dir; + else return cb('Directory "' + dir + '" does not exist.'); - async.waterfall([ - function getUserProjects (fn) { - projectController.find({ userId: userConfig.data.userId }, function (err, projects) { - if (err) { - return error.handleApiError(err, 'GET_PROJECTS', fn); - } + Async.waterfall([ + function getUserProjects(fn) { + ProjectController.find( + { userId: UserConfig.data.userId }, function (err, projects) { + if (err) { + return Errors.handleApiError(err, 'GET_PROJECTS', fn); + } - if (projects.length === 0) { - return error.handleApiError({ code: 'PROJECTS_NOT_FOUND' }, 'GET_PROJECTS', fn); - } + if (projects.length === 0) { + return Errors.handleApiError( + { code: 'PROJECTS_NOT_FOUND' }, 'GET_PROJECTS', fn + ); + } - fn(null, projects); - }); + fn(null, projects); + }); }, - function promptForProject (projects, fn) { + function promptForProject(projects, fn) { if (projectName && projectInArray(projects, projectName) === -1) { return fn(null, projects, null); } - project.chooseProjectPrompt(projects, projectName, function(err, selectedProject) { - fn(err, projects, selectedProject); - }); + project.chooseProjectPrompt( + projects, projectName, function (err, selectedProject) { + fn(err, projects, selectedProject); + }); }, - function verifyProjectExists (projects, selectedProject, fn) { + function verifyProjectExists(projects, selectedProject, fn) { if (selectedProject) { return fn(null, selectedProject); } - modulus.io.prompt.get([{ - name : 'createProject', - description : 'Project ' + projectName + ' not found, do you want to create it?', - message : 'Acceptable response is "yes" or "no".', - pattern : /^[yntf]{1}/i, + Modulus.io.prompt.get([{ + name: 'createProject', + description: 'Project ' + projectName + ' not found, do you want to create it?', + message: 'Acceptable response is "yes" or "no".', + pattern: /^[yntf]{1}/i, default: 'no' }], function (err, result) { + var answer; if (err) { - return error.handleApiError(err, 'CONFIRM_CREATE_PROJECT', fn); + return Errors.handleApiError(err, 'CONFIRM_CREATE_PROJECT', fn); } - var answer = /^[yt]{1}/i.test(result.createProject); + answer = /^[yt]{1}/i.test(result.createProject); if (answer) { - return project.create(projectName, null, null, function (err, project) { - fn(null, project); + return project.create(projectName, null, null, function (err, newProject) { + if (err) fn(err); + fn(null, newProject); }); } - return error.handleApiError({ code: 'NO_MATCHING_NAME' }, 'CHOOSE_PROJECT_PROMPT', fn); + return Errors.handleApiError({ code: 'NO_MATCHING_NAME' }, 'CHOOSE_PROJECT_PROMPT', fn); }); }, - function deployProject (selectedProject, fn) { + function deployProject(selectedProject, fn) { if (!selectedProject) { return fn('You must deploy to a project.'); } - projectController.deploy(selectedProject.id, dir, includeModules, registry, meteorDebug, withTests, function (err, domain) { - if (!err) { - modulus.io.success(selectedProject.name + ' running at ' + domain); - fn(); - } else { - projectController.status(selectedProject.id, function (e, status) { - if (e) { - return error.handleApiError(e, 'DEPLOY_PROJECT', fn); - } + ProjectController.deploy( + selectedProject.id, dir, includeModules, registry, meteorDebug, withTests, function (err, domain) { + if (err) { + ProjectController.status(selectedProject.id, function (e, status) { + if (e) { + return Errors.handleApiError(e, 'DEPLOY_PROJECT', fn); + } - //get the max upload retries - uploadTriesMax = userConfig.data.upload_retry || uploadTriesMax; + // get the max upload retries + UPLOADTRIESMAX = UserConfig.data.upload_retry || UPLOADTRIESMAX; - if (status === 'UPLOADING' && uploadTries < uploadTriesMax) { - uploadTries++; - modulus.io.error(util.format('Upload Failed. Retrying. (%s/%s)', uploadTries, uploadTriesMax)); - project.deploy(selectedProject.name, dir, includeModules, registry, meteorDebug, fn); - } else { - fn(err); - } - }); - } - }); + if (status === 'UPLOADING' && UPLOADTRIES < UPLOADTRIESMAX) { + UPLOADTRIES++; + Modulus.io.error(Util.format('Upload Failed. Retrying. (%s/%s)', UPLOADTRIES, UPLOADTRIESMAX)); + project.deploy(selectedProject.name, dir, includeModules, registry, meteorDebug, fn); + } else { + fn(err); + } + }); + } + Modulus.io.success(selectedProject.name + ' running at ' + domain); + fn(); + }); } ], cb); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- /** - * Description - Gets the logs for a specific project. May download or print to console. + * Description - Gets the logs for a specific project. May download or print to + * console. * @param {string} projectName - name of the project to retrieve logs from. - * @param {string} download - flag to swap between printing and downloading logs. + * @param {string} download - flag to swap between printing & downloading logs. * @param {string} output - filename to download the tarball at * @param {string} dir - directory to download to * @param {function} cb Callback invoked with log data. */ -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- project.getLogs = function (projectName, download, output, dir, cb) { if (typeof dir !== 'string') { dir = process.cwd(); } - dir = path.resolve(dir); + dir = Path.resolve(dir); dir = dir.replace(/\\/g, '/'); - if (!fs.existsSync(dir)) { + if (!FS.existsSync(dir)) { return cb('Directory "' + dir + '" does not exist.'); } - projectController.find({ - userId : userConfig.data.userId - }, + ProjectController.find( + { userId: UserConfig.data.userId }, function (err, projects) { + var selectedProject = null; if (err) { - err = error.handleApiError(err, 'GET_PROJECT_LOGS', cb); + err = Errors.handleApiError(err, 'GET_PROJECT_LOGS', cb); if (err.length > 0) { return cb(err); } } if (projects.length === 0) { - modulus.io.error('You currently have no projects. You can create one with "project create".'); + Modulus.io.error('You currently have no projects. You can create one with "project create".'); return cb(); } - var selectedProject = null; + project.chooseProjectPrompt( + projects, projectName, function (err, result) { + if (err) { + return cb(err); + } - project.chooseProjectPrompt(projects, projectName, function (err, result) { - if (err) { - return cb(err); - } + if (!result) { + return cb('You must select a project.'); + } - if (!result) { - return cb('You must select a project.'); - } + selectedProject = result; - selectedProject = result; + if (result.status !== 'RUNNING') { + return cb('Your project is not running. Please start your project to retrieve logs.'); + } - if (result.status !== 'RUNNING'){ - return cb('Your project is not running. Please start your project to retrieve logs.'); - } - if (download){ - projectController.downloadLogs(result.id, result.name, output, function (err, res) { - if (!err){ - modulus.io.success(res.msg); - } else { - modulus.io.error('Problem downloading logs.'); - } - cb(err); - }); - } else{ - projectController.getLogs(selectedProject.id, function (err, logs) { + if (download) { + ProjectController.downloadLogs( + result.id, result.name, output, function (err, res) { + if (!err) Modulus.io.success(res.msg); + Modulus.io.error('Problem downloading logs.'); + cb(err); + }); + } + ProjectController.getLogs(selectedProject.id, function (err, logs) { if (err) return cb(err); if (logs.length === 1) { - modulus.io.print(logs[0].log); - modulus.io.success('Logs successfully retrieved.'); - cb(); - } else if (logs.length > 0) { - - project.chooseServoPrompt(selectedProject, false, function (err, servo) { - if (err) { - return cb(err); - } - - for(var i = 0; i < logs.length; i++) { - if (logs[i].servo.id === servo.id) { - modulus.io.print(logs[i].log); - modulus.io.success('Logs successfully retrieved for servo ' + servo.id); - return cb(); + Modulus.io.print(logs[0].log); + Modulus.io.success('Logs successfully retrieved.'); + return cb(); + } + + if (logs.length > 0) { + project.chooseServoPrompt( + selectedProject, false, function (err, servo) { + var i; + if (err) { + return cb(err); } - } - modulus.io.print('No log data.'); + for (i = 0; i < logs.length; ++i) { + if (logs[i].servo.id === servo.id) { + Modulus.io.print(logs[i].log); + Modulus.io.success( + 'Logs successfully retrieved for servo ' + servo.id + ); - }); + return cb(); + } + } + + Modulus.io.print('No log data.'); + }); } }); - } - }); + }); } ); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- /** * Description - Wipes the logs for a specific project * @param {string} projectName - name of the project to retrieve logs from. * @param {function} cb - Callback invoked with log data. */ - //-------------------------------------------------------------------- + // -------------------------------------------------------------------- project.clearLogs = function (projectName, cb) { - projectController.find({ - userId : userConfig.data.userId - }, - function (err, projects) { - if (err) { - err = error.handleApiError(err, 'GET_PROJECT_LOGS', cb); - if (err.length > 0) { - return cb(err); - } - } - if (projects.length === 0) { - modulus.io.error('You currently have no projects. You can create one with "project create".'); - return cb(); + ProjectController.find({ + userId: UserConfig.data.userId + }, function (err, projects) { + if (err) { + err = Errors.handleApiError(err, 'GET_PROJECT_LOGS', cb); + if (err.length > 0) { + return cb(err); } - project.chooseProjectPrompt(projects, projectName, function (err, result) { - if (err) { - return cb(err); - } - - if (!result) { - return cb('You must select a project.'); - } + } + if (projects.length === 0) { + Modulus.io.error('You currently have no projects. You can create one with "project create".'); + return cb(); + } + project.chooseProjectPrompt( + projects, projectName, function (err, result) { + if (err) { + return cb(err); + } - if (result.status !== 'RUNNING'){ - return cb('Your project is not running. Please start your project to clear logs.'); - } + if (!result) { + return cb('You must select a project.'); + } - projectController.clearLogs(result.id, function (err) { - if (!err){ - modulus.io.success('Logs successfully cleared.'); - } else { - modulus.io.error('Failed to clear logs.'); + if (result.status !== 'RUNNING') { + return cb('Your project is not running. Please start your project to clear logs.'); } - cb(err); + + ProjectController.clearLogs(result.id, function (err) { + if (err) { + Modulus.io.error('Failed to clear logs.'); + } + + Modulus.io.success('Logs successfully cleared.'); + cb(err); + }); }); - }); - } - ); + }); }; /** Description - Streams logs for a specific project * @param {string} projectName - name of the project to retrieve logs from. * @param {function} cb - Callback invoked with stream data **/ -//-------------------------------------------------------------------- -project.streamLogs = function (projectName, selectedServo, cb){ - projectController.find({ - userId : userConfig.data.userId - }, +// -------------------------------------------------------------------- +project.streamLogs = function (projectName, selectedServo, cb) { + ProjectController.find({ + userId: UserConfig.data.userId + }, function (err, projects) { if (err) { - err = error.handleApiError(err, 'GET_PROJECT_LOGS', cb); + err = Errors.handleApiError(err, 'GET_PROJECT_LOGS', cb); if (err.length > 0) { return cb(err); } } if (projects.length === 0) { - modulus.io.error('You currently have no projects. You can create one with "project create".'); + Modulus.io.error('You currently have no projects. You can create one with "project create".'); return cb(); } - project.chooseProjectPrompt(projects, projectName, function (err, result) { - if (err) { - return cb(err); - } - - if (!result) { - return cb('You must select a project.'); - } + project.chooseProjectPrompt( + projects, projectName, function (err, result) { + var selectedProject, selectedServos, go; + if (err) { + return cb(err); + } - if (result.status !== 'RUNNING'){ - return cb('Your project is not running. Please start your project to stream logs.'); - } + if (!result) { + return cb('You must select a project.'); + } - var selectedProject = result; - var selectedServos = selectedProject.pus[0]; + if (result.status !== 'RUNNING') { + return cb('Your project is not running. Please start your project to stream logs.'); + } - var go = function () { - projectController.streamLogs(selectedProject.id, selectedServos, function () { - modulus.io.error('Disconnected from stream.'); - }); - }; + selectedProject = result; + selectedServos = selectedProject.pus[0]; - if (selectedProject.pus.length === 1) { - return go(); - } + go = function () { + ProjectController.streamLogs( + selectedProject.id, selectedServos, function () { + Modulus.io.error('Disconnected from stream.'); + }); + }; - if (selectedServo) { - if (selectedServo === 0) { - selectedServos = selectedProject.pus; + if (selectedProject.pus.length === 1) { + return go(); } - else { - selectedServo--; - if (!selectedProject.pus[selectedServo]) { - return error.handleApiError({ code: 'INVALID_SERVO_SELECTED' }, 'CHOOSE_SERVO_PROMPT', cb); + + if (selectedServo) { + if (selectedServo === 0) { + selectedServos = selectedProject.pus; + } else { + selectedServo--; + if (!selectedProject.pus[selectedServo]) { + return Errors.handleApiError( + { code: 'INVALID_SERVO_SELECTED' }, 'CHOOSE_SERVO_PROMPT', cb + ); + } + selectedServos = selectedProject.pus[selectedServo]; } - selectedServos = selectedProject.pus[selectedServo]; + return go(); } - return go(); - } - project.chooseServoPrompt(selectedProject, true, function (err, servos) { - if (err) { - return cb(err); - } + project.chooseServoPrompt( + selectedProject, true, function (err, servos) { + if (err) { + return cb(err); + } - selectedServos = servos; - return go(); + selectedServos = servos; + return go(); + }); }); - }); } ); }; /** - * Figures out the format of the scale options provided by the user. Valid formats are: + * Figures out the format of the scale options provided by the user. + * Valid formats are: * $ modulus project scale # * $ modulus project scale aws.us-east-1a=# joyent.us-east-1=#, etc. * @param {Array} instances The instances to convert to scale options. * @returns {Array} scaleOptions ready for API call. Null if invalid. */ project.getScaleOptions = function (instances) { + var num, idx, instance, dotIdx, equalIdx, iaas, region, count, result = []; if (!instances || instances.length === 0) { return null; } // Length is one, user could have specified a single number. if (instances.length === 1) { - var num = parseInt(instances[0], 10); + num = parseInt(instances[0], 10); // User specified a single number. We're done. if (!isNaN(num)) { @@ -868,21 +895,20 @@ project.getScaleOptions = function (instances) { } } - var result = []; // Each instance is an iaas.region combo. Break it apart. - for(var idx = 0; idx < instances.length; idx++) { - var instance = instances[idx]; - var dotIdx = instance.indexOf('.'); - var equalIdx = instance.indexOf('='); + for (idx = 0; idx < instances.length; ++idx) { + instance = instances[idx]; + dotIdx = instance.indexOf('.'); + equalIdx = instance.indexOf('='); // There's no dot or equals. Invalid format. if (dotIdx < 0 || equalIdx < 0) { return null; } - var iaas = instance.substring(0, dotIdx); - var region = instance.substring(dotIdx + 1, equalIdx); - var count = parseInt(instance.substr(equalIdx + 1), 10); + iaas = instance.substring(0, dotIdx); + region = instance.substring(dotIdx + 1, equalIdx); + count = parseInt(instance.substr(equalIdx + 1), 10); // Count is not a number. Invalid format. if (isNaN(count)) { @@ -899,195 +925,212 @@ project.getScaleOptions = function (instances) { return result; }; -//-------------------------------------------------------------------- +// -------------------------------------------------------------------- project.scale = function (instances, projectName, cb) { - instances = project.getScaleOptions(instances); if (!instances) { - modulus.io.error('Please specify the number of servos.'); - modulus.help.printUsage('scale'); + Modulus.io.error('Please specify the number of servos.'); + Modulus.help.printUsage('scale'); return cb(); } - projectController.find({ - userId : userConfig.data.userId - }, + ProjectController.find( + { userId: UserConfig.data.userId }, function (err, projects) { if (err) { - err = error.handleApiError(err, 'SCALE_PROJECT', cb); + err = Errors.handleApiError(err, 'SCALE_PROJECT', cb); if (err.length > 0) { return cb(err); } } if (projects.length === 0) { - modulus.io.error('You currently have no projects. You can create one with "project create".'); + Modulus.io.error('You currently have no projects. You can create one with "project create".'); return cb(); } - project.chooseProjectPrompt(projects, projectName, function (err, result) { - if (err) { - return cb(err); - } + project.chooseProjectPrompt( + projects, projectName, function (err, result) { + if (err) { + return cb(err); + } - if (!result) { - return cb('You must select a project.'); - } + if (!result) { + return cb('You must select a project.'); + } - projectController.scale( - result.id, - instances, - result.status.toLowerCase() === 'running', - function (err) { - if (!err) { - modulus.io.success('Project successfully scaled.'); - } - cb(err); - }); - }); + ProjectController.scale( + result.id, + instances, + result.status.toLowerCase() === 'running', + function (err) { + if (!err) { + Modulus.io.success('Project successfully scaled.'); + } + cb(err); + }); + }); }); }; -//-------------------------------------------------------------------- -project.runApp = function(projectName, nodeEnv, cb) { - console.log(arguments); - async.waterfall([ - function getUserProjects (fn) { - projectController.find({ userId: userConfig.data.userId }, function (err, projects) { - if (err) return error.handleApiError(err, 'GET_PROJECTS', fn); - if (projects.length === 0) return error.handleApiError({ code: 'PROJECTS_NOT_FOUND' }, 'GET_PROJECTS', fn); +// -------------------------------------------------------------------- +project.runApp = function (projectName, nodeEnv, cb) { + Async.waterfall([ + function getUserProjects(fn) { + ProjectController.find( + { userId: UserConfig.data.userId }, function (err, projects) { + if (err) return Errors.handleApiError(err, 'GET_PROJECTS', fn); + if (projects.length === 0) { + return Errors.handleApiError( + { code: 'PROJECTS_NOT_FOUND' }, 'GET_PROJECTS', fn + ); + } - fn(null, projects); - }); + fn(null, projects); + }); }, - function promptForProject (projects, fn) { + function promptForProject(projects, fn) { if (projectName && projectInArray(projects, projectName) === -1) { - return error.handleApiError({ code: 'NO_MATCHING_NAME' }, 'CHOOSE_PROJECT_PROMPT', cb); + return Errors.handleApiError( + { code: 'NO_MATCHING_NAME' }, 'CHOOSE_PROJECT_PROMPT', cb + ); } - project.chooseProjectPrompt(projects, projectName, function(err, selectedProject) { - if (err) return error.handlePromptError(err, fn); - - fn(null, selectedProject); - }); + project.chooseProjectPrompt( + projects, projectName, function (err, selectedProject) { + if (err) return Errors.handlePromptError(err, fn); + fn(null, selectedProject); + }); }, - function getProjectEnvVars (project, fn) { - if (!project) return fn('You must select a project.'); + function getProjectEnvVars(projectObject, fn) { + if (!projectObject) return fn('You must select a project.'); fn(null, project.envVars); }, - function buildStartCommand (envVars, fn) { - project.getMainFile(function(err, file) { + function buildStartCommand(envVars, fn) { + project.getMainFile(function (err, file) { if (err) return fn(err); nodeEnv = nodeEnv || 'development'; - project._createStartCommand(envVars, nodeEnv, file, function(err, command) { - if (err) return fn(err); - fn(null, command); - }); + project._createStartCommand( + envVars, nodeEnv, file, function (err, command) { + if (err) return fn(err); + fn(null, command); + }); }); }, - function startApp (command, fn) { - modulus.io.print('Starting application'); - var program = proc.exec(command); + function startApp(command, fn) { + var program = Proc.exec(command); + Modulus.io.print('Starting application'); - if (!program.killed) modulus.io.success('Application started successfully.'); + if (!program.killed) { + Modulus.io.success('Application started successfully.'); + } - program.stdout.on('data', function(data) { - modulus.io.print(data); + program.stdout.on('data', function (data) { + Modulus.io.print(data); }); - program.stderr.on('data', function(data) { - modulus.io.warning(data); + program.stderr.on('data', function (data) { + Modulus.io.warning(data); }); } - ], cb); + ], cb); }; -//------------------------------------------------------------------------------------------------- -project._createStartCommand = function(envVars, nodeEnv, mainFile, cb) { - var command = ''; +// ---------------------------------------------------------------------------- +project._createStartCommand = function (envVars, nodeEnv, mainFile, cb) { + var i, command = ''; mainFile = mainFile.replace(/'/g, ''); - for (var v = 0; v < envVars.length; v++) { - if (envVars[v].name === 'NODE_ENV') { - command = command.concat(util.format(' %s=%s', envVars[v].name, 'development')); - } else { - command = command.concat(util.format(' %s=%s', envVars[v].name, envVars[v].value)); + for (i = 0; i < envVars.length; ++i) { + if (envVars[i].name === 'NODE_ENV') { + command = command.concat( + Util.format(' %s=%s', envVars[i].name, 'development') + ); } + + command = command.concat( + Util.format(' %s=%s', envVars[i].name, envVars[i].value) + ); } - command = command.concat(util.format(' node %s', mainFile)); + command = command.concat(Util.format(' node %s', mainFile)); cb(null, command); }; -//------------------------------------------------------------------------------------------------- -project.getMainFile = function(cb) { +// ---------------------------------------------------------------------------- +project.getMainFile = function (cb) { // Check for "main" and set `mainFile` to the result. - var mainFile; - metaPath = findFileSync(project.dir || process.cwd(), 'package.json', ['.git', 'node_modules']); + var meta, mainFile, metaPath; + metaPath = FindFileSync( + project.dir || process.cwd(), 'package.json', ['.git', 'node_modules'] + ); + if (metaPath) { - var meta = null; + meta = null; try { - meta = JSON.parse(fs.readFileSync(metaPath), 'utf8'); - } catch (e) {} + meta = JSON.parse(FS.readFileSync(metaPath), 'utf8'); + } catch (e) { + // FIXME: handle e + } if (meta && meta['main'] && meta['main'] !== '') { mainFile = meta['main']; - modulus.io.print(util.format('Main file found in package.json: %s', mainFile)); - cb(null, mainFile); - } else { - cb('Main file not specified in package.json.'); + Modulus.io.print( + Util.format('Main file found in package.json: %s', mainFile) + ); + + return cb(null, mainFile); } + + return cb('Main file not specified in package.json.'); } }; -//------------------------------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- project._createProjectPrompt = function (cb) { - modulus.io.prompt.get([{ - name : 'name', - description : 'Enter a project name:', - maxLength : 50, - required : true + Modulus.io.prompt.get([{ + name: 'name', + description: 'Enter a project name:', + maxLength: 50, + required: true }], function (err, results) { - if (err) { - return error.handlePromptError(err, cb); - } + if (err) return Errors.handlePromptError(err, cb); cb(null, results.name); }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- /** * Displays a prompt for choosing a servo. * - * @param {Object} project The project object. + * @param {Object} projectObject The project object. * @param {Boolean} multi toggle allow multi servo selction * @param {Function} cb */ -//----------------------------------------------------------------------------- -project.chooseServoPrompt = function (project, multi, cb) { - if (project.pus.length === 0) { +// ---------------------------------------------------------------------------- +project.chooseServoPrompt = function (projectObject, multi, cb) { + var msg, promptOptions, table = []; + if (projectObject.pus.length === 0) { return cb(null, null); } - if (project.pus.length === 1) { - return cb(null, project.pus[0]); + if (projectObject.pus.length === 1) { + return cb(null, projectObject.pus[0]); } - modulus.io.print('Please choose which servo to use:'.input); + Modulus.io.print('Please choose which servo to use:'.input); if (multi) { - modulus.io.print(' 0' + ') '.input + 'All'); + Modulus.io.print(' 0' + ') '.input + 'All'); } - var table = []; - - project.pus.forEach(function (pu, i) { + projectObject.pus.forEach(function (pu, i) { var servoName = 'Servo: '.input; if (pu.host) { - servoName += util.format( + servoName += Util.format( '%s (%s.%s),', pu.id, pu.host.iaas, @@ -1103,48 +1146,50 @@ project.chooseServoPrompt = function (project, multi, cb) { ]); }); - modulus.io.print(createTable(table)); + Modulus.io.print(CreateTable(table)); - var promptOptions = { - name : 'servo', - description : 'Servo Number?', - warning : 'Servo number has to be between 1 and ' + project.pus.length, - minimum : 1, - maximum : project.pus.length, - type : 'number', - required : true + promptOptions = { + name: 'servo', + description: 'Servo Number?', + warning: 'Servo number has to be between 1 and ' + projectObject.pus.length, + minimum: 1, + maximum: projectObject.pus.length, + type: 'number', + required: true }; if (multi) { - promptOptions.warning = 'Servo number has to be between 0 and ' + project.pus.length; + msg = 'Servo number has to be between 0 and ' + projectObject.pus.length; + promptOptions.warning = msg; promptOptions.minimum = 0; } - modulus.io.prompt.get(promptOptions, function (err, answer) { + Modulus.io.prompt.get(promptOptions, function (err, answer) { if (err) { - return error.handlePromptError(err, cb); + return Errors.handlePromptError(err, cb); } - if (answer.servo === 0) { - cb(null, project.pus); - } else { - cb(null, project.pus[answer.servo - 1]); - } + if (answer.servo === 0) return cb(null, projectObject.pus); + return cb(null, projectObject.pus[answer.servo - 1]); }); }; -//----------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- /** * Displays a prompt for choosing projects. * @param {Array} projects Array of user's projects. * @param {String} [projectName] Default selection. * @param {Function} cb */ -//------------------------------------------------------------------------------------------------- +// ---------------------------------------------------------------------------- project.chooseProjectPrompt = function (projects, projectName, cb) { - var projectIndex = -1, - metaPath = null, - foundPrint = 'Selecting %s\n'; + var i, index, msg, selectedProject; + var projectIndex = -1; + var metaPath = null; + var foundPrint = 'Selecting %s\n'; + var meta = null; + var table = []; + var projectsLength = projects.length; if (typeof projectName === 'function') { cb = projectName; @@ -1152,13 +1197,16 @@ project.chooseProjectPrompt = function (projects, projectName, cb) { } // Check for "mod-project-name" and set `projectName` to the result. - metaPath = findFileSync(project.dir || process.cwd(), 'package.json', ['.git', 'node_modules']); - if (metaPath && autoCmds.indexOf(project.cmd) >= 0) { - var meta = null; + metaPath = FindFileSync( + project.dir || process.cwd(), 'package.json', ['.git', 'node_modules'] + ); + if (metaPath && autoCmds.indexOf(project.cmd) >= 0) { try { - meta = JSON.parse(fs.readFileSync(metaPath), 'utf8'); - } catch (e) {} + meta = JSON.parse(FS.readFileSync(metaPath), 'utf8'); + } catch (e) { + // FIXME: handle e + } if (meta && meta['mod-project-name'] && !projectName) { // "mod-project-name" found in package, check for the project name @@ -1166,7 +1214,7 @@ project.chooseProjectPrompt = function (projects, projectName, cb) { projectIndex = projectInArray(projects, meta['mod-project-name']); if (projectIndex >= 0) { - modulus.io.print('Found mod-project-name \'' + meta['mod-project-name'] + '\' in package.json'); + Modulus.io.print('Found mod-project-name \'' + meta['mod-project-name'] + '\' in package.json'); projectName = projects[projectIndex].name; } } @@ -1178,35 +1226,41 @@ project.chooseProjectPrompt = function (projects, projectName, cb) { projectIndex = projectInArray(projects, projectName); if (projectIndex >= 0) { - modulus.io.print(util.format(foundPrint, projectName.data)); + Modulus.io.print(Util.format(foundPrint, projectName.data)); return cb(null, projects[projectIndex]); } // No match was found. Error out. - return error.handleApiError({ code: 'NO_MATCHING_NAME' }, 'CHOOSE_PROJECT_PROMPT', cb); + return Errors.handleApiError( + { code: 'NO_MATCHING_NAME' }, 'CHOOSE_PROJECT_PROMPT', cb + ); } if (projects.length === 1) { - var selectedProject = projects[0]; - modulus.io.prompt.get([{ - name : 'confirm', - description : 'Are you sure you want to use project ' + selectedProject.name.data + '?', - message : 'Acceptable response is "yes" or "no".', - pattern : /^[yntf]{1}/i, - default : 'yes' + msg = Util.format( + 'Are you sure you want to use project %s ?', selectedProject.name.data + ); + + selectedProject = projects[0]; + Modulus.io.prompt.get([{ + name: 'confirm', + description: msg, + message: 'Acceptable response is "yes" or "no".', + pattern: /^[yntf]{1}/i, + default: 'yes' }], function (err, result) { + var y, p; if (err) { - return error.handlePromptError(err, cb); + return Errors.handlePromptError(err, cb); } - var y = /^[yt]{1}/i.test(result.confirm); - var p = y ? selectedProject : null; + y = /^[yt]{1}/i.test(result.confirm); + p = y ? selectedProject : null; return cb(null, p); }); } else { - var table = []; - modulus.io.print('Please choose which project to use:'.input); - for(var i = 0, len = projects.length; i < len; i++) { - var index = i + 1; + Modulus.io.print('Please choose which project to use:'.input); + for (i = 0; i < projectsLength; ++i) { + index = i + 1; table.push([ (' ' + index.toString() + ')').main, projects[i].name.main, @@ -1216,23 +1270,27 @@ project.chooseProjectPrompt = function (projects, projectName, cb) { ]); } - modulus.io.print(createTable(table)); - modulus.io.prompt.get([{ - name : 'project', - description : 'Project Number?', - warning : 'Project number has to be between 1 and ' + projects.length, - required : true, - type : 'number', - minimum : 1, - maximum : projects.length + Modulus.io.print(CreateTable(table)); + Modulus.io.prompt.get([{ + name: 'project', + description: 'Project Number?', + warning: 'Project number has to be between 1 and ' + projects.length, + required: true, + type: 'number', + minimum: 1, + maximum: projects.length }], function (err, result) { if (err) { - return error.handlePromptError(err, cb); + return Errors.handlePromptError(err, cb); } - modulus.io.print(util.format(foundPrint, projects[result.project - 1].name.data)); + Modulus.io.print( + Util.format(foundPrint, projects[result.project - 1].name.data) + ); + return cb(null, projects[result.project - 1]); }); } }; module.exports = project; +/* eslint-enable no-sync, no-underscore-dangle */ diff --git a/lib/commands/servo.js b/lib/commands/servo.js index 598f376..1ba2308 100644 --- a/lib/commands/servo.js +++ b/lib/commands/servo.js @@ -20,15 +20,14 @@ * THE SOFTWARE. * */ -var createTable = require('text-table'); +const CreateTable = require('text-table'); -var modulus = require('../modulus'); -var projectCommand = require('./project'); -var projectController = require('../controllers/project'); -var servoController = require('../controllers/servo'); - -var userConfig = require('../common/api').userConfig; -var error = require('../common/error'); +const Modulus = require('../modulus'); +const ProjectCommand = require('./project'); +const ProjectController = require('../controllers/project'); +const ServoController = require('../controllers/servo'); +const UserConfig = require('../common/api').userConfig; +const Errors = require('../common/error'); var servo = {}; @@ -38,27 +37,30 @@ servo.list = function (projectName, cb) { projectName = null; } - projectController.find({ - userId : userConfig.data.userId - }, + ProjectController.find({ + userId: UserConfig.data.userId + }, function (err, projects) { + var listProjects; if (err) { - err = error.handleApiError(err, 'GET_PROJECTS', cb); + err = Errors.handleApiError(err, 'GET_PROJECTS', cb); if (err.length > 0) return cb(err); } if (projects.length === 0) { - modulus.io.error('You currently have no projects. One can be created using the create command.'); + Modulus.io.error('You currently have no projects. One can be created using the create command.'); return cb(); } - var listProjects = function (projects, cb) { + listProjects = function (allProjects, callback) { var table = []; var filtered = []; var count = 0; - projects.forEach(function (project) { - table.push([' ' + project.name.data + (' (' + project.status+ ')').main]); + allProjects.forEach(function (project) { + table.push( + [' ' + project.name.data + (' (' + project.status + ')').main] + ); if (project.status === 'RUNNING') { project.pus.forEach(function (pu) { @@ -70,14 +72,16 @@ servo.list = function (projectName, cb) { } }); - modulus.io.print(createTable(table)); - cb(err, filtered); + Modulus.io.print(CreateTable(table)); + callback(err, filtered); }; if (projectName) { - projectCommand.chooseProjectPrompt(projects, projectName, function (err, selected) { - return listProjects([selected], cb); - }); + ProjectCommand.chooseProjectPrompt( + projects, projectName, function (err, selected) { + if (err) return Errors.handlePromptError(err, cb); + return listProjects([selected], cb); + }); } else { return listProjects(projects, cb); } @@ -85,40 +89,46 @@ servo.list = function (projectName, cb) { }; servo.restart = function (servoId, cb) { - function restartServo(servoId, cb) { - servoController.restart(servoId, function (err) { + function restartServo(restartServoId, callback) { + ServoController.restart(restartServoId, function (err) { if (err) { - err = error.handleApiError(err, 'RESTART_SERVO', cb); + err = Errors.handleApiError(err, 'RESTART_SERVO', callback); if (err.length > 0) return cb(err); } - if (!err) modulus.io.success(servoId + ' restarted.'); + if (!err) Modulus.io.success(servoId + ' restarted.'); - cb(err); + callback(err); }); } if (servoId) { - servoController.find(servoId, function (err, servo) { - if (err || !servo) return cb('Servo not found. Please specify a valid servo ID.'); + ServoController.find(servoId, function (err, servoItem) { + if (err || !servoItem) { + return cb('Servo not found. Please specify a valid servo ID.'); + } }); return restartServo(servoId, cb); } servo.list(function (err, filtered) { - var promptOptions = { - name : 'servo', - description : 'Servo Number?', - warning : 'Servo number has to be between 1 and ' + filtered.length, - minimum : 1, - maximum : filtered.length, - type : 'number', - required : true + var promptOptions; + + if (err) return Errors.handlePromptError(err, cb); + + promptOptions = { + name: 'servo', + description: 'Servo Number?', + warning: 'Servo number has to be between 1 and ' + filtered.length, + minimum: 1, + maximum: filtered.length, + type: 'number', + required: true }; - modulus.io.prompt.get(promptOptions, function (err, answer) { - if (err) return error.handlePromptError(err, cb); + Modulus.io.prompt.get(promptOptions, function (err, answer) { + if (err) return Errors.handlePromptError(err, cb); return restartServo(filtered[answer.servo - 1], cb); }); diff --git a/lib/commands/status.js b/lib/commands/status.js index 01601f8..17c38e7 100644 --- a/lib/commands/status.js +++ b/lib/commands/status.js @@ -21,23 +21,23 @@ * */ -var request = require('request'); -var createTable = require('text-table'); +const Request = require('request'); +const CreateTable = require('text-table'); -var modulus = require('../modulus'); -var url = 'http://yzskf90qzqff.statuspage.io/api/v2/summary.json'; +const Modulus = require('../modulus'); +const URL = 'http://yzskf90qzqff.statuspage.io/api/v2/summary.json'; var Status = {}; Status.get = function (callback) { - request.get({ - url: url, + Request.get({ + url: URL, json: true }, function (err, response, body) { + var table = []; if (err) return callback(err); - var table = []; body.components.forEach(function (component) { if (component.status === 'operational') { table.push([ @@ -52,13 +52,13 @@ Status.get = function (callback) { } }); - modulus.io.print('--------------------------------------------------'); - modulus.io.print('Current Status'.grey); - modulus.io.print('--------------------------------------------------'); - modulus.io.print(createTable(table)); - modulus.io.print('--------------------------------------------------'); - modulus.io.print('View full details at ' + 'http://status.modulus.io'.blue); - modulus.io.print('--------------------------------------------------'); + Modulus.io.print('--------------------------------------------------'); + Modulus.io.print('Current Status'.grey); + Modulus.io.print('--------------------------------------------------'); + Modulus.io.print(CreateTable(table)); + Modulus.io.print('--------------------------------------------------'); + Modulus.io.print('View full details at ' + 'http://status.modulus.io'.blue); + Modulus.io.print('--------------------------------------------------'); callback(); }); }; diff --git a/lib/commands/user.js b/lib/commands/user.js index 9cab67e..8a6500e 100755 --- a/lib/commands/user.js +++ b/lib/commands/user.js @@ -21,207 +21,200 @@ * */ -var modulus = require('../modulus'), - userConfig = require('../common/api').userConfig, - userController = require('../controllers/user'), - error = require('../common/error'), - util = require('util'); +const Modulus = require('../modulus'); +const UserConfig = require('../common/api').userConfig; +const UserController = require('../controllers/user'); +const Errors = require('../common/error'); +const Util = require('util'); -var user = {}; +var _signupPrompt, user = {};// eslint-disable-line no-underscore-dangle +var print = Modulus.io.print; -user.authenticate = function(username, password, loginProvided, passwordProvided, cb) { - userController.authenticate( +user.authenticate = function (username, password, loginProvided, passwordProvided, cb) { + UserController.authenticate( username, password, - function(err, u) { - if(err) { - err = error.handleApiError(err, 'LOGIN', cb); + function (err, u) { + var login = null; + var udata = null; + if (err) { + err = Errors.handleApiError(err, 'LOGIN', cb); if (err.length > 0) { - modulus.io.error(err); - - if(loginProvided && passwordProvided) { - return; - } else if(loginProvided) { - return user.login(username, null, false, cb); - } else if(passwordProvided) { - return user.login(null, password, false, cb); - } else { - return user.login(null, null, false, cb); + Modulus.io.error(err); + + if (loginProvided) login = user.login(username, null, false, cb); + if (passwordProvided) login = user.login(null, password, false, cb); + if (!loginProvided && !passwordProvided) { + login = user.login(null, null, false, cb); } + + return login; } } - userConfig.load(); - var udata = null; + UserConfig.load(); - if (userConfig.data) { + if (UserConfig.data) { // Don't overwrite existing data. - udata = util._extend(userConfig.data, { + udata = Util._extend(UserConfig.data, {// eslint-disable-line no-underscore-dangle username: u.username, - userId : u.id, - apiKey : u.authToken + userId: u.id, + apiKey: u.authToken }); } else { udata = { username: u.username, - userId : u.id, - apiKey : u.authToken + userId: u.id, + apiKey: u.authToken }; } - userConfig.save(udata); - modulus.io.success('Signed in as user ' + u.username.data); + UserConfig.save(udata); + Modulus.io.success('Signed in as user ' + u.username.data); return cb(); - }); + }); }; -user.authenticateGithub = function(username, password, loginProvided, passwordProvided, cb) { - userController.authenticateGithub( +user.authenticateGithub = function (username, password, loginProvided, passwordProvided, cb) { + UserController.authenticateGithub( username, password, - function(err, u) { - if(err) { - err = error.handleApiError(err, 'LOGIN', cb); - if(err.length > 0) { - modulus.io.error(err); - - if(loginProvided && passwordProvided) { - return; - } else if(loginProvided) { - return user.login(username, null, true, cb); - } else if(passwordProvided) { - return user.login(null, password, true, cb); - } else { - return user.login(null, null, true, cb); + function (err, u) { + var udata, login = null; + if (err) { + err = Errors.handleApiError(err, 'LOGIN', cb); + if (err.length > 0) { + Modulus.io.error(err); + + if (loginProvided) login = user.login(username, null, true, cb); + if (passwordProvided) login = user.login(null, password, true, cb); + if (!loginProvided && !passwordProvided) { + login = user.login(null, null, true, cb); } + + return login; } } - var udata = { + udata = { username: u.username, - userId : u.id, - apiKey : u.authToken + userId: u.id, + apiKey: u.authToken }; - userConfig.save(udata); - modulus.io.success('Signed in as user ' + u.username.data); + UserConfig.save(udata); + Modulus.io.success('Signed in as user ' + u.username.data); return cb(); - }); + }); }; -user.isAuthenticated = function(callback) { - userController.initAuthToken(function(err, result) { - if(err) { - modulus.io.error('Invalid MODULUS_TOKEN value.'); +user.isAuthenticated = function (callback) { + UserController.initAuthToken(function (err, result) { + if (err) { + Modulus.io.error('Invalid MODULUS_TOKEN value.'); return callback(); } - if(!result) { - userConfig.load(); + if (!result) { + UserConfig.load(); } - if(userConfig.data && userConfig.data.userId) { - modulus.io.print('You are logged in as ' + userConfig.data.username.magenta); + if (UserConfig.data && UserConfig.data.userId) { + print('You are logged in as ' + UserConfig.data.username.magenta); return callback(null, true); } return callback(null, false); }); }; -user.signup = function(cb) { - modulus.io.print('In order to sign up we a few pieces of information.'); +user.signup = function (cb) { + print('In order to sign up we a few pieces of information.'); _signupPrompt(cb); }; -var _signupPrompt = function(cb) { - modulus.io.prompt.get([{ - name: 'username', - description: 'Choose a username:', - message: 'Username is required and can not be longer than 50 chars.', - maxLength : 50, - pattern: /^[a-zA-Z0-9()<>\[\]:,;@\"!#$%&'*+\-\/=?\^_`{}|~?\.]+$/, - conform : function(value) { - // TODO: check with api if username exists - return true; - }, - required: true - }, { - name: 'jobTitle', - description: 'Enter your job title (optional):', - required: false - }, { - name: 'company', - description: 'Enter your company name (optional):', - required: false - }, { - name: 'email', - description: 'Enter a valid email:', - message: 'Email must be valid.', - format: 'email', - required: true - }, { - name: 'password', - description: 'Enter a password:', - required: true, - hidden: true - }, { - name: 'passwordConfirm', - description: 'Confirm your password:', - required: true, - hidden: true - }], function (err, result) { - if(err) { - return error.handlePromptError(err, cb); - } - - if(result.password !== result.passwordConfirm) { - modulus.io.error('Passwords much match.'); - return _signupPrompt(cb); - } +_signupPrompt = function (cb) { // eslint-disable-line no-underscore-dangle + Modulus.io.prompt.get([{ + name: 'username', + description: 'Choose a username:', + message: 'Username is required and can not be longer than 50 chars.', + maxLength: 50, + pattern: /^[a-zA-Z0-9()<>\[\]:,;@\"!#$%&'*+\-\/=?\^_`{}|~?\.]+$/, + conform: function (value) { + // TODO: check with api if username exists + return true; + }, + required: true + }, { + name: 'jobTitle', + description: 'Enter your job title (optional):', + required: false + }, { + name: 'company', + description: 'Enter your company name (optional):', + required: false + }, { + name: 'email', + description: 'Enter a valid email:', + message: 'Email must be valid.', + format: 'email', + required: true + }, { + name: 'password', + description: 'Enter a password:', + required: true, + hidden: true + }, { + name: 'passwordConfirm', + description: 'Confirm your password:', + required: true, + hidden: true + }], function (err, result) { + if (err) return Errors.handlePromptError(err, cb); + if (result.password !== result.passwordConfirm) { + Modulus.io.error('Passwords much match.'); + return _signupPrompt(cb); + } // Create user - userController.create( - result.username, - result.email, - result.jobTitle, - result.company, - result.password, - function(err, u) { - if(err) { - err = error.handleApiError(err, 'SIGNUP', cb); - if(err.length > 0) { - modulus.io.error(err); - return _signupPrompt(cb); - } + UserController.create( + result.username, + result.email, + result.jobTitle, + result.company, + result.password, + function (err, u) { + if (err) { + err = Errors.handleApiError(err, 'SIGNUP', cb); + if (err.length > 0) { + Modulus.io.error(err); + return _signupPrompt(cb); } + } - modulus.io.success('User ' + result.username.data + ' has been created successfully.'); - modulus.io.print('You should receive an email at ' + result.email.data + ' with more information.'); - user.authenticate(result.username, result.password, false, false, cb); + Modulus.io.success('User ' + result.username.data + ' has been created successfully.'); + print('You should receive an email at ' + result.email.data + ' with more information.'); + user.authenticate(result.username, result.password, false, false, cb); }); }); }; -user.login = function(username, password, github, cb) { - var login = username, - loginProvided = true, - pass = password, - passProvided = true, - prompt = [], - authFunction = github ? user.authenticateGithub : user.authenticate; +user.login = function (username, password, github, cb) { + var login = username; + var loginProvided = true; + var pass = password; + var passProvided = true; + var prompt = []; + var authFunction = github ? user.authenticateGithub : user.authenticate; - if(typeof login !== 'string' || login.length < 1) { + if (typeof login !== 'string' || login.length < 1) { prompt.push({ name: 'login', description: 'Enter your username or email:', required: true }); - if(github) { - prompt[0].description = 'Enter your GitHub username or email:'; - } - - login = undefined; + if (github) prompt[0].description = 'Enter your GitHub username or email:'; + login = null; loginProvided = false; } - if(typeof pass !== 'string' || pass.length < 1) { + if (typeof pass !== 'string' || pass.length < 1) { prompt.push({ name: 'password', description: 'Enter your password:', @@ -229,107 +222,94 @@ user.login = function(username, password, github, cb) { required: true }); - pass = undefined; + pass = null; passProvided = false; } - if(prompt.length > 0) { - modulus.io.prompt.get(prompt, function (err, result) { - if(err) { - return error.handlePromptError(err, cb); - } - authFunction.call(user, login || result.login, pass || result.password, loginProvided, passProvided, cb); + if (prompt.length > 0) { + Modulus.io.prompt.get(prompt, function (err, result) { + if (err) return Errors.handlePromptError(err, cb); + authFunction.call(user, login || result.login, pass || result.password, loginProvided, passProvided, cb); }); - } - else { + } else { authFunction.call(user, login, password, loginProvided, passProvided, cb); } }; -user.logout = function(cb) { - userConfig.clearSession(); - modulus.io.success('You have signed out of ' + 'Modulus'.data); +user.logout = function (cb) { + UserConfig.clearSession(); + Modulus.io.success('You have signed out of ' + 'Modulus'.data); return cb(); }; -user.resetPassword = function(cb) { - modulus.io.prompt.get([{ +user.resetPassword = function (cb) { + Modulus.io.prompt.get([{ name: 'email', description: 'Enter email for account:', format: 'email' - }], function(err, result) { - if(err) { - return error.handlePromptError(err, cb); + }], function (err, result) { + if (err) { + return Errors.handlePromptError(err, cb); } - userController.resetPassword( + + UserController.resetPassword( result.email, - function(err, res) { - if(err) { - err = error.handleApiError(err, 'UNLOCK', cb); - if(err.length > 0) { - modulus.io.error(err); + function (err, res) { + if (err) { + err = Errors.handleApiError(err, 'UNLOCK', cb); + if (err.length > 0) { + Modulus.io.error(err); return user.unlock(cb); } } else { - modulus.io.print('You should receive an email at ' + result.email.data + ' with instructions on resetting your password.'); + print('You should receive an email at ' + result.email.data + ' with instructions on resetting your password.'); return cb(); } - }); + }); }); }; -user.createToken = function(cb) { - userController.createToken(function(err, result) { - - if(err) { - err = error.handleApiError(err, 'CREATE_TOKEN', cb); - - if(err.length > 0) { - return cb(err); - } +user.createToken = function (cb) { + UserController.createToken(function (err, result) { + if (err) { + err = Errors.handleApiError(err, 'CREATE_TOKEN', cb); + if (err.length > 0) return cb(err); } - modulus.io.success('Token: ' + result); + + Modulus.io.success('Token: ' + result); cb(); }); }; -user.listTokens = function(cb) { - userController.getTokens(function(err, result) { - - if(err) { - err = error.handleApiError(err, 'LIST_TOKENS', cb); - - if(err.length > 0) { - return cb(err); - } +user.listTokens = function (cb) { + UserController.getTokens(function (err, result) { + if (err) { + err = Errors.handleApiError(err, 'LIST_TOKENS', cb); + if (err.length > 0) return cb(err); } - if(result.length === 0) { - modulus.io.print('You have no tokens. Tokens can be created using the "modulus token create" command.'); + if (result.length === 0) { + print('You have no tokens. Tokens can be created using the "modulus token create" command.'); return cb(); } - modulus.io.print('Current tokens:'.input); - result.forEach(function(token) { - modulus.io.print(token.key); + print('Current tokens:'.input); + result.forEach(function (token) { + print(token.key); }); cb(); }); }; -user.removeToken = function(token, cb) { - userController.removeToken(token, function(err, result) { - - if(err) { - err = error.handleApiError(err, 'REMOVE_TOKEN', cb); - - if(err.length > 0) { - return cb(err); - } +user.removeToken = function (token, cb) { + UserController.removeToken(token, function (err, result) { + if (err) { + err = Errors.handleApiError(err, 'REMOVE_TOKEN', cb); + if (err.length > 0) return cb(err); } - modulus.io.success('Token successfully removed.'); + Modulus.io.success('Token successfully removed.'); cb(); }); }; diff --git a/package.json b/package.json index bc8a3df..4d99ab5 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,6 @@ } ], "dependencies": { - "@modulus/logger": "~1.2.0", "async": "0.1.x", "colors": "0.6.x", "commander-plus": "0.0.x",