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: deletes singular CL when from CLs when specified #381

Merged
merged 16 commits into from
May 17, 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
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ export {
ConflictResponse,
SourceConflictError,
} from './shared/types';
export { getKeyFromObject } from './shared/functions';
export { getKeyFromObject, deleteCustomLabels } from './shared/functions';
51 changes: 51 additions & 0 deletions src/shared/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@
*/

import { sep, normalize, isAbsolute, relative } from 'path';
import * as fs from 'fs';
import { isString } from '@salesforce/ts-types';
import { SourceComponent } from '@salesforce/source-deploy-retrieve';
import { XMLBuilder, XMLParser } from 'fast-xml-parser';
import { ensureArray } from '@salesforce/kit';
import { RemoteChangeElement, ChangeResult } from './types';

export const getMetadataKey = (metadataType: string, metadataName: string): string =>
Expand Down Expand Up @@ -45,3 +48,51 @@ export const chunkArray = <T>(arr: T[], size: number): T[][] =>

export const ensureRelative = (filePath: string, projectPath: string): string =>
isAbsolute(filePath) ? relative(projectPath, filePath) : filePath;

/**
* A method to help delete custom labels from a file, or the entire file if there are no more labels
*
* @param filename - a path to a custom labels file
* @param customLabels - an array of SourceComponents representing the custom labels to delete
*/
export const deleteCustomLabels = (filename: string, customLabels: SourceComponent[]): Promise<void> => {
Copy link
Contributor

@mshanemc mshanemc May 11, 2023

Choose a reason for hiding this comment

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

Can it return some sort of results structure?

Like maybe it returns a Promise of either the file contents as JSON or undefined (if it was deleted), inside an object for potential future expansion? like, {fileContents?: cls }

you'd still need the writeStub in your test, but you could assert from the function response?

const customLabelsToDelete = customLabels
.filter((label) => label.type.id === 'customlabel')
.map((change) => change.fullName);

// if we don't have custom labels, we don't need to do anything
if (!customLabelsToDelete.length) {
return Promise.resolve();
}
// for custom labels, we need to remove the individual label from the xml file
// so we'll parse the xml
const parser = new XMLParser({
ignoreDeclaration: false,
ignoreAttributes: false,
attributeNamePrefix: '@_',
});
const cls = parser.parse(fs.readFileSync(filename, 'utf8')) as {
CustomLabels: { labels: Array<{ fullName: string }> };
};

// delete the labels from the json based on their fullName's
cls.CustomLabels.labels = ensureArray(cls.CustomLabels.labels).filter(
(label) => !customLabelsToDelete.includes(label.fullName)
);

if (cls.CustomLabels.labels.length === 0) {
// we've deleted everything, so let's delete the file
return fs.promises.unlink(filename);
} else {
// we need to write the file json back to xml back to the fs
const builder = new XMLBuilder({
attributeNamePrefix: '@_',
ignoreAttributes: false,
format: true,
indentBy: ' ',
});
// and then write that json back to xml and back to the fs
const xml = builder.build(cls) as string;
return fs.promises.writeFile(filename, xml);
}
};
57 changes: 2 additions & 55 deletions src/sourceTracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ import {
} from '@salesforce/source-deploy-retrieve';
// this is not exported by SDR (see the comments in SDR regarding its limitations)
import { filePathsFromMetadataComponent } from '@salesforce/source-deploy-retrieve/lib/src/utils/filePathGenerator';

import { XMLBuilder, XMLParser } from 'fast-xml-parser';
import { RemoteSourceTrackingService, remoteChangeElementToChangeResult } from './shared/remoteSourceTrackingService';
import { ShadowRepo } from './shared/localShadowRepo';
import { throwIfConflicts, findConflictsInComponentSet, getDedupedConflictsFromChanges } from './shared/conflicts';
Expand All @@ -42,7 +40,7 @@ import {
RemoteChangeElement,
} from './shared/types';
import { sourceComponentGuard } from './shared/guards';
import { supportsPartialDelete, pathIsInFolder, ensureRelative } from './shared/functions';
import { supportsPartialDelete, pathIsInFolder, ensureRelative, deleteCustomLabels } from './shared/functions';
import { registrySupportsType } from './shared/metadataKeys';
import { populateFilePaths } from './shared/populateFilePaths';
import { populateTypesAndNames } from './shared/populateTypesAndNames';
Expand Down Expand Up @@ -107,54 +105,6 @@ export class SourceTracking extends AsyncCreatable {
this.subscribeSDREvents = options.subscribeSDREvents ?? false;
}

/**
* A static method to help delete custom labels from a file, or the entire file if there are no more labels
*
* @param filename - a path to a custom labels file
* @param customLabels - an array of SourceComponents representing the custom labels to delete
*/
public static async deleteCustomLabels(filename: string, customLabels: SourceComponent[]): Promise<void> {
// for custom labels, we need to remove the individual label from the xml file
// so we'll parse the xml
const parser = new XMLParser({
ignoreDeclaration: false,
ignoreAttributes: false,
attributeNamePrefix: '@_',
});
const cls = parser.parse(fs.readFileSync(filename, 'utf8')) as {
CustomLabels: { labels: Array<{ fullName: string }> | { fullName: string } };
};
if ('fullName' in cls.CustomLabels.labels) {
// a single custom label remains, delete the entire file
return fs.promises.unlink(filename);
} else {
// in theory, we should only have custom labels passed in, but filter just to make sure
const customLabelsToDelete = customLabels
.filter((label) => label.type.id === 'customlabel')
.map((change) => change.fullName);
// delete the labels from the json based on their fullName's
cls.CustomLabels.labels = cls.CustomLabels.labels.filter(
(label) => !customLabelsToDelete.includes(label.fullName)
);

if (cls.CustomLabels.labels.length === 0) {
// we've deleted everything, so let's delete the file
return fs.promises.unlink(filename);
} else {
// we need to write the file json back to xml back to the fs
const builder = new XMLBuilder({
attributeNamePrefix: '@_',
ignoreAttributes: false,
format: true,
indentBy: ' ',
});
// and then write that json back to xml and back to the fs
const xml = builder.build(cls) as string;
return fs.promises.writeFile(filename, xml);
}
}
}

// eslint-disable-next-line class-methods-use-this
public async init(): Promise<void> {
await this.maybeSubscribeLifecycleEvents();
Expand Down Expand Up @@ -418,10 +368,7 @@ export class SourceTracking extends AsyncCreatable {
await Promise.all(
filenames.map((filename) => {
if (sourceComponentByFileName.get(filename)?.type.id === 'customlabel') {
return SourceTracking.deleteCustomLabels(
filename,
changesToDelete.filter((change) => change.type.id === 'customlabel')
);
return deleteCustomLabels(filename, changesToDelete);
} else {
return fs.promises.unlink(filename);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import * as fs from 'fs';
import * as sinon from 'sinon';
import { SourceComponent } from '@salesforce/source-deploy-retrieve';
import { expect } from 'chai';
import { SourceTracking } from '../../src';
import { deleteCustomLabels } from '../../src/';

describe('SourceTracking', () => {
describe('deleteCustomLabels', () => {
const sandbox = sinon.createSandbox();
let fsReadStub: sinon.SinonStub;
let fsWriteStub: sinon.SinonStub;
Expand Down Expand Up @@ -54,21 +54,21 @@ describe('SourceTracking', () => {
});

describe('deleteCustomLabels', () => {
it('will delete a singular custom label from a file', async () => {
it('will delete a singular custom label from a file', () => {
const labels = [
{
type: { id: 'customlabel', name: 'CustomLabel' },
fullName: 'DeleteMe',
} as SourceComponent,
];

await SourceTracking.deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
void deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
expect(fsWriteStub.firstCall.args[1]).to.not.include('DeleteMe');
expect(fsWriteStub.firstCall.args[1]).to.include('KeepMe1');
expect(fsWriteStub.firstCall.args[1]).to.include('KeepMe2');
expect(fsReadStub.callCount).to.equal(1);
});
it('will delete a multiple custom labels from a file', async () => {
it('will delete a multiple custom labels from a file', () => {
const labels = [
{
type: { id: 'customlabel', name: 'CustomLabel' },
Expand All @@ -80,14 +80,14 @@ describe('SourceTracking', () => {
},
] as SourceComponent[];

await SourceTracking.deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
void deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
expect(fsWriteStub.firstCall.args[1]).to.include('DeleteMe');
expect(fsWriteStub.firstCall.args[1]).to.not.include('KeepMe1');
expect(fsWriteStub.firstCall.args[1]).to.not.include('KeepMe2');
expect(fsReadStub.callCount).to.equal(1);
});

it('will delete the file when everything is deleted', async () => {
it('will delete the file when everything is deleted', () => {
const labels = [
{
type: { id: 'customlabel', name: 'CustomLabel' },
Expand All @@ -103,12 +103,12 @@ describe('SourceTracking', () => {
},
] as SourceComponent[];

await SourceTracking.deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
void deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
expect(fsUnlinkStub.callCount).to.equal(1);
expect(fsReadStub.callCount).to.equal(1);
});

it('will delete the file when only a single label is present and deleted', async () => {
it('will delete the file when only a single label is present and deleted', () => {
fsReadStub.returns(
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">\n' +
Expand All @@ -128,23 +128,23 @@ describe('SourceTracking', () => {
},
] as SourceComponent[];

await SourceTracking.deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
void deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
expect(fsUnlinkStub.callCount).to.equal(1);
expect(fsReadStub.callCount).to.equal(1);
});

it('will not delete custom labels', async () => {
it('no custom labels, quick exit and do nothing', () => {
const labels = [
{
type: { id: 'apexclass', name: 'ApexClass' },
fullName: 'DeleteMe',
},
] as SourceComponent[];

await SourceTracking.deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
void deleteCustomLabels('labels/CustomLabels.labels-meta.xml', labels);
expect(fsUnlinkStub.callCount).to.equal(0);
expect(fsWriteStub.firstCall.args[1]).to.include('DeleteMe');
expect(fsReadStub.callCount).to.equal(1);
expect(fsWriteStub.callCount).to.equal(0);
expect(fsReadStub.callCount).to.equal(0);
});
});
});