diff --git a/packages/cli/src/commands/plugins/available.ts b/packages/cli/src/commands/plugins/available.ts index 7b87fced..71f77fde 100644 --- a/packages/cli/src/commands/plugins/available.ts +++ b/packages/cli/src/commands/plugins/available.ts @@ -44,6 +44,7 @@ export default class PluginsAvailable extends Command { cliux.Table.table(availablePlugins, { key: { header: 'PLUGIN (KEY)', minWidth: 20, get: row => (row.hidden ? clColor.dim : clColor).blueBright(row.name) }, description: { header: 'DESCRIPTION', get: row => (row.hidden ? clColor.dim(row.description) : row.description) }, + version: { header: 'VERSION', get: row => clColor.dim(row.version) }, }, { printLine: clUtil.log, }) @@ -62,25 +63,31 @@ type PluginRelease = { description: string; enabled: boolean; hidden?: boolean; - version?: string; + /** + * The versions of the plugin this CLI installs and updates: its major, as + * a range (^N). A new major of the plugin is never installed or updated to + * implicitly: the user asks for it (plugins:install --latest), + * or a CLI release raises the range here (a breaking change of the CLI). + */ + version: string; } const AvailablePlugins: PluginRelease[] = [ - { name: 'resources', plugin: '@commercelayer/cli-plugin-resources', description: 'CRUD operations on API resources', enabled: true }, - { name: 'seeder', plugin: '@commercelayer/cli-plugin-seeder', description: 'Organization data seeder', enabled: true }, - { name: 'imports', plugin: '@commercelayer/cli-plugin-imports', description: 'Organization imports manager', enabled: true }, - { name: 'webhooks', plugin: '@commercelayer/cli-plugin-webhooks', description: 'Organization webhooks analyzer', enabled: true }, - { name: 'orders', plugin: '@commercelayer/cli-plugin-orders', description: 'Organization orders management', enabled: true }, - { name: 'checkout', plugin: '@commercelayer/cli-plugin-checkout', description: 'Checkout URLs generation', enabled: true }, - { name: 'triggers', plugin: '@commercelayer/cli-plugin-triggers', description: 'Execute actions on resources', enabled: true }, - { name: 'token', plugin: '@commercelayer/cli-plugin-token', description: 'Manage Commerce Layer access tokens', enabled: true }, - { name: 'microstore', plugin: '@commercelayer/cli-plugin-microstore', description: 'Microstore URLs generation', enabled: true }, - { name: 'exports', plugin: '@commercelayer/cli-plugin-exports', description: 'Organization exports manager', enabled: true }, - { name: 'cleanups', plugin: '@commercelayer/cli-plugin-cleanups', description: 'Organization cleanups manager', enabled: true }, - { name: 'tags', plugin: '@commercelayer/cli-plugin-tags', description: 'Manage resources tags', enabled: true }, - { name: 'provisioning', plugin: '@commercelayer/cli-plugin-provisioning', description: 'Add support for Provisioning API', enabled: true }, - { name: 'links', plugin: '@commercelayer/cli-plugin-links', description: 'Manage links to resources', enabled: true }, - { name: 'metrics', plugin: '@commercelayer/cli-plugin-metrics', description: 'Add support for Metrics APIs', enabled: true } + { name: 'resources', plugin: '@commercelayer/cli-plugin-resources', description: 'CRUD operations on API resources', version: '^7', enabled: true }, + { name: 'seeder', plugin: '@commercelayer/cli-plugin-seeder', description: 'Organization data seeder', version: '^6', enabled: true }, + { name: 'imports', plugin: '@commercelayer/cli-plugin-imports', description: 'Organization imports manager', version: '^5', enabled: true }, + { name: 'webhooks', plugin: '@commercelayer/cli-plugin-webhooks', description: 'Organization webhooks analyzer', version: '^5', enabled: true }, + { name: 'orders', plugin: '@commercelayer/cli-plugin-orders', description: 'Organization orders management', version: '^6', enabled: true }, + { name: 'checkout', plugin: '@commercelayer/cli-plugin-checkout', description: 'Checkout URLs generation', version: '^6', enabled: true }, + { name: 'triggers', plugin: '@commercelayer/cli-plugin-triggers', description: 'Execute actions on resources', version: '^5', enabled: true }, + { name: 'token', plugin: '@commercelayer/cli-plugin-token', description: 'Manage Commerce Layer access tokens', version: '^9', enabled: true }, + { name: 'microstore', plugin: '@commercelayer/cli-plugin-microstore', description: 'Microstore URLs generation', version: '^4', enabled: true }, + { name: 'exports', plugin: '@commercelayer/cli-plugin-exports', description: 'Organization exports manager', version: '^5', enabled: true }, + { name: 'cleanups', plugin: '@commercelayer/cli-plugin-cleanups', description: 'Organization cleanups manager', version: '^4', enabled: true }, + { name: 'tags', plugin: '@commercelayer/cli-plugin-tags', description: 'Manage resources tags', version: '^3', enabled: true }, + { name: 'provisioning', plugin: '@commercelayer/cli-plugin-provisioning', description: 'Add support for Provisioning API', version: '^3', enabled: true }, + { name: 'links', plugin: '@commercelayer/cli-plugin-links', description: 'Manage links to resources', version: '^2', enabled: true }, + { name: 'metrics', plugin: '@commercelayer/cli-plugin-metrics', description: 'Add support for Metrics APIs', version: '^2', enabled: true } ] diff --git a/packages/cli/src/hooks/prerun/plugin.ts b/packages/cli/src/hooks/prerun/plugin.ts index 1491cf2e..2b87615c 100644 --- a/packages/cli/src/hooks/prerun/plugin.ts +++ b/packages/cli/src/hooks/prerun/plugin.ts @@ -1,8 +1,10 @@ +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' import { clColor, clOutput } from '@commercelayer/cli-core' import type { Hook, Interfaces } from '@oclif/core' import { Errors } from '@oclif/core' import inquirer from 'inquirer' -import { getAvailablePlugins, getInstalledPlugins, getPluginInfo, isPluginInstalled } from '../../commands/plugins/available' +import { getAvailablePlugins, getInstalledPlugins, getPluginInfo, isPluginInstalled, type PluginRelease } from '../../commands/plugins/available' const { CLIError } = Errors type Config = Interfaces.Config @@ -17,6 +19,9 @@ const hook: Hook<'prerun'> = async function (opts) { // Only plugins commands are affected by this hook if (!opts.Command.id.startsWith('plugins')) return + // Plugins installed by an older CLI, or with --latest, follow npm's latest: keep them on their major + if (opts.Command.id === 'plugins:update') pinInstalledPlugins(this.config) + if (['plugins:install', 'plugins:uninstall'].includes(opts.Command.id)) { @@ -30,6 +35,16 @@ const hook: Hook<'prerun'> = async function (opts) { opts.argv.splice(tgIndex, 2) } + // --latest: the latest version on npm (--tag latest), the explicit move to a new major + const ltIndex = opts.argv.indexOf('--latest') + if (ltIndex > -1) { + if (tgIndex > -1) this.error(`${clColor.cli.flag('--latest')} and ${clColor.cli.flag('--tag')} cannot be used together`) + if (command !== 'install') this.error(`${clColor.cli.flag('--latest')} is a flag of plugins:install only`) + tag = 'latest' + opts.argv.splice(ltIndex, 1) + } + const tagged = (tag !== undefined) + if (opts.argv.length === 0) { const arg = await promptPlugin(this.config, command) .catch((error: Error) => { this.error(error) }) @@ -42,6 +57,7 @@ const hook: Hook<'prerun'> = async function (opts) { let index = -1 let plugin: string = '' + let pluginInfo: PluginRelease | undefined let pluginArg: string = '' let testBuild: string | undefined @@ -62,7 +78,10 @@ const hook: Hook<'prerun'> = async function (opts) { } const p = getPluginInfo(pluginArg) if (p === undefined) this.error(`Unknown Commerce Layer CLI plugin: ${clColor.msg.error(a)}. Run '${clColor.italic(`${this.config.bin} plugins:available`)}' to get a list of all available plugins`) - else plugin = p.plugin + else { + plugin = p.plugin + pluginInfo = p + } return true @@ -74,18 +93,21 @@ const hook: Hook<'prerun'> = async function (opts) { if (found && plugin) { let errMsg: string = '' - if ((command === 'install') && isPluginInstalled(plugin, this.config)) errMsg = 'Commerce Layer CLI plugin already installed' + // With --latest or --tag an installed plugin is installed again: the explicit move to another version (e.g. its next major) + if ((command === 'install') && !tagged && isPluginInstalled(plugin, this.config)) errMsg = 'Commerce Layer CLI plugin already installed' else if ((command === 'uninstall') && !isPluginInstalled(plugin, this.config)) errMsg = 'Commerce Layer CLI plugin not installed' if (errMsg) { this.log(`\n${errMsg}: ${clColor.cli.plugin(pluginArg)}\n`) + if (command === 'install') this.log(`To install its latest version, a new major included, run '${clColor.italic(`${this.config.bin} plugins:install ${pluginArg} --latest`)}'\n`) throw new CLIError('HOOK_EXIT') } else this.log('') - // Set version - if (tgIndex > -1) plugin = `${plugin}@${tag}` + // Set version: the major of the plugin table unless the user asks for another (--latest, --tag) + if (tagged) plugin = `${plugin}@${tag}` + else if ((command === 'install') && pluginInfo) plugin = `${plugin}@${pluginInfo.version}` // Overwrite plugin short name whith its full name opts.argv[index] = plugin @@ -97,6 +119,40 @@ const hook: Hook<'prerun'> = async function (opts) { } +type PluginsManifest = { oclif?: { plugins?: Array<{ name: string; tag?: string; type?: string }> } } + +/** + * Pins the plugins of the plugin table that follow npm's latest (installed by + * an older CLI, or with --latest) to the major they have, so that + * plugins:update never moves them to a new major. Without a known installed + * version, to the range of the plugin table. Returns whether anything changed. + */ +const pinPlugins = (manifest: PluginsManifest, plugins: PluginRelease[], installed: Map): boolean => { + let changed = false + for (const entry of manifest.oclif?.plugins ?? []) { + const info = plugins.find(p => p.plugin === entry.name) + if (info && (entry.type === 'user') && ((entry.tag === undefined) || (entry.tag === 'latest'))) { + const major = installed.get(entry.name)?.split('.')[0] + entry.tag = major ? `^${major}` : info.version + changed = true + } + } + return changed +} + +/** pinPlugins on the user plugins of the CLI (package.json of its data folder, as oclif keeps it) */ +const pinInstalledPlugins = (config: Config): void => { + const file = join(config.dataDir, 'package.json') + const installed = new Map(config.getPluginsList().map(p => [p.name, p.version])) + try { + const manifest = JSON.parse(readFileSync(file, 'utf8')) as PluginsManifest + if (pinPlugins(manifest, getAvailablePlugins(), installed)) writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`) + } catch { + // No user plugins yet + } +} + + /** * The plugin a test build installs, when the argument is one: a pkg.pr.new * preview URL (preview.yml) or a local tarball (file:…/commercelayer-cli-plugin--.tgz, @@ -138,4 +194,4 @@ const promptPlugin = async (config: Config, command: string): Promise => export default hook -export { testBuildPlugin } +export { pinPlugins, testBuildPlugin } diff --git a/packages/cli/test/hooks/prerun/plugin.test.ts b/packages/cli/test/hooks/prerun/plugin.test.ts index c0df9ae4..f1c23736 100644 --- a/packages/cli/test/hooks/prerun/plugin.test.ts +++ b/packages/cli/test/hooks/prerun/plugin.test.ts @@ -1,5 +1,8 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' import { expect } from 'chai' -import { testBuildPlugin } from '../../../src/hooks/prerun/plugin' +import { getAvailablePlugins } from '../../../src/commands/plugins/available' +import { pinPlugins, testBuildPlugin } from '../../../src/hooks/prerun/plugin' describe('hooks:prerun:plugin', () => { describe('test builds', () => { @@ -21,3 +24,39 @@ describe('hooks:prerun:plugin', () => { }) }) }) + +describe('hooks:prerun:plugin pinning', () => { + const table = getAvailablePlugins() + const range = (name: string): string | undefined => table.find((p) => p.name === name)?.version + + it('pins the plugins that follow latest to their installed major, or else to the plugin table', () => { + const manifest = { + oclif: { + plugins: [ + { name: '@commercelayer/cli-plugin-tags', tag: 'latest', type: 'user' }, + { name: '@commercelayer/cli-plugin-orders', type: 'user' }, + { name: '@commercelayer/cli-plugin-imports', tag: '^4', type: 'user' }, + { name: 'some-other-plugin', tag: 'latest', type: 'user' }, + ], + }, + } + const installed = new Map([['@commercelayer/cli-plugin-orders', '5.7.0']]) + expect(pinPlugins(manifest, table, installed)).to.equal(true) + // orders keeps its major 5 even if the table installs ^6: a new major is never implicit + expect(manifest.oclif.plugins.map((p) => p.tag)).to.deep.equal([range('tags'), '^5', '^4', 'latest']) + expect(pinPlugins(manifest, table, installed)).to.equal(false) + }) +}) + +describe('plugin table', () => { + // A new major of a plugin reaches the table only explicitly: the table may + // lag behind the workspace, never get ahead of it + it('installs every plugin with a ^N range, N a major of the workspace plugin', () => { + for (const p of getAvailablePlugins()) { + const { name, version } = JSON.parse(readFileSync(join(__dirname, `../../../../../plugins/${p.name}/package.json`), 'utf8')) + expect(name).to.equal(p.plugin) + expect(p.version, p.name).to.match(/^\^\d+$/) + expect(Number(p.version.slice(1)), p.name).to.be.at.most(Number(version.split('.')[0])) + } + }) +})