Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: adds target-org and wait support to deploy report command #758

Merged
merged 4 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions command-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@
{
"command": "project:deploy:report",
"plugin": "@salesforce/plugin-deploy-retrieve",
"flags": ["coverage-formatters", "job-id", "json", "junit", "results-dir", "use-most-recent"],
"flags": ["coverage-formatters", "job-id", "json", "junit", "results-dir", "target-org", "use-most-recent", "wait"],
"alias": ["deploy:metadata:report"],
"flagChars": ["i", "r"],
"flagChars": ["i", "o", "r", "w"],
"flagAliases": []
},
{
Expand Down
2 changes: 1 addition & 1 deletion messages/deploy.metadata.quick.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ Overrides your default org.

# error.CannotQuickDeploy

Job ID can't be used for quick deployment. Possible reasons include the deployment hasn't been validated or the validation expired because you ran it more than 10 days ago.
Job ID can't be used for quick deployment. Possible reasons include the deployment hasn't been validated, has already been deployed, or the validation expired because you ran it more than 10 days ago.

# error.QuickDeployFailure

Expand Down
88 changes: 74 additions & 14 deletions src/commands/project/deploy/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { Messages, Org } from '@salesforce/core';
import { Duration } from '@salesforce/kit';
import { Messages, Org, SfProject } from '@salesforce/core';
import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { DeployResult, MetadataApiDeployStatus } from '@salesforce/source-deploy-retrieve';
import { buildComponentSet } from '../../../utils/deploy';
import { ComponentSet, DeployResult, MetadataApiDeploy } from '@salesforce/source-deploy-retrieve';
import { buildComponentSet, DeployOptions } from '../../../utils/deploy';
import { DeployProgress } from '../../../utils/progressBar';
import { DeployCache } from '../../../utils/deployCache';
import { DeployReportResultFormatter } from '../../../formatters/deployReportResultFormatter';
import { DeployResultJson } from '../../../utils/types';
import { coverageFormattersFlag } from '../../../utils/flags';

Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-deploy-retrieve', 'deploy.metadata.report');
const deployMessages = Messages.loadMessages('@salesforce/plugin-deploy-retrieve', 'deploy.metadata');
const testFlags = 'Test';

export default class DeployMetadataReport extends SfCommand<DeployResultJson> {
Expand All @@ -27,6 +28,11 @@ export default class DeployMetadataReport extends SfCommand<DeployResultJson> {
public static readonly deprecateAliases = true;

public static readonly flags = {
'target-org': Flags.optionalOrg({
char: 'o',
description: deployMessages.getMessage('flags.target-org.description'),
summary: deployMessages.getMessage('flags.target-org.summary'),
}),
'job-id': Flags.salesforceId({
char: 'i',
startsWith: '0Af',
Expand All @@ -51,23 +57,77 @@ export default class DeployMetadataReport extends SfCommand<DeployResultJson> {
summary: messages.getMessage('flags.results-dir.summary'),
helpGroup: testFlags,
}),
// we want to allow undefined for a simple check deploy status
// eslint-disable-next-line sf-plugin/flag-min-max-default
wait: Flags.duration({
char: 'w',
summary: deployMessages.getMessage('flags.wait.summary'),
description: deployMessages.getMessage('flags.wait.description'),
unit: 'minutes',
helpValue: '<minutes>',
min: 1,
}),
};

public async run(): Promise<DeployResultJson> {
const [{ flags }, cache] = await Promise.all([this.parse(DeployMetadataReport), DeployCache.create()]);
const jobId = cache.resolveLatest(flags['use-most-recent'], flags['job-id']);
const jobId = cache.resolveLatest(flags['use-most-recent'], flags['job-id'], false);

const deployOpts = cache.get(jobId) ?? ({} as DeployOptions & { isMdapi: boolean });
shetzel marked this conversation as resolved.
Show resolved Hide resolved
const waitDuration = flags['wait'];
const org = flags['target-org'] ?? (await Org.create({ aliasOrUsername: deployOpts['target-org'] }));

const deployOpts = cache.get(jobId);
const org = await Org.create({ aliasOrUsername: deployOpts['target-org'] });
const [deployStatus, componentSet] = await Promise.all([
// we'll use whatever the org supports since we can't specify the org
// if we're using mdapi we won't have a component set
let componentSet = new ComponentSet();
if (!deployOpts.isMdapi) {
shetzel marked this conversation as resolved.
Show resolved Hide resolved
if (!cache.get(jobId)) {
// If the cache file isn't there, use the project package directories for the CompSet
try {
this.project = await SfProject.resolve();
const sourcepath = this.project.getUniquePackageDirectories().map((pDir) => pDir.fullPath);
componentSet = await buildComponentSet({ 'source-dir': sourcepath, wait: waitDuration });
} catch (err) {
// ignore the error. this was just to get improved command output.
}
} else {
componentSet = await buildComponentSet({ ...deployOpts, wait: waitDuration });
}
}
const mdapiDeploy = new MetadataApiDeploy({
// setting an API version here won't matter since we're just checking deploy status
// eslint-disable-next-line sf-plugin/get-connection-with-version
shetzel marked this conversation as resolved.
Show resolved Hide resolved
org.getConnection().metadata.checkDeployStatus(jobId, true),
// if we're using mdapi, we won't have a component set
deployOpts.isMdapi ? undefined : buildComponentSet({ ...deployOpts, wait: Duration.minutes(deployOpts.wait) }),
]);
usernameOrConnection: org.getConnection(),
id: jobId,
components: componentSet,
apiOptions: {
rest: deployOpts.api === 'REST',
},
});

const getDeployResult = async (): Promise<DeployResult> => {
const deployStatus = await mdapiDeploy.checkStatus();
return new DeployResult(deployStatus, componentSet);
};

const result = new DeployResult(deployStatus as MetadataApiDeployStatus, componentSet);
let result: DeployResult;
if (waitDuration) {
// poll for deploy results
try {
new DeployProgress(mdapiDeploy, this.jsonEnabled()).start();
result = await mdapiDeploy.pollStatus(500, waitDuration.seconds);
} catch (error) {
if (error instanceof Error && error.message.includes('The client has timed out')) {
this.debug('[project deploy report] polling timed out. Requesting status...');
} else {
throw error;
}
} finally {
result = await getDeployResult();
}
} else {
// check the deploy status
result = await getDeployResult();
}

const formatter = new DeployReportResultFormatter(result, {
...deployOpts,
Expand Down
47 changes: 28 additions & 19 deletions test/commands/deploy/metadata/report.nut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@ import { assert, isObject } from '@salesforce/ts-types';
import { expect } from 'chai';
import { DeployResultJson } from '../../../../src/utils/types';

describe('deploy metadata report NUTs with source-dir', () => {
describe('[project deploy report] NUTs with source-dir', () => {
let testkit: SourceTestkit;

const orgAlias = 'reportTestOrg2';

before(async () => {
testkit = await SourceTestkit.create({
repository: 'https://github.com/salesforcecli/sample-project-multiple-packages.git',
nut: __filename,
scratchOrgs: [{ duration: 1, alias: orgAlias, config: path.join('config', 'project-scratch-def.json') }],
});
});

Expand All @@ -28,63 +31,69 @@ describe('deploy metadata report NUTs with source-dir', () => {

describe('--use-most-recent', () => {
it('should report most recently started deployment', async () => {
await testkit.execute<DeployResultJson>('deploy:metadata', {
await testkit.execute<DeployResultJson>('project deploy start', {
args: '--source-dir force-app --async',
json: true,
exitCode: 0,
});

const deploy = await testkit.execute<DeployResultJson>('deploy:metadata:report', {
const deploy = await testkit.execute<DeployResultJson>('project deploy report', {
args: '--use-most-recent',
json: true,
exitCode: 0,
});
assert(isObject(deploy));
await testkit.expect.filesToBeDeployedViaResult(['force-app/**/*'], ['force-app/test/**/*'], deploy.result.files);
});
});

it.skip('should report most recently started deployment without specifying the flag', async () => {
await testkit.execute<DeployResultJson>('deploy:metadata', {
args: '--source-dir force-app --async',
describe('--job-id', () => {
it('should report the provided job id', async () => {
const first = await testkit.execute<DeployResultJson>('project deploy start', {
args: '--source-dir force-app --async --ignore-conflicts',
json: true,
exitCode: 0,
});

const deploy = await testkit.execute<DeployResultJson>('deploy:metadata:report', {
const deploy = await testkit.execute<DeployResultJson>('project deploy report', {
args: `--job-id ${first?.result.id}`,
json: true,
exitCode: 0,
});
assert(isObject(deploy));
await testkit.expect.filesToBeDeployedViaResult(['force-app/**/*'], ['force-app/test/**/*'], deploy.result.files);
});
});

describe('--job-id', () => {
it('should report the provided job id', async () => {
const first = await testkit.execute<DeployResultJson>('deploy:metadata', {
args: '--source-dir force-app --async --ignore-conflicts',
it('should report from specified target-org and job-id without deploy cache', async () => {
const first = await testkit.execute<DeployResultJson>('project deploy start', {
args: `--source-dir force-app --async --target-org ${orgAlias}`,
json: true,
exitCode: 0,
});
const deploy = await testkit.execute<DeployResultJson>('deploy:metadata:report', {
args: `--job-id ${first?.result.id}`,

// delete the cache file so we can verify that reporting just with job-id and org works
const deployCacheFilePath = path.resolve(testkit.projectDir, path.join('..', '.sf', 'deploy-cache.json'));
fs.unlinkSync(deployCacheFilePath);
assert(!fs.existsSync(deployCacheFilePath));

const deploy = await testkit.execute<DeployResultJson>('project deploy report', {
args: `--job-id ${first?.result.id} --target-org ${orgAlias} --wait 9`,
json: true,
exitCode: 0,
});
assert(isObject(deploy));
await testkit.expect.filesToBeDeployedViaResult(['force-app/**/*'], ['force-app/test/**/*'], deploy.result.files);
await testkit.expect.filesToBeDeployed(['force-app/**/*'], ['force-app/test/**/*']);
});
});

describe('test flags', () => {
it('should override the --output-dir', async () => {
const first = await testkit.execute<DeployResultJson>('deploy:metadata', {
const first = await testkit.execute<DeployResultJson>('project deploy start', {
args: '--source-dir force-app --async --ignore-conflicts --test-level RunAllTestsInOrg --coverage-formatters html --junit --results-dir test-output',
json: true,
exitCode: 0,
});
const deploy = await testkit.execute<DeployResultJson>('deploy:metadata:report', {
args: `--job-id ${first?.result.id} --coverage-formatters html --coverage-formatters text --junit --results-dir test-output-override`,
const deploy = await testkit.execute<DeployResultJson>('project deploy report', {
args: `--job-id ${first?.result.id} --coverage-formatters html --coverage-formatters text --junit --results-dir test-output-override --wait 9`,
json: true,
exitCode: 0,
});
Expand Down
Loading