From 5111dc7b3c67dae6ecda609de2cc3aed8607c855 Mon Sep 17 00:00:00 2001 From: ryanp Date: Fri, 21 Aug 2015 11:16:20 -0500 Subject: [PATCH] remove un-needed jsonfile package. Promise and path fixups --- lib/commands/custom.js | 58 +++++++---- lib/commands/install.js | 207 ++++++++++++++++++++++------------------ lib/commands/new.js | 79 +++++++-------- lib/commands/tag.js | 59 +++++++----- lib/jaws-error/index.js | 1 + package.json | 1 - 6 files changed, 227 insertions(+), 178 deletions(-) diff --git a/lib/commands/custom.js b/lib/commands/custom.js index 05999b739..0c58a2ffa 100644 --- a/lib/commands/custom.js +++ b/lib/commands/custom.js @@ -5,31 +5,57 @@ * - Run a custom command from jaws-commands.js */ -// Defaults -var Promise = require('bluebird'), - fs = Promise.promisifyAll(require('fs')); +var JawsError = require('../jaws-error'), + Promise = require('bluebird'), + path = require('path'), + fs = require('fs'); + +Promise.promisifyAll([ + fs, +]); module.exports = function(JAWS) { JAWS.custom = function(command) { + return new Promise(function(resolve, reject) { + // Validate + if (!command || !command['0']) { + reject(new JawsError( + 'Sorry, this command was not recognized or is malformed', + JawsError.errorCodes.UNKNOWN + )); + } - // Validate - if (!command || !command['0']) return console.log('JAWS Error: Sorry, this command was not recognized or is malformed'); + command = command['0'].trim(); - command = command['0'].trim(); + // Find Custom Command + var cmdsInRoot = path.join(JAWS._meta.projectRootPath, 'jaws-commands.js'), + cmdsInCWD = path.join(JAWS._meta.cwd, 'jaws-commands.js'); - // Find Custom Command - try { - if (fs.existsSync(JAWS._meta.projectRootPath + '/jaws-commands.js')) command = require(JAWS._meta.projectRootPath + '/jaws-commands.js')[command]; - if (fs.existsSync(JAWS._meta.cwd + '/jaws-commands.js')) command = require(JAWS._meta.projectRootPath + '/jaws-commands.js')[command]; - } catch (e) { - return console.log('JAWS Error: Could not find this custom command'); - } + try { + if (fs.existsSync(cmdsInRoot)) { + command = require(cmdsInRoot)[command]; + } else if (fs.existsSync(cmdsInCWD)) { + command = require(cmdsInCWD)[command]; + } + } catch (e) { + reject(new JawsError( + 'Could not find this custom command', + JawsError.errorCodes.UNKNOWN + )); + } - if (!typeof command !== 'function') return console.log('JAWS Error: Sorry, this command could not be found in the current directory or your project\'s root folder.'); + if (!typeof command !== 'function') { + reject(new JawsError( + 'Sorry, this command could not be found in the current directory or your project\'s root folder.', + JawsError.errorCodes.UNKNOWN + )); + } - // Run - return command(); + // Run + command(); + resolve(); + }); }; }; diff --git a/lib/commands/install.js b/lib/commands/install.js index 9123d8627..0e88422fe 100644 --- a/lib/commands/install.js +++ b/lib/commands/install.js @@ -5,119 +5,138 @@ * - Fetches an jaws-module from another github repo and installs it locally */ -// Defaults -var Promise = require('bluebird'), - fs = Promise.promisifyAll(require('fs')), +var JawsError = require('../jaws-error'), + Promise = require('bluebird'), + path = require('path'), + fs = require('fs'), del = require('del'), wrench = require('wrench'), shortid = require('shortid'), Download = require('Download'); +Promise.promisifyAll([ + fs, +]); + module.exports = function(JAWS) { JAWS.install = function(url) { + return new Promise(function(resolve, reject) { + if (!JAWS._meta.projectRootPath) { + reject(new JawsError( + 'Could\'nt find your JAWS Project. Are you sure you are in the right directory?', + JawsError.errorCodes.UNKNOWN + )); + } - // Check if not in current directory - if (!JAWS._meta.projectRootPath) return console.log('JAWS Error: Couldn\'t find your JAWS project. Are you sure ' + - 'you\'re in the right folder?'); + // Inform + console.log('Downloading and installing module...'); - // Inform - console.log('JAWS: Downloading and installing module...'); + // Prepare URL + var repo = {}; + url = url.replace('https://', '').replace('http://', '').replace('www.', '').split('/'); //TODO: why not regex? + repo.owner = url[1]; + repo.repo = url[2]; + repo.branch = 'master'; - // Prepare URL - var repo = {}; - url = url.replace('https://', '').replace('http://', '').replace('www.', '').split('/'); - repo.owner = url[1]; - repo.repo = url[2]; - repo.branch = 'master'; + if (~repo.repo.indexOf('#')) { + url[2].split('#'); + repo.repo = url[2].split('#')[0]; + repo.branch = url[2].split('#')[1]; + } - if (~repo.repo.indexOf('#')) { - url[2].split('#'); - repo.repo = url[2].split('#')[0]; - repo.branch = url[2].split('#')[1]; - } + // Throw error if invalid url + if (url[0] !== 'github.com' || !repo.owner || !repo.repo) { + reject(new JawsError( + 'Must be a github url in this format: https://github.com/jaws-stack/JAWS', + JawsError.errorCodes.UNKNOWN + )); + } - // Throw error if invalid url - if (url[0] !== 'github.com' || !repo.owner || !repo.repo) return console.log('JAWS Error: Must be a github url ' + - 'in this format: https://github.com/jaws-stack/JAWS'); + // Prepare Download url + var downloadUrl = 'https://github.com/' + repo.owner + '/' + repo.repo + '/archive/' + repo.branch + '.zip'; - // Prepare Download url - var downloadUrl = 'https://github.com/' + repo.owner + '/' + repo.repo + '/archive/' + repo.branch + '.zip'; + // Make a temporary directory for the module + var tempDir = 'temp-' + shortid.generate(); + var tempDirPath = path.join(JAWS._meta.projectRootPath, tempDir); - // Make a temporary directory for the module - var tempDir = 'temp-' + shortid.generate(); - var tempDirPath = JAWS._meta.projectRootPath + '/' + tempDir; + // Download module + new Download({ + timeout: 30000, + extract: true, + strip: 1, + mode: '755', + }) + .get(downloadUrl) + .dest(tempDirPath) + .run(function(error) { - // Download module - new Download({ - timeout: 30000, - extract: true, - strip: 1, - mode: '755', - }) - .get(downloadUrl) - .dest(tempDirPath) - .run(function(error) { - - if (error) { - console.log('JAWS Error: Module Download and installation failed.'); - return console.log(error); - } - - // Fetch module's jaws.json - try { - var jawsJson = require(tempDirPath + '/jaws.json'); - } catch (e) { - - // Remove module and report if malformed - return del([tempDirPath], { - force: true, - }, function(error) { - if (error) console.log(error); - return console.log(e); - }); - - } - - // Handle according to module profile - if (['lambda', 'lambdaGroup'].indexOf(jawsJson.profile) > -1) { - - // If folder exists, create unique module folder name - if (fs.existsSync(JAWS._meta.projectRootPath + '/back/' + jawsJson.name)) { - for (var i = 2; i < 500; i++) { - if (!fs.existsSync(JAWS._meta.projectRootPath + '/back/' + jawsJson.name + '-' + i)) { - jawsJson.name = jawsJson.name + '-' + i; - break; - } - } + if (error) { + console.error('Module Download and installation failed.'); + reject(error); } - // Copy folders into new module folder - wrench.copyDirSyncRecursive(tempDirPath, JAWS._meta.projectRootPath + '/back/' + jawsJson.name, { - forceDelete: false, // Whether to overwrite existing directory or not - excludeHiddenUnix: false // Whether to copy hidden Unix files or not (preceding .) - // filter: regexpOrFunction // A filter to match files against; if matches, do nothing (exclude). + // Fetch module's jaws.json + try { + var jawsJson = require(tempDirPath + '/jaws.json'); + } catch (e) { + + // Remove module and report if malformed + return del([tempDirPath], { + force: true, + }, function(error) { + if (error) { + console.error(error); + } + + reject(e); + }); + + } + + var backPath = path.join(JAWS._meta.projectRootPath, 'back', jawsJson.name); + + // Handle according to module profile + if (['lambda', 'lambdaGroup'].indexOf(jawsJson.profile) > -1) { + + // If folder exists, create unique module folder name + if (fs.existsSync(backPath)) { + for (var i = 2; i < 500; i++) { + if (!fs.existsSync(backPath + '-' + i)) { + jawsJson.name = jawsJson.name + '-' + i; + break; + } + } + } + + // Copy folders into new module folder + wrench.copyDirSyncRecursive(tempDirPath, backPath, { + forceDelete: false, // Whether to overwrite existing directory or not + excludeHiddenUnix: false, // Whether to copy hidden Unix files or not (preceding .) + // filter: regexpOrFunction // A filter to match files against; if matches, do nothing (exclude). + }); + + } else if (jawsJson.profile === 'front') { + //TODO:implement + } else if (jawsJson.profile === 'project') { + //TODO: implement + } else { + reject(new JawsError('This module has an unknown profile', JawsError.errorCodes.UNKNOWN)); + } + + // Delete temp directory + del([tempDirPath], { + force: true, + }, function(error) { + + if (error) { + reject(error); + } + + console.log('Module successfully installed'); + resolve(); }); - - } else if (jawsJson.profile === 'front') { - //TODO:implement - } else if (jawsJson.profile === 'project') { - //TODO: implement - } else { - return console.log('JAWS Error: This module has an unknown profile'); - } - - // Delete temp directory - del([tempDirPath], { - force: true, - }, function(error) { - - if (error) return console.log(error); - - // Conclude - return console.log('JAWS: Module successfully installed'); - }); - }); + }); }; }; diff --git a/lib/commands/new.js b/lib/commands/new.js index f59a24650..0e5423b64 100644 --- a/lib/commands/new.js +++ b/lib/commands/new.js @@ -7,7 +7,8 @@ */ // Defaults -var Promise = require('bluebird'), +var JawsError = require('../jaws-error'), + Promise = require('bluebird'), fs = require('fs'), path = require('path'), os = require('os'), @@ -15,7 +16,6 @@ var Promise = require('bluebird'), AWS = require('aws-sdk'), inquirer = require('inquirer'), chalk = require('chalk'), - jsonfile = Promise.promisifyAll(require('jsonfile')), shortid = require('shortid'); Promise.promisifyAll([ @@ -69,13 +69,18 @@ function _generateAscii() { module.exports = function(JAWS) { + /** + * @returns Promise + */ JAWS.new = function() { // Epic greeting chalk.yellow(_generateAscii()); var iam = new AWS.IAM(); - var project = {}, + var project = { + awsProfile: 'default', + }, requireAdminCreds = true; var getOrSetAdminCreds = new Promise(function(resolve, reject) { @@ -88,6 +93,13 @@ module.exports = function(JAWS) { },], function(answers) { project.awsProfile = answers.awsCliProfile || 'default'; project.creds = new AWS.SharedIniFileCredentials({profile: project.awsProfile}); + + if (!project.creds || !project.creds.accessKeyId) { + reject(new JawsError( + 'Could not find AWS admin profile ' + project.awsProfile, + JawsError.errorCodes.MISSING_AWS_CREDS_PROFILE)); + } + requireAdminCreds = false; }); } @@ -170,12 +182,12 @@ module.exports = function(JAWS) { }); }); - // Do user prompts - getOrSetAdminCreds + return getOrSetAdminCreds .then(function() { return userPrompts; }) - .then(function() { + .then(function() { //Make skeleton dir structure and initial files + var adminEnv = 'ADMIN_AWS_PROFILE=' + project.awsProfile; // Set project root path. Append unique id if name is in use if (fs.existsSync(JAWS._meta.cwd + '/' + project.name)) { @@ -188,38 +200,24 @@ module.exports = function(JAWS) { JAWS._meta.projectRootPath = project.name.replace(/\s/g, '-'); } - // Create project root directory - return fs.mkdirAsync(JAWS._meta.projectRootPath); + var cfTemplate = require('../templates/jaws-cf'); + cfTemplate.Parameters.aaProjectName.Default = project.name; + cfTemplate.Parameters.aaProjectName.AllowedValues = [project.name]; + cfTemplate.Parameters.aaStage = project.stages[0]; + cfTemplate.Parameters.aaDataModelPrefix.Default = project.project.stages[0]; //to simplify bootstrap use same stage + cfTemplate.Parameters.aaDataModelPrefix.AllowedValues = [project.project.stages[0]]; + cfTemplate.Parameters.aaNotficationEmail.Default = project.notificationEmail; + return Promise.all([ + fs.mkdirAsync(JAWS._meta.projectRootPath), + fs.mkdirAsync(path.join(JAWS._meta.projectRootPath, 'back')), + fs.mkdirAsync(path.join(JAWS._meta.projectRootPath, 'front')), + fs.mkdirAsync(path.join(JAWS._meta.projectRootPath, 'tests')), + fs.writeFileAsync(path.join(JAWS._meta.projectRootPath, 'admin.env'), adminEnv), + fs.writeFileAsync(JAWS._meta.projectRootPath + '/jaws-cf.json', cfTemplate), + ]); }).then(function() { - // Create project/back - return fs.mkdirAsync(JAWS._meta.projectRootPath + '/back'); - - }).then(function() { - - // Create project/front - return fs.mkdirAsync(JAWS._meta.projectRootPath + '/front'); - - }).then(function() { - - // Create project/front - return fs.mkdirAsync(JAWS._meta.projectRootPath + '/tests'); - - }).then(function() { - - // Create admin.env - var adminEnv = 'ADMIN_AWS_PROFILE=' + project.awsProfile; - return fs.writeFile(path.join(JAWS._meta.projectRootPath, 'admin.env'), adminEnv); - - }) - .catch(function(e) { - - console.error(e); - - }) - .finally(function() { - // Configure AWS SDK //AWS.config.update({ // accessKeyId: project.awsAdminKeyId, @@ -227,13 +225,6 @@ module.exports = function(JAWS) { //}); AWS.config.update(project.creds); - var cfTemplate = require('../templates/jaws-cf'); - cfTemplate.Parameters.aaProjectName.Default = project.name; - cfTemplate.Parameters.aaProjectName.AllowedValues = [project.name]; - cfTemplate.Parameters.aaStage = project.stages[0]; - cfTemplate.Parameters.aaDataModelPrefix.Default = project.project.stages[0]; //to simplify bootstrap use same stage - cfTemplate.Parameters.aaDataModelPrefix.AllowedValues = [project.project.stages[0]]; - cfTemplate.Parameters.aaNotficationEmail.Default = project.notificationEmail; // Create IAM Roles and their policies for each stage async.eachSeries(project.stages, function(stage, stageCallback) { @@ -271,7 +262,7 @@ module.exports = function(JAWS) { if (err) return console.log(err, err.stack); // Inform - console.log('JAWS: Stage created successfully! (' + stage + ')'); + console.log('Stage created successfully! (' + stage + ')'); // Callback return stageCallback(); @@ -294,8 +285,6 @@ module.exports = function(JAWS) { jsonfile.spaces = 2; jsonfile.writeFileSync(JAWS._meta.projectRootPath + '/jaws.json', jawsJson); - // Create CloudFormation file - jsonfile.writeFileSync(JAWS._meta.projectRootPath + '/jaws-cf.json', cfTemplate); // Create Swagger file jsonfile.writeFileSync( diff --git a/lib/commands/tag.js b/lib/commands/tag.js index 2de516c15..04480051e 100644 --- a/lib/commands/tag.js +++ b/lib/commands/tag.js @@ -5,40 +5,55 @@ * - Tags a lambda function with "deploy:true" */ -// Defaults -var Promise = require('bluebird'), - fs = Promise.promisifyAll(require('fs')), - jsonfile = Promise.promisifyAll(require('jsonfile')); +var JawsError = require('../jaws-error'), + Promise = require('bluebird'), + path = require('path'), + fs = require('fs'); + +Promise.promisifyAll([ + fs, +]); module.exports = function(JAWS) { JAWS.tag = function() { + return new Promise(function(resolve, reject) { + var jawsJsonPath = path.join(process.cwd(), 'jaws.json'); - // Check if cwd is a lambda function - if (!fs.existsSync(process.cwd() + '/jaws.json')) return console.log('JAWS Error: Could\'nt find a lambda function. Are you sure you are in a lambda function\'s directory?'); + if (!fs.existsSync(jawsJsonPath)) { // Check if cwd is a lambda function + reject(new JawsError( + 'Could\'nt find a lambda function. Are you sure you are in a lambda function\'s directory?', + JawsError.errorCodes.UNKNOWN + )); + } - var jawsJson = require(process.cwd() + '/jaws.json'); + var jawsJson = require(jawsJsonPath); - // Check if jaws.json has correct profile - if (['lambda', 'lambdaGroup'].indexOf(jawsJson.profile) === -1) return console.log('JAWS Error: This jaws-module is not a lambda function. Make sure it\'s profile is set to lambda or lambdaGroup'); + // Check if jaws.json has correct profile + if (-1 === ['lambda', 'lambdaGroup'].indexOf(jawsJson.profile)) { + reject(new JawsError( + 'This jaws-module is not a lambda function. Make sure it\'s profile is set to lambda or lambdaGroup', + JawsError.errorCodes.UNKNOWN + )); + } - // Handle profile type 'lambda' - if (jawsJson.profile === 'lambda') { + // Handle profile type 'lambda' + if (jawsJson.profile === 'lambda') { - // Add deploy property - if (!jawsJson.deploy) jawsJson.deploy = 1; - jsonfile.spaces = 2; - jsonfile.writeFileSync(process.cwd() + '/jaws.json', jawsJson); + // Add deploy property + if (!jawsJson.deploy) jawsJson.deploy = 1; - } + fs.writeFileSync(path.join(process.cwd(), 'jaws.json', JSON.stringify(jawsJson, null, 2))); + } - // Handle profile type 'lambdaGroup' - if (jawsJson.profile === 'lambdaGroup') { + // Handle profile type 'lambdaGroup' + if (jawsJson.profile === 'lambdaGroup') { + //TODO: implement + } - } - - // Inform - return console.log('JAWS: Lambda tagged for deployment.'); + console.log('Lambda successfully tagged for deployment'); + resolve(); + }); }; }; diff --git a/lib/jaws-error/index.js b/lib/jaws-error/index.js index 9decafad5..a66bc54e7 100644 --- a/lib/jaws-error/index.js +++ b/lib/jaws-error/index.js @@ -24,4 +24,5 @@ module.exports = JawsError; module.exports.errorCodes = { UNKNOWN: 1, MISSING_HOMEDIR: 2, + MISSING_AWS_CREDS_PROFILE: 3, }; diff --git a/package.json b/package.json index 5ed90b89d..a741c1ad4 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,6 @@ "download": "^4.2.0", "inquirer": "^0.9.0", "js-yaml": "^3.3.1", - "jsonfile": "^2.2.1", "moment": "^2.10.6", "node-uuid": "^1.4.2", "node-zip": "^1.1.0",