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

Sm/error json #450

Merged
merged 9 commits into from
Mar 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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 src/commands/force/source/beta/pull.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default class Pull extends SourceCommand {
protected retrieveResult: RetrieveResult;
protected deleteFileResponses: FileResponse[];

public async run(): Promise<PullResponse[]> {
public async run(): Promise<PullResponse> {
await this.preChecks();
await this.retrieve();
// do not parallelize delete and retrieve...we only get to delete IF retrieve was successful
Expand Down Expand Up @@ -139,7 +139,7 @@ export default class Pull extends SourceCommand {
}
}

protected formatResult(): PullResponse[] {
protected formatResult(): PullResponse {
const formatterOptions = {
verbose: this.getFlag<boolean>('verbose', false),
};
Expand Down
20 changes: 17 additions & 3 deletions src/formatters/source/pullFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { ResultFormatter, ResultFormatterOptions, toArray } from '../resultForma
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-source', 'pull');

export type PullResponse = Pick<FileResponse, 'filePath' | 'fullName' | 'state' | 'type'>;
export type PullResponse = { pulledSource: Array<Pick<FileResponse, 'filePath' | 'fullName' | 'state' | 'type'>> };

export class PullResultFormatter extends ResultFormatter {
protected result: RetrieveResult;
Expand Down Expand Up @@ -53,8 +53,22 @@ export class PullResultFormatter extends ResultFormatter {
*
* @returns RetrieveCommandResult
*/
public getJson(): PullResponse[] {
return this.fileResponses.map(({ state, fullName, type, filePath }) => ({ state, fullName, type, filePath }));
public getJson(): PullResponse {
if (!this.isSuccess()) {
const error = new SfdxError('Pull failed.', 'PullFailed', [], process.exitCode);
error.setData(
this.fileResponses.map(({ state, fullName, type, filePath }) => ({ state, fullName, type, filePath }))
);
throw error;
}
return {
pulledSource: this.fileResponses.map(({ state, fullName, type, filePath }) => ({
state,
fullName,
type,
filePath,
})),
};
}

/**
Expand Down
14 changes: 14 additions & 0 deletions src/formatters/source/pushResultFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,20 @@ export class PushResultFormatter extends ResultFormatter {
* @returns a JSON formatted result matching the provided type.
*/
public getJson(): PushResponse {
// throws a particular json structure. commandName property will be appended by sfdxCommand when this throws
if (process.exitCode !== 0) {
iowillhoit marked this conversation as resolved.
Show resolved Hide resolved
const error = new SfdxError(messages.getMessage('sourcepushFailed'), 'DeployFailed', [], process.exitCode);
const errorData = this.fileResponses.filter((fileResponse) => fileResponse.state === ComponentStatus.Failed);
error.setData(errorData);
error['result'] = errorData;
// partial success
if (process.exitCode === 69) {
error['partialSuccess'] = this.fileResponses.filter(
(fileResponse) => fileResponse.state !== ComponentStatus.Failed
);
}
throw error;
}
// quiet returns only failures
const toReturn = this.isQuiet()
? this.fileResponses.filter((fileResponse) => fileResponse.state === ComponentStatus.Failed)
Expand Down
43 changes: 27 additions & 16 deletions src/trackingFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* 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 * as path from 'path';
import { UX } from '@salesforce/command';
import {
ChangeResult,
Expand All @@ -21,7 +22,6 @@ import {
FileResponse,
RetrieveResult,
} from '@salesforce/source-deploy-retrieve';

Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-source', 'tracking');

Expand All @@ -42,6 +42,12 @@ interface TrackingUpdateRequest {
fileResponses?: FileResponse[];
}

interface ConflictResponse {
state: 'Conflict';
fullName: string;
type: string;
filePath: string;
}
/**
* Check if any conflicts exist in a specific component set.
* If conflicts exist, this will output the table and throw
Expand Down Expand Up @@ -141,18 +147,15 @@ export const updateTracking = async ({ tracking, result, ux, fileResponses }: Tr
ux.stopSpinner();
};

const writeConflictTable = (conflicts: ChangeResult[], ux: UX): void => {
ux.table(
conflicts.map((conflict) => ({ ...conflict, state: 'Conflict' })),
{
columns: [
{ label: 'STATE', key: 'state' },
{ label: 'FULL NAME', key: 'name' },
{ label: 'TYPE', key: 'type' },
{ label: 'PROJECT PATH', key: 'filenames' },
],
}
);
const writeConflictTable = (conflicts: ConflictResponse[], ux: UX): void => {
ux.table(conflicts, {
columns: [
{ label: 'STATE', key: 'state' },
{ label: 'FULL NAME', key: 'name' },
{ label: 'TYPE', key: 'type' },
{ label: 'PROJECT PATH', key: 'filenames' },
],
});
};

/**
Expand All @@ -166,8 +169,16 @@ const processConflicts = (conflicts: ChangeResult[], ux: UX, message: string): v
if (conflicts.length === 0) {
return;
}
writeConflictTable(conflicts, ux);
const err = new SfdxError(message);
err.setData(conflicts);
const reformattedConflicts: ConflictResponse[] = conflicts.flatMap((conflict) =>
conflict.filenames.map((f) => ({
state: 'Conflict',
fullName: conflict.name,
type: conflict.type,
filePath: path.resolve(f),
}))
);
writeConflictTable(reformattedConflicts, ux);
const err = new SfdxError(message, 'sourceConflictDetected');
err.setData(reformattedConflicts);
throw err;
};
14 changes: 10 additions & 4 deletions test/commands/source/deployResponses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,16 @@ export const getDeployResponse = (
if (type === 'failed') {
response.status = RequestStatus.Failed;
response.success = false;
response.details.componentFailures = cloneJson(baseDeployResponse.details.componentSuccesses[1]) as DeployMessage;
response.details.componentSuccesses = cloneJson(baseDeployResponse.details.componentSuccesses[0]) as DeployMessage;
response.details.componentFailures.success = 'false';
response.details.componentFailures = {
...(cloneJson(baseDeployResponse.details.componentSuccesses[1]) as DeployMessage),
success: false,
problemType: 'Error',
problem: 'This component has some problems',
lineNumber: '27',
columnNumber: '18',
};
delete response.details.componentFailures.id;
response.details.componentFailures.problemType = 'Error';
response.details.componentFailures.problem = 'This component has some problems';
}

if (type === 'failedTest') {
Expand Down Expand Up @@ -305,6 +309,8 @@ export const getDeployResult = (
type: comp.componentType,
error: comp.problem,
problemType: comp.problemType,
lineNumber: comp.lineNumber,
columnNumber: comp.columnNumber,
}));
} else {
const successes = response.details.componentSuccesses;
Expand Down
152 changes: 152 additions & 0 deletions test/formatters/pullFormatter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* Copyright (c) 2020, 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 { relative } from 'path';
import * as sinon from 'sinon';
import { expect } from 'chai';
import { Logger } from '@salesforce/core';
import { UX } from '@salesforce/command';
import { FileResponse } from '@salesforce/source-deploy-retrieve';
// import { cloneJson } from '@salesforce/kit';
import { stubInterface } from '@salesforce/ts-sinon';
import { getRetrieveResult } from '../commands/source/retrieveResponses';
import { PullResponse, PullResultFormatter } from '../../src/formatters/source/pullFormatter';
import { toArray } from '../../src/formatters/resultFormatter';

describe('PullFormatter', () => {
const sandbox = sinon.createSandbox();

const retrieveResultSuccess = getRetrieveResult('success');
const retrieveResultFailure = getRetrieveResult('failed');
const retrieveResultInProgress = getRetrieveResult('inProgress');
const retrieveResultEmpty = getRetrieveResult('empty');
const retrieveResultWarnings = getRetrieveResult('warnings');

const logger = Logger.childFromRoot('retrieveTestLogger').useMemoryLogging();
let ux;
let logStub: sinon.SinonStub;
let styledHeaderStub: sinon.SinonStub;
let tableStub: sinon.SinonStub;

const resolveExpectedPaths = (fileResponses: FileResponse[]): void => {
fileResponses.forEach((file) => {
if (file.filePath) {
file.filePath = relative(process.cwd(), file.filePath);
}
});
};

beforeEach(() => {
logStub = sandbox.stub();
styledHeaderStub = sandbox.stub();
tableStub = sandbox.stub();
ux = stubInterface<UX>(sandbox, {
log: logStub,
styledHeader: styledHeaderStub,
table: tableStub,
});
});

afterEach(() => {
sandbox.restore();
process.exitCode = undefined;
});

describe('getJson', () => {
it('should return expected json for a success', async () => {
process.exitCode = 0;
const expectedSuccessResults: PullResponse['pulledSource'] = retrieveResultSuccess.getFileResponses();
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultSuccess);
expect(formatter.getJson().pulledSource).to.deep.equal(expectedSuccessResults);
});

it('should return expected json for a failure', async () => {
process.exitCode = 1;
const expectedFailureResults: PullResponse['pulledSource'] = retrieveResultFailure.getFileResponses();
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultFailure);
try {
formatter.getJson().pulledSource;
throw new Error('should have thrown');
} catch (error) {
expect(error).to.have.property('message', 'Pull failed.');
expect(error).to.have.property('data').deep.equal(expectedFailureResults);
expect(error).to.have.property('stack').includes('PullFailed:');
expect(error).to.have.property('name', 'PullFailed');
}
});

it('should return expected json for an InProgress', async () => {
const expectedInProgressResults: PullResponse['pulledSource'] = retrieveResultInProgress.getFileResponses();
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultInProgress);
expect(formatter.getJson().pulledSource).to.deep.equal(expectedInProgressResults);
});

describe('display', () => {
it('should output as expected for a success', async () => {
process.exitCode = 0;
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultSuccess);
formatter.display();
expect(styledHeaderStub.called).to.equal(true);
expect(logStub.called).to.equal(false);
expect(tableStub.called).to.equal(true);
expect(styledHeaderStub.firstCall.args[0]).to.contain('Retrieved Source');
const fileResponses = retrieveResultSuccess.getFileResponses();
resolveExpectedPaths(fileResponses);
expect(tableStub.firstCall.args[0]).to.deep.equal(fileResponses);
});

it('should output as expected for an InProgress', async () => {
process.exitCode = 68;
const options = { waitTime: 33 };
const formatter = new PullResultFormatter(logger, ux as UX, options, retrieveResultInProgress);
formatter.display();
expect(styledHeaderStub.called).to.equal(false);
expect(logStub.called).to.equal(true);
expect(tableStub.called).to.equal(false);
expect(logStub.firstCall.args[0])
.to.contain('Your retrieve request did not complete')
.and.contain(`${options.waitTime} minutes`);
});

it('should output as expected for a Failure', async () => {
process.exitCode = 1;
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultFailure);
sandbox.stub(formatter, 'isSuccess').returns(false);

formatter.display();
expect(logStub.called).to.equal(true);
expect(tableStub.called).to.equal(false);
expect(logStub.firstCall.args[0]).to.contain('Retrieve Failed due to:');
});

it('should output as expected for warnings', async () => {
process.exitCode = 0;
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultWarnings);
formatter.display();
// Should call styledHeader for warnings and the standard "Retrieved Source" header
expect(styledHeaderStub.calledTwice).to.equal(true);
expect(logStub.called).to.equal(true);
expect(tableStub.calledOnce).to.equal(true);
expect(styledHeaderStub.secondCall.args[0]).to.contain('Retrieved Source Warnings');
const warnMessages = retrieveResultWarnings.response.messages;
const warnings = toArray(warnMessages);
expect(tableStub.firstCall.args[0]).to.deep.equal(warnings);
});

it('should output a message when no results were returned', async () => {
process.exitCode = 0;
const formatter = new PullResultFormatter(logger, ux as UX, {}, retrieveResultEmpty);
formatter.display();
expect(styledHeaderStub.called).to.equal(true);
expect(logStub.called).to.equal(true);
expect(tableStub.called).to.equal(false);
expect(styledHeaderStub.firstCall.args[0]).to.contain('Retrieved Source');
expect(logStub.firstCall.args[0]).to.contain('No results found');
});
});
});
});
38 changes: 36 additions & 2 deletions test/formatters/pushResultFormatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,18 @@ describe('PushResultFormatter', () => {
});

describe('json', () => {
const expectedFail = {
filePath: 'classes/ProductController.cls',
fullName: 'ProductController',
state: 'Failed',
type: 'ApexClass',
lineNumber: '27',
columnNumber: '18',
problemType: 'Error',
error: 'This component has some problems',
};
it('returns expected json for success', () => {
process.exitCode = 0;
const formatter = new PushResultFormatter(logger, new UX(logger), {}, deployResultSuccess);
expect(formatter.getJson().pushedSource).to.deep.equal([
{
Expand All @@ -48,14 +59,37 @@ describe('PushResultFormatter', () => {
},
]);
});
it('returns expected json for failure', () => {
const formatter = new PushResultFormatter(logger, new UX(logger), {}, deployResultFailure);
process.exitCode = 1;

try {
formatter.getJson();
throw new Error('should have thrown');
} catch (error) {
expect(error).to.have.property('message', 'Push failed.');
expect(error).to.have.property('name', 'DeployFailed');
expect(error).to.have.property('stack').includes('DeployFailed:');
expect(error).to.have.property('actions').deep.equal([]);
expect(error).to.have.property('data').deep.equal([expectedFail]);
expect(error).to.have.property('result').deep.equal([expectedFail]);
}
});
describe('json with quiet', () => {
it('honors quiet flag for json successes', () => {
process.exitCode = 0;
const formatter = new PushResultFormatter(logger, new UX(logger), { quiet: true }, deployResultSuccess);
expect(formatter.getJson().pushedSource).to.deep.equal([]);
});
it('honors quiet flag for json successes', () => {
it('honors quiet flag for json failure', () => {
const formatter = new PushResultFormatter(logger, new UX(logger), { quiet: true }, deployResultFailure);
expect(formatter.getJson().pushedSource).to.have.length(1);
try {
formatter.getJson();
throw new Error('should have thrown');
} catch (error) {
expect(error).to.have.property('message', 'Push failed.');
expect(error).to.have.property('result').deep.equal([expectedFail]);
}
});
});
});
Expand Down
Loading