Skip to content
17 changes: 12 additions & 5 deletions command-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -84,8 +84,7 @@
"seed-metadata",
"target-dev-hub",
"verbose",
"wait",
"code-coverage"
"wait"
],
"plugin": "@salesforce/plugin-packaging"
},
Expand Down Expand Up @@ -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",
Expand Down
37 changes: 37 additions & 0 deletions messages/package_version_displaydependencies.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
16 changes: 16 additions & 0 deletions schemas/package-version-displaydependencies.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "#/definitions/DisplayDependenciesCommandResult",
"definitions": {
"DisplayDependenciesCommandResult": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
}
}
65 changes: 65 additions & 0 deletions src/commands/package/version/displaydependencies.ts
Original file line number Diff line number Diff line change
@@ -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<DisplayDependenciesCommandResult> {
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<DisplayDependenciesCommandResult> {
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);
}
}
90 changes: 90 additions & 0 deletions test/commands/package/packageVersion.nut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>('target-dev-hub') });
const pvRecords = (await devHubOrg.getConnection().tooling.query<PackageVersionCreateRequestResult>(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<string>(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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why the || [] is needed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need the empty array to find the length if the results return null.

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: {
Expand Down
Loading