diff --git a/package.json b/package.json index 8a862e04b5..828b18c88d 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "build": "lerna run build", "test": "cross-env CI=true lerna run test --since origin/master -- --coverage", "create-plugin": "backstage-cli create-plugin", + "remove-plugin": "backstage-cli remove-plugin", "release": "if [ \"$(git symbolic-ref --short HEAD)\" = master ]; then echo \"don't try to release master\"; exit 1; else lerna version --no-push; fi", "lint": "cross-env CI=true lerna run lint --since origin/master --", "storybook": "yarn workspace storybook start" diff --git a/packages/cli/src/commands/remove-plugin/removePlugin.test.ts b/packages/cli/src/commands/remove-plugin/removePlugin.test.ts new file mode 100644 index 0000000000..5253fdf301 --- /dev/null +++ b/packages/cli/src/commands/remove-plugin/removePlugin.test.ts @@ -0,0 +1,47 @@ +// Test Suite for removePlugin command. + +import fse from 'fs-extra' +import path from 'path' +import {// removeExportStatementFromPlugins, + removePluginDependencyFromApp, + //removePluginDirectory, +} from './removePlugin' + +const rootDir = fse.realpathSync(process.cwd().replace('/cli', '')); + +// test remove export statement +describe('removePlugin', () => { + describe('Remove Plugin Dependencies', () => { + // Set up test + // Copy contents of package file for test + const packageFile = path.join(rootDir, 'app', 'package.json'); + const testFilePath = path.join(rootDir, 'app', 'test.json'); + const testPluginName = 'yarn-test-package'; + const testPluginPackage = `@spotify-backstage/plugin-${testPluginName}`; + + let packageFileContents = JSON.parse(fse.readFileSync(packageFile, 'utf8')); + packageFileContents.dependencies[testPluginPackage] = "0.1.0"; + + it('should remove plugin dependency from /packages/app/package.json', async () => { + fse.createFileSync(testFilePath); + fse.writeFileSync( + testFilePath, + `${JSON.stringify(packageFileContents, null, 2)}\n`, + 'utf8'); + console.log(JSON.parse(fse.readFileSync(testFilePath, 'utf8'))); + try { + await removePluginDependencyFromApp(testFilePath, testPluginName); + expect(JSON.parse(fse.readFileSync(testFilePath, 'utf8')).hasOwnProperty(testPluginPackage)).toBe(false); + } finally { + fse.removeSync(testFilePath); + } + }); + }); +}); + + +// test remove plugin dependency from app + +// remove plugin from directory + +// remove symlink from lerna scope \ No newline at end of file diff --git a/packages/cli/src/commands/remove-plugin/removePlugin.ts b/packages/cli/src/commands/remove-plugin/removePlugin.ts new file mode 100644 index 0000000000..86444ab640 --- /dev/null +++ b/packages/cli/src/commands/remove-plugin/removePlugin.ts @@ -0,0 +1,189 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import fse from 'fs-extra'; +import path from 'path'; +// import handlebars from 'handlebars'; +import chalk from 'chalk'; +import inquirer, { Answers, Question } from 'inquirer'; +// import recursive from 'recursive-readdir'; +// import { execSync } from 'child_process'; +// import { resolve as resolvePath } from 'path'; +import { realpathSync, /*existsSync*/ } from 'fs'; +// import os from 'os'; +import ora from 'ora'; + +const MARKER_SUCCESS = chalk.green(` ✔︎`); +const MARKER_FAILURE = chalk.red(` ✘`); + +export const checkExists = async (rootDir: string, pluginName: string) => { + const destination = path.join(rootDir, 'plugins', pluginName); + const spinner = ora({ + prefixText: `Checking plugin exists.`, + spinner: 'arc', + color: 'green', + }).start(); + try { + let pathExist = await fse.pathExists(destination); + if (pathExist) { + spinner.succeed(); + console.log(chalk.green(` Plugin ID ${chalk.cyan(pluginName)} exists at: ${destination.replace(`${rootDir}`, '')} ${MARKER_SUCCESS}`)); + } else { + throw new Error(chalk.red(` Plugin ${chalk.cyan(pluginName)} does not exist!`)); + } + } catch (e) { + spinner.fail(); + throw new Error(chalk.red(` There was an error removing plugin ${chalk.cyan(pluginName)}: ${e.message}`)); + } +} + +export const removePluginDirectory = async (destination: string, pluginName: string) => { + console.log(` Removing plugin files ${chalk.cyan(destination)}.`); + try { + await fse.remove(destination); + console.log(chalk.green(` Plugin files removed successfully. ${MARKER_SUCCESS}`)); + } catch (e) { + throw Error(` Could not remove Plugin\t${pluginName}. ${MARKER_FAILURE} \n Please try again. Error: ${e.message}`) + } +} + +export const removeSymLink = async (destination: string) => { + console.log(` Removing symbolic link if it exists at:\t${chalk.cyan(destination)}.`) + const symLinkExists = fse.pathExists(destination); + if (symLinkExists) { + try { + await fse.remove(destination); + console.log(chalk.green(` Symbolic link successfully removed. ${MARKER_SUCCESS}`)) + } catch (e) { + throw Error(` Could not remove symbolic link\t${destination}. ${MARKER_FAILURE} \n Please try again. Error: ${e.message}`) + } + + } +} + +export const removeExportStatementFromPlugins = async (pluginsFile: string, pluginName: string) => { + const pluginNameCapitalized = pluginName + .split('-') + .map(name => capitalize(name)) + .join(''); + + console.log(` Removing export statement from ${chalk.cyan(pluginsFile.replace(pluginsFile.split('/app', 1)[0], ''))}`); // remove long path + try { + let originalContent = await fse.readFile(pluginsFile, 'utf8'); + const contentAfterRemoval = originalContent + .split('\n') + .filter(Boolean) // get rid of empty lines + .filter(statement => { return !statement.includes(`${pluginNameCapitalized}`) }) // get rid of lines with pluginName + .sort() + .concat(['']) // newline at end of line + .join('\n'); + await fse.writeFile(pluginsFile, contentAfterRemoval, 'utf8'); + const finalContent = await fse.readFile(pluginsFile, 'utf8'); + if (finalContent === originalContent) + throw new Error(`File was not modified.`); + console.log(chalk.green(` Successfully removed export statement from /app/src/plugin.ts ${MARKER_SUCCESS}`)); + } catch (e) { + throw new Error(chalk.red(` There was an error removing export statement for plugin ${chalk.cyan(pluginNameCapitalized)} ${MARKER_FAILURE} ${e.message}`)); + } +}; + +export const removePluginDependencyFromApp = async ( + packageFile: string, + pluginName: string, +) => { + + const pluginPackage = `@spotify-backstage/plugin-${pluginName}`; + + console.log(` Removing plugin from app dependencies ${chalk.cyan(packageFile.replace(`${packageFile}/packages`, ''))}:`); + + try { + const packageFileContent = await fse.readFile(packageFile, 'utf-8'); + const packageFileContentJSON = JSON.parse(packageFileContent); + const dependencies = packageFileContentJSON.dependencies; + + if (!dependencies[pluginPackage]) { + throw new Error( + chalk.red(` Plugin ${chalk.cyan(pluginPackage)} does not exist in ${chalk.yellow(packageFile)}`), + ); + } + + delete dependencies[pluginPackage]; + await fse.writeFile( + packageFile, + `${JSON.stringify(packageFileContentJSON, null, 2)}\n`, + 'utf-8', + ); + + console.log(chalk.green(` Successfully removed plugin from app dependencies. ${MARKER_SUCCESS}`)); + } catch (e) { + throw new Error( + `${chalk.red(` Failed to remove plugin as dependency in app: ${chalk.cyan(packageFile)}:`)} ${e.message}`, + ); + } +} + +const capitalize = (str: string): string => + str.charAt(0).toUpperCase() + str.slice(1); + +const removePlugin = async () => { + const questions: Question[] = [ + { + type: 'input', + name: 'pluginName', + message: chalk.blue('Enter the ID of the plugin to be removed [required]'), + validate: (value: any) => { + if (!value) { + return chalk.red('Please enter an ID for the plugin'); + } else if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(value)) { + return chalk.red( + 'Plugin IDs must be kehbab-cased and contain only letters, digits and dashes.' + ); + } + return true; + }, + }, + ]; + + const answers: Answers = await inquirer.prompt(questions); + + const rootDir = realpathSync(process.cwd()); + const pluginName: string = answers.pluginName; + const packageFile = path.join(rootDir, 'packages', 'app', 'package.json'); + const pluginsFile = path.join(rootDir, 'packages', 'app', 'src', 'plugins.ts'); + const pluginDirectory = path.join(rootDir, 'plugins', pluginName); + const pluginScopedDirectory = path.join(rootDir, `node_modules/@spotify-backstage/plugin-${pluginName}`); + + console.log(pluginScopedDirectory); + try { + + await checkExists(rootDir, pluginName); + await removeExportStatementFromPlugins(pluginsFile, pluginName); + await removePluginDependencyFromApp(packageFile, pluginName); + await removePluginDirectory(pluginDirectory, pluginName); + await removeSymLink(pluginScopedDirectory); + + console.log(chalk.green(`Successfully removed plugin ${chalk.cyan(pluginName)} from app.`)); + + } catch (e) { + // If error, restore files + console.log(e); + throw new Error( + chalk.red(`Failed to remove plugin: ${chalk.cyan(pluginName)}: ${e.message}`), + ); + } + +}; + +export default removePlugin; \ No newline at end of file diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 997c05c18c..44e30fa2c8 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -18,6 +18,7 @@ import program from 'commander'; import chalk from 'chalk'; import fs from 'fs'; import createPluginCommand from './commands/create-plugin/createPlugin'; +import removePluginCommand from './commands/remove-plugin/removePlugin'; import watch from './commands/watch-deps'; import buildCache from './commands/build-cache'; import lintCommand from './commands/lint'; @@ -48,6 +49,11 @@ const main = (argv: string[]) => { .description('Creates a new plugin in the current repository') .action(actionHandler(createPluginCommand)); + program + .command('remove-plugin') + .description('Removes plugin in the current repository') + .action(actionHandler(removePluginCommand)); + program .command('plugin:build') .option('--watch', 'Enable watch mode')