UNPKG

tyr-cli

Version:

A command line interface for hammer-io.

229 lines (190 loc) 13.5 kB
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.enableTravis = exports.waitForProjectToExist = exports.waitForSync = exports.generateTravisCIFile = undefined; /** * Generates the TravisCI file. * @param configs the configurations object * @param projectPath the path to the newly created project * @returns {Promise<void>} */let generateTravisCIFile = exports.generateTravisCIFile = (() => {var _ref = _asyncToGenerator( function* (configs, projectPath) { log.verbose('Travis Service - generateTravisCIFile()'); const path = `${projectPath}/.travis.yml`; // load in the base travis CI file. const travisCIFile = _jsYaml2.default.safeLoad(file.loadTemplate('./../../templates/travis/travis.yml')); // if the user has selected heroku for deployment, then generate the specific heroku instances if (configs.toolingConfigurations.deployment === 'Heroku') { log.verbose('Travis Service - generateTravisCIFIle() - generating TravisCI file for use with' + ' Docker/Heroku'); const docker = 'docker'; const dockerBuild = `docker build -t ${configs.projectConfigurations.herokuAppName} .`; const dockerPs = 'docker ps -a'; const afterSuccess = 'if [ "$TRAVIS_BRANCH" == "master" ]; then\n' + 'docker login -u="$HEROKU_USERNAME" -p="$HEROKU_PASSWORD" registry.heroku.com;\n' + `docker build -t registry.heroku.com/${configs.projectConfigurations.herokuAppName}/web .;\n` + `docker push registry.heroku.com/${configs.projectConfigurations.herokuAppName}/web;\n` + 'fi'; travisCIFile.services = [docker]; travisCIFile.before_install = [dockerBuild, dockerPs]; travisCIFile.after_success = [afterSuccess]; } file.writeFile(path, _jsYaml2.default.safeDump(travisCIFile)); log.info(`Successfully generated file: ${path}`); });return function generateTravisCIFile(_x, _x2) {return _ref.apply(this, arguments);};})(); /** * Waits for the user's travis account to be done syncing. * Often times, the travis account can be found syncing. * We need to wait for the account to not be syncing and then return the user information. * This will hit the /users/{user.id} endpoint at travis every * 2 seconds until the user is not syncing anymore. * * @param travisAccessToken the access token to retrieve user information * @param account the account trying to get user informatin for * @param isPrivate is the project private or not * @returns {Promise} */let waitForSync = exports.waitForSync = (() => {var _ref2 = _asyncToGenerator( function* (travisAccessToken, account, isPrivate) { log.verbose('Travis Service - waitForSync()'); log.warn('Waiting for TravisCI to sync account...'); return new Promise((() => {var _ref3 = _asyncToGenerator(function* (resolve) { setTimeout(_asyncToGenerator(function* () { let user = yield travisClient.getUserInformation(travisAccessToken, account, isPrivate); if (user.user.is_syncing) { user = yield waitForSync(travisAccessToken, account, isPrivate); } resolve(user); }), 2000); });return function (_x6) {return _ref3.apply(this, arguments);};})()); });return function waitForSync(_x3, _x4, _x5) {return _ref2.apply(this, arguments);};})(); /** * Waits for the project that is being created to exist on TravisCI * @param projectName the project name * @param username the username * @param travisAccessToken the travis access token * @param account the account * @param isPrivate is the project private or not * @returns {Promise<void>} */let waitForProjectToExist = exports.waitForProjectToExist = (() => {var _ref5 = _asyncToGenerator( function* ( projectName, username, travisAccessToken, account, isPrivate) { const repos = yield travisClient.getRepos(username, travisAccessToken, isPrivate); let isFound = false; repos.repositories.forEach(function (repo) { if (repo.name === projectName) { isFound = true; } }); if (!isFound) { yield waitForSync(travisAccessToken, account, isPrivate); yield travisClient.syncTravisWithGithub(travisAccessToken, isPrivate); yield waitForProjectToExist(projectName, username, travisAccessToken, account, isPrivate); } });return function waitForProjectToExist(_x7, _x8, _x9, _x10, _x11) {return _ref5.apply(this, arguments);};})(); /** * Enables TravisCI for the project * @param configs the configuration object * @returns {Promise<{}>} */let enableTravis = exports.enableTravis = (() => {var _ref6 = _asyncToGenerator( function* (configs) { log.verbose('Travis Service - enableTravis()'); let githubToken = { token: configs.credentials.github.token }; const username = configs.credentials.github.username; const password = configs.credentials.github.password; const projectName = configs.projectConfigurations.projectName; const isPrivate = configs.projectConfigurations.isPrivateProject; const envVariables = []; if (typeof configs.toolingConfigurations.deployment !== 'undefined' && configs.toolingConfigurations.deployment.toLowerCase() === 'heroku') { envVariables.push({ name: 'HEROKU_USERNAME', value: configs.credentials.heroku.email }); envVariables.push({ name: 'HEROKU_PASSWORD', value: configs.credentials.heroku.apiKey }); } // get the github token if it does not exist if (!githubToken.token) { try { githubToken = yield githubClient.requestGitHubToken(username, password); } catch (error) { throw new Error(`Failed to enable travis on ${username}/${projectName} because we were unable to get a token from GitHub.`); } } // Use the GitHub token to get a Travis token let travisAccessToken = {}; try { travisAccessToken = yield travisClient.requestTravisToken(githubToken.token, isPrivate); } catch (error) { throw new Error(`Failed to enable travis on ${username}/${projectName} because we were unable to get a token from TravisCI.`); } let response = {}; let account = {}; try { // get the accounts for the user response = yield travisClient.getUserAccount(travisAccessToken, isPrivate); // a user may have many accounts, we should find the account associated with the github username for (let i = 0; i < response.accounts.length; i += 1) { if (response.accounts[i].login.toLowerCase() === username.toLowerCase()) { account = response.accounts[i]; break; } } if (account === {}) { // Should be located above, but in the case that it doesn't throw a new error throw new Error(); } } catch (error) { throw new Error(`Failed to enable travis on ${username}/${projectName} because we were unable to get account information from TravisCI.`); } // Wait for the user's account to be done syncing.... yield waitForSync(travisAccessToken, account, isPrivate); // Sync Travis with GitHub, which must be done before activating the repository try { yield travisClient.syncTravisWithGithub(travisAccessToken, isPrivate); } catch (error) { throw new Error(`Failed to enable travis on ${username}/${projectName} because we were unable to sync TravisCI with GitHub.`); } yield waitForProjectToExist( configs.projectConfigurations.projectName, username, travisAccessToken, account, isPrivate); // Get the project repository ID, and then use that ID to activate Travis for the project let repoId = ''; try { repoId = yield travisClient.getRepositoryId( travisAccessToken, username, projectName, isPrivate); yield travisClient.activateTravisHook(repoId, travisAccessToken, isPrivate); } catch (error) { throw new Error(`Failed to enable travis on ${username}/${projectName} because we were unable to activate TravisCI.`); } // Add environment variables try { if (envVariables && envVariables.length !== 0) { for (const env of envVariables) {// eslint-disable-line no-restricted-syntax yield travisClient.setEnvironmentVariable( // eslint-disable-line no-await-in-loop travisAccessToken, repoId, env, isPrivate); } } } catch (error) { throw new Error(`Failed to enable travis on ${username}/${projectName} because we were unable to set environment variables.`); } if (githubToken.url) { // if the token was not passed in through the configs, delete it. yield githubClient.deleteGitHubToken(githubToken.url, username, password); } log.info(`Successfully enabled TravisCI on ${username}/${projectName}`); return travisAccessToken; });return function enableTravis(_x12) {return _ref6.apply(this, arguments);};})();var _jsYaml = require('js-yaml');var _jsYaml2 = _interopRequireDefault(_jsYaml);var _githubClient = require('../clients/github-client');var githubClient = _interopRequireWildcard(_githubClient);var _travisClient = require('../clients/travis-client');var travisClient = _interopRequireWildcard(_travisClient);var _file = require('../utils/file');var file = _interopRequireWildcard(_file);var _winston = require('../utils/winston');function _interopRequireWildcard(obj) {if (obj && obj.__esModule) {return obj;} else {var newObj = {};if (obj != null) {for (var key in obj) {if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];}}newObj.default = obj;return newObj;}}function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};} /* eslint-disable import/prefer-default-export,prefer-destructuring */const log = (0, _winston.getActiveLogger)();