UNPKG

@onboardbase/cli

Version:

[![Version](https://img.shields.io/npm/v/@onboardbase/cli.svg)](https://www.npmjs.com/package/@onboardbase/cli) [![Downloads/week](https://img.shields.io/npm/dw/@onboardbase/cli.svg)](https://www.npmjs.com/package/@onboardbase/cli) [![License](https://img

222 lines (221 loc) 11.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SetupCommandService = void 0; const inquirer = require("inquirer"); const fs_1 = require("fs"); const path_1 = require("path"); const utils_1 = require("../utils"); const chalk = require("chalk"); const jwt_decode_1 = require("jwt-decode"); const uploadSecretsActionTypes_enum_1 = require("../enums/uploadSecretsActionTypes.enum"); const common_1 = require("../common"); const access_manager_1 = require("./access-manager"); const config_1 = require("../config"); const types_1 = require("../common/types"); const auth_1 = require("./auth"); const Table = require("cli-table"); class SetupCommandService extends common_1.BaseService { constructor(configManager) { super(configManager); this.accessManager = new access_manager_1.AccessManager(configManager); } async _runLoginProcess() { console.log("Can't find any login information, running login process..."); return new auth_1.BaseAuthService(this.configManager).login({ flags: { overwrite: true, password: null, scope: process.cwd(), }, shouldCloseProcess: false, }); } async initialize({ args, flags }) { var _a, _b, _c, _d; let project = (_a = flags.project) !== null && _a !== void 0 ? _a : flags.project; let environment = (_b = flags.environment) !== null && _b !== void 0 ? _b : flags.environment; let startScript = flags["start-script"]; const cliToken = await this._getCliToken(); const authHandshakeResult = await this.accessManager.getAuthInfoFromDeviceToken(cliToken); const { team, teamRole, } = (0, jwt_decode_1.default)(authHandshakeResult.accessToken); const userHasAdminPriviledges = teamRole.name !== "Employee"; let environmentId = ""; if (!project || !environment) { console.log(chalk.greenBright("Fetching projects....")); let projects = await this.httpInstance.fetchProjects(authHandshakeResult.accessToken); // Only show projects the user have access to projects = projects.filter(({ member }) => member); if (Array.isArray(projects) && projects.length === 0) { console.log(chalk.green(`Sorry you don't have any project under the ${chalk.bold.greenBright(team.name)} team, please signin to Onboardbase and create a project.`)); process.exit(1); } // Filter the environment list to only display the ones the user have access to const modifiedProjects = projects.map((project) => Object.assign(project, { environments: { list: project.environments.list.filter(({ member }) => member), }, })); const projectInq = await inquirer.prompt([ { name: "project", type: "list", message: "Select a project", choices: projects.map(({ title }) => title), }, ]); project = projectInq.project; const envInq = await inquirer.prompt([ { name: "environment", type: "list", message: "Select an environment", choices: (_c = modifiedProjects .find(({ title }) => project === title)) === null || _c === void 0 ? void 0 : _c.environments.list.map(({ title }) => title), }, ]); environment = envInq.environment; const environmentData = (_d = projects .find(({ title }) => project === title)) === null || _d === void 0 ? void 0 : _d.environments.list.find(({ title }) => title === environment); environmentId = environmentData === null || environmentData === void 0 ? void 0 : environmentData.id; } if (!startScript) { const { startScriptCommand } = await inquirer.prompt([ { type: "input", message: "What command starts your project?", name: "startScriptCommand", }, ]); startScript = startScriptCommand; } this.configManager.setProject("setup.project", project); this.configManager.setProject("setup.environment", environment); this.configManager.setProject("setup.start_script", startScript); environmentId && this.setScopeConfig(`environment-id`, environmentId); const gitIgnoreFile = (0, path_1.join)(process.cwd(), ".gitignore"); if ((0, utils_1.isExist)(gitIgnoreFile)) { let gitIgnoreFileContent = (0, fs_1.readFileSync)(gitIgnoreFile, "utf8"); if (!gitIgnoreFileContent.includes(config_1.PROJECT_CONFIG_FILENAME)) { gitIgnoreFileContent += `\n${config_1.PROJECT_CONFIG_FILENAME}`; (0, fs_1.writeFileSync)(gitIgnoreFile, `${gitIgnoreFileContent}`); } console.log(chalk.greenBright(`${config_1.PROJECT_CONFIG_FILENAME} file added to .gitignore successfully`)); } if (userHasAdminPriviledges) { /** * Check if user has any .env file in their project directory * and ask if it should be synced to onboardbase and then deleted */ const projectDirectory = (0, fs_1.readdirSync)(process.cwd()); const pattern = RegExp("^.env+"); const envFiles = []; projectDirectory.map((file) => pattern.test(file) && envFiles.push(file)); if (envFiles.length > 0 && !flags.teammate) { console.log(chalk.greenBright("We noticed that you have an ENV file inside your project directory")); const { shouldSyncEnv } = await inquirer.prompt([ { type: "list", message: "Would you like to upload the env contents to onboardbase", name: "shouldSyncEnv", choices: ["Yes", "No"], default: "Yes", }, ]); if (shouldSyncEnv === "Yes") { if (envFiles.length === 1) { const { shouldDeleteEnvFileAfterSync } = await inquirer.prompt([ { type: "list", message: "Would you like to delete the ENV file after uploading to onboardbase ?", name: "shouldDeleteEnvFileAfterSync", choices: ["Yes", "No"], default: "No", }, ]); const envContent = (0, fs_1.readFileSync)((0, path_1.join)(process.cwd(), envFiles[0]), "utf8"); console.log(chalk.greenBright("Uploading ENV....")); await (0, utils_1.uploadSecretsToOnboardbase)(project, environment, (0, utils_1.parseEnvContentToObject)(envContent), cliToken, [], uploadSecretsActionTypes_enum_1.UploadSecretsActionTypes.CREATE); console.log(chalk.greenBright.bold("ENV Contents has been uploaded to Onboardbase successfully.")); if (shouldDeleteEnvFileAfterSync === "Yes") { (0, fs_1.unlinkSync)((0, path_1.join)(process.cwd(), envFiles[0])); console.log("ENV file has been deleted."); } } if (envFiles.length > 1) { // User has multiple envs console.log(chalk.greenBright("We noticed you have multiple ENV files in your project directory")); const { wouldLikeToSyncEnv } = await inquirer.prompt([ { type: "list", message: "Will you like to sync any of the ENV's to onboardbase", choices: ["Yes", "No"], default: "Yes", name: "wouldLikeToSyncEnv", }, ]); if (wouldLikeToSyncEnv === "Yes") { const { selectedEnvFile } = await inquirer.prompt([ { type: "list", message: "Please select the ENV file you would like to sync", choices: envFiles, name: "selectedEnvFile", }, ]); const { shouldDeleteEnvFileAfterSync } = await inquirer.prompt([ { type: "list", message: "Would you like to delete the ENV file after uploading to onboardbase ?", name: "shouldDeleteEnvFileAfterSync", choices: ["Yes", "No"], default: "No", }, ]); const envContent = (0, fs_1.readFileSync)((0, path_1.join)(process.cwd(), selectedEnvFile), "utf8"); console.log(chalk.greenBright("Uploading ENV....")); await (0, utils_1.uploadSecretsToOnboardbase)(project, environment, (0, utils_1.parseEnvContentToObject)(envContent), cliToken, [], uploadSecretsActionTypes_enum_1.UploadSecretsActionTypes.CREATE); console.log(chalk.greenBright.bold("ENV Contents has been uploaded to Onboardbase successfully.")); if (shouldDeleteEnvFileAfterSync === "Yes") { (0, fs_1.unlinkSync)((0, path_1.join)(process.cwd(), selectedEnvFile)); console.log("ENV file has been deleted."); } } } } } } const configTableData = { head: ["Project", "Environment", "Scope"], colWidths: [30, 30, 50], }; const configTable = new Table(configTableData); const directory = process.cwd().split("/"); // We need to start from one cos path has / at the beginning which will take the place of directory[0] const finalDirectory = `/${directory[1]}/${directory[2]}/.../${directory[directory.length - 1]}`; configTable.push([ project, environment, process.platform === "win32" ? process.cwd() : finalDirectory, ]); console.log(configTable.toString()); } async preInit() { try { this._getFromGlobalConfigOrThrow({ configPath: "token", envName: types_1.ENV_NAMES.TOKEN, }); } catch (_a) { await this._runLoginProcess(); } } async _getCliToken() { let cliToken = this._getFromGlobalConfigOrThrow({ configPath: "token", envName: types_1.ENV_NAMES.TOKEN, }); return cliToken; } } exports.SetupCommandService = SetupCommandService;