diff --git a/command-snapshot.json b/command-snapshot.json index 5d1c3ac4..d2a99018 100644 --- a/command-snapshot.json +++ b/command-snapshot.json @@ -66,13 +66,13 @@ "installationkeybypass", "patchversion", "target-hub-org", - "targetdevhubusername", - "codecoverage" + "targetdevhubusername" ], - "flagChars": ["a", "f", "k", "m", "p", "s", "v", "w", "x", "c"], + "flagChars": ["a", "c", "f", "k", "m", "p", "s", "v", "w", "x"], "flags": [ "api-version", "build-instance", + "code-coverage", "definition-file", "flags-dir", "installation-key", @@ -84,8 +84,7 @@ "seed-metadata", "target-dev-hub", "verbose", - "wait", - "code-coverage" + "wait" ], "plugin": "@salesforce/plugin-packaging" }, @@ -368,6 +367,14 @@ "flags": ["api-version", "dot-code", "flags-dir", "json", "loglevel", "package", "target-dev-hub", "verbose"], "plugin": "@salesforce/plugin-packaging" }, + { + "alias": [], + "command": "package:version:displaydependencies", + "flagAliases": ["apiversion", "target-hub-org", "targetdevhubusername"], + "flagChars": ["p", "v"], + "flags": ["api-version", "edge-direction", "flags-dir", "json", "loglevel", "package", "target-dev-hub", "verbose"], + "plugin": "@salesforce/plugin-packaging" + }, { "alias": ["force:package:version:list"], "command": "package:version:list", diff --git a/messages/package_version_displaydependencies.md b/messages/package_version_displaydependencies.md new file mode 100644 index 00000000..7634d7b2 --- /dev/null +++ b/messages/package_version_displaydependencies.md @@ -0,0 +1,37 @@ +# summary + +Display the dependency graph for an unlocked or 2GP managed package version. + +# examples + +- Display the dependency graph for a package version with the specified alias, using your default Dev Hub org and the default edge-direction: + + <%= config.bin %> <%= command.id %> --package package_version_alias + +- Display the dependency graph for a package version with the specified ID and display the graph using a root-last edge direction. Use the Dev Hub org with username devhub@example.com: + + <%= config.bin %> <%= command.id %> --package 04t... --edge-direction root-last --target-dev-hub devhub@example.com + +- Display the dependency graph of a version create request with the specified ID, using your default Dev Hub org and the default edge-direction: + + <%= config.bin %> <%= command.id %> --package 08c... + +# flags.package.summary + +ID or alias of the package version (starts with 04t) or the package version create request (starts with 08c) to display the dependency graph for. + +# flags.package.description + +Before running this command, update your sfdx-project.json file to specify the calculateTransitiveDependencies attribute, and set the value to true. This command returns GraphViz code, which can be compiled to a graph using DOT code or another graph visualization software. + +# flags.edge-direction.summary + +Order (root-first or root-last) in which the dependencies are displayed. + +# flags.edge-direction.description + +A root-first graph declares the root as the package that must be installed last. A root-last graph is the reverse order of root-first. If you specify "--edge-direction root-last", the graph displays the packages in the order they must be installed. The root starts with the farthest leaf of the package dependencies and ends with the base package, which must be installed last. + +# flags.verbose.summary + +Display both the package version ID (starts with 04t) and the version number (major.minor.patch.build) in each node. diff --git a/package.json b/package.json index b2253ad6..b7b91f0f 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "@salesforce/core": "^8.15.0", "@salesforce/kit": "^3.2.3", "@salesforce/packaging": "^4.9.0", - "@salesforce/sf-plugins-core": "^12.2.2", + "@salesforce/sf-plugins-core": "^12.2.3", "chalk": "^5.4.1" }, "devDependencies": { diff --git a/schemas/package-version-displaydependencies.json b/schemas/package-version-displaydependencies.json new file mode 100644 index 00000000..e433bb59 --- /dev/null +++ b/schemas/package-version-displaydependencies.json @@ -0,0 +1,16 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$ref": "#/definitions/DisplayDependenciesCommandResult", + "definitions": { + "DisplayDependenciesCommandResult": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + } +} diff --git a/src/commands/package/version/displaydependencies.ts b/src/commands/package/version/displaydependencies.ts new file mode 100644 index 00000000..2fe80828 --- /dev/null +++ b/src/commands/package/version/displaydependencies.ts @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022, salesforce.com, inc. + * All rights reserved. + * Licensed under the BSD 3-Clause license. + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + */ +import { Flags, loglevel, orgApiVersionFlagWithDeprecations, SfCommand } from '@salesforce/sf-plugins-core'; +import { Messages } from '@salesforce/core/messages'; +import { Package } from '@salesforce/packaging'; +import { requiredHubFlag } from '../../../utils/hubFlag.js'; +import { maybeGetProject } from '../../../utils/getProject.js'; + +Messages.importMessagesDirectoryFromMetaUrl(import.meta.url); +const messages = Messages.loadMessages('@salesforce/plugin-packaging', 'package_version_displaydependencies'); +export type DisplayDependenciesCommandResult = string | void; + +export class PackageVersionDisplayDependenciesCommand extends SfCommand { + public static readonly summary = messages.getMessage('summary'); + public static readonly examples = messages.getMessages('examples'); + public static readonly deprecateAliases = true; + + public static readonly flags = { + loglevel, + 'target-dev-hub': requiredHubFlag, + 'api-version': orgApiVersionFlagWithDeprecations, + package: Flags.string({ + char: 'p', + summary: messages.getMessage('flags.package.summary'), + description: messages.getMessage('flags.package.description'), + required: true, + }), + 'edge-direction': Flags.custom<'root-first' | 'root-last'>({ + options: ['root-first', 'root-last'], + })({ + summary: messages.getMessage('flags.edge-direction.summary'), + description: messages.getMessage('flags.edge-direction.description'), + default: 'root-first', + }), + verbose: Flags.boolean({ + summary: messages.getMessage('flags.verbose.summary'), + default: false, + }), + }; + + public async run(): Promise { + const { flags } = await this.parse(PackageVersionDisplayDependenciesCommand); + const packageDependencyGraph = await Package.getDependencyGraph( + flags.package, + await maybeGetProject(), + flags['target-dev-hub'].getConnection(flags['api-version']), + { + verbose: flags['verbose'], + edgeDirection: flags['edge-direction'], + } + ); + + const dotProducer = await packageDependencyGraph.getDependencyDotProducer(); + const dotCodeResult = dotProducer.produce(); + + if (flags.json) { + return dotCodeResult; + } + this.log(dotCodeResult); + } +} diff --git a/test/commands/package/packageVersion.nut.ts b/test/commands/package/packageVersion.nut.ts index 58d75f01..f46ba9e1 100644 --- a/test/commands/package/packageVersion.nut.ts +++ b/test/commands/package/packageVersion.nut.ts @@ -470,6 +470,96 @@ describe('package:version:*', () => { }); }); + describe('package:version:displaydependencies', () => { + type PackageVersionCreateRequestResult = { + Id: string; + Package2Version: { + SubscriberPackageVersionId: string; + }; + }; + let devHubOrg: Org; + let configAggregator: ConfigAggregator; + let testPackageRequestId: string; // 08c ID + let testSubscriberPackageVersionId: string; // 04t ID + const NODE_LABEL_REGEX = /label="[^"]*@\d+\.\d+\.\d+\.\d+"/; + const EDGE_REGEX = /\t node_\w+ -> node_\w+/g; + + before('dependencies project setup', async () => { + const query = 'SELECT Id, Package2Version.SubscriberPackageVersionId FROM Package2VersionCreateRequest LIMIT 10'; + configAggregator = await ConfigAggregator.create(); + devHubOrg = await Org.create({ aliasOrUsername: configAggregator.getPropertyValue('target-dev-hub') }); + const pvRecords = (await devHubOrg.getConnection().tooling.query(query)) + .records; + + if (!pvRecords || pvRecords.length === 0) { + throw new Error('No package version create requests found with dependency graph json'); + } + const pv = pvRecords[0]; + testPackageRequestId = pv.Id; + testSubscriberPackageVersionId = pv.Package2Version.SubscriberPackageVersionId; + }); + it('should print the correct DOT code output (default)', () => { + const command = `package:version:displaydependencies -p ${testPackageRequestId}`; + const result = execCmd(command, { ensureExitCode: 0 }).shellOutput.stdout; + expect(result).to.contain('strict digraph G {'); + const hasValidNode = result.includes('node_'); + expect(hasValidNode).to.be.true; + expect(result).to.match(NODE_LABEL_REGEX); + const hasMultipleNodes = result.split('\n').filter((line) => line.includes('node_')).length > 1; + if (hasMultipleNodes) { + expect(result).to.contain('->'); + } + }); + it('should print the correct DOT code output (verbose)', () => { + const command = `package:version:displaydependencies -p ${testPackageRequestId} --verbose`; + const result = execCmd(command, { ensureExitCode: 0 }).shellOutput.stdout; + expect(result).to.contain('strict digraph G {'); + const hasSubscriberPackageVersionId = /\(04t.{15}\)/.test(result); + const hasVersionBeingBuilt = result.includes('(VERSION_BEING_BUILT)'); + expect(hasSubscriberPackageVersionId || hasVersionBeingBuilt).to.be.true; + }); + it('should print the correct DOT code output (json)', () => { + const command = `package:version:displaydependencies -p ${testPackageRequestId} --json`; + const result = execCmd(command, { ensureExitCode: 0 }); + const dotCode = result.jsonOutput?.result; + expect(dotCode).to.be.a('string'); + expect(dotCode).to.contain('strict digraph G {'); + }); + it('should print the correct DOT code output (root-last)', () => { + const commandRootFirst = `package:version:displaydependencies -p ${testPackageRequestId} --edge-direction root-first`; + const resultRootFirst = execCmd(commandRootFirst, { ensureExitCode: 0 }).shellOutput.stdout; + const commandRootLast = `package:version:displaydependencies -p ${testPackageRequestId} --edge-direction root-last`; + const resultRootLast = execCmd(commandRootLast, { ensureExitCode: 0 }).shellOutput.stdout; + expect(resultRootFirst).to.contain('strict digraph G {'); + expect(resultRootLast).to.contain('strict digraph G {'); + const hasMultipleNodes = ((resultRootFirst.match(/node_/g) && resultRootLast.match(/node_/g)) || []).length > 1; + if (hasMultipleNodes) { + const edgeLinesFirst = resultRootFirst.match(EDGE_REGEX) || []; + const edgeLinesLast = resultRootLast.match(EDGE_REGEX) || []; + expect(edgeLinesFirst.length).to.equal(edgeLinesLast.length); + expect(resultRootFirst).to.not.equal(resultRootLast); + } else { + expect(resultRootFirst).to.contain('node_'); + expect(resultRootLast).to.contain('node_'); + } + }); + it('should work with 04t package version ID if available', function () { + if (!testSubscriberPackageVersionId) { + this.skip(); + } + const command = `package:version:displaydependencies -p ${testSubscriberPackageVersionId}`; + const result = execCmd(command, { ensureExitCode: 0 }).shellOutput.stdout; + expect(result).to.contain('strict digraph G {'); + const hasValidNode = result.includes('node_'); + expect(hasValidNode).to.be.true; + expect(result).to.match(NODE_LABEL_REGEX); + const hasMultipleNodes = result.split('\n').filter((line) => line.includes('node_')).length > 1; + if (hasMultipleNodes) { + expect(result).to.contain('->'); + } + }); + }); + describe('package:version:ancestrydisplay', () => { type PackageVersionQueryResult = PackagingSObjects.Package2Version & { Package2: {